View a markdown version of this page

Cargo Lambda에서를 사용하여 Rust Lambda 함수 빌드 AWS SAM - AWS Serverless Application Model

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Cargo Lambda에서를 사용하여 Rust Lambda 함수 빌드 AWS SAM

Rust AWS Lambda 함수와 함께 AWS Serverless Application Model 명령줄 인터페이스(AWS SAM CLI)를 사용합니다.

사전 조건

Rust 언어

Rust를 설치하려면 Rust 언어 웹 사이트Rust 설치 섹션을 참조하세요.

Cargo Lambda

AWS SAMCLI에는 Cargo의 하위 명령인 Cargo Lambda의 설치가 필요합니다. 설치에 대한 지침은 Cargo Lambda 설명서설치 섹션을 참조하세요.

Docker

Rust Lambda 함수를 빌드하고 테스트하려면 Docker가 필요합니다. 설치 지침은 Docker 설치을 확인하세요.

Rust Lambda 함수와 함께 AWS SAM 사용하도록 구성

1단계: AWS SAM 템플릿 구성

다음을 사용하여 AWS SAM 템플릿을 구성합니다.

  • 바이너리 - 선택 사항. 단일 Cargo 패키지가 둘 이상의 바이너리를 정의할 때를 지정하여이 함수에 대해 빌드할 바이너리를 식별합니다. 워크Cargo스페이스와 같이 각 함수가 자체 Cargo 패키지인 경우이 속성이 필요하지 않습니다.

  • BuildMethodrust-cargolambda.

  • CodeUriCargo.toml 파일에 대한 경로

  • 핸들러bootstrap.

  • 런타임provided.al2023.

사용자 지정 런타임에 대한 자세한 내용은 AWS Lambda 개발자 안내서사용자 지정 AWS Lambda 런타임을 참조하세요.

다음은 구성된 AWS SAM 템플릿의 예입니다.

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 ... Resources: MyFunction: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda BuildProperties: function_a Properties: CodeUri: ./rust_app Handler: bootstrap Runtime: provided.al2023 ...

2단계: Rust Lambda 함수와 함께 AWS SAMCLI 사용

AWS SAM 템플릿과 함께 명령을 AWS SAM CLI 사용합니다. 자세한 내용은 AWS SAM CLI 단원을 참조하십시오.

예제

Hello World 예제

이 예제에서는 Rust를 런타임으로 사용하여 샘플 Hello World 애플리케이션을 빌드합니다.

먼저 sam init를 사용하여 새 서버리스 애플리케이션을 초기화합니다. 대화형 흐름 중에 Hello World 애플리케이션을 선택하고 Rust 런타임을 선택합니다.

$ sam init ... Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 Choose an AWS Quick Start application template 1 - Hello World Example 2 - Multi-step workflow 3 - Serverless API ... Template: 1 Use the most popular runtime and package type? (Python and zip) [y/N]: ENTER Which runtime would you like to use? 1 - dotnet8 2 - dotnet6 3 - go (provided.al2) ... 18 - python3.11 19 - python3.10 20 - ruby4.0 21 - ruby3.3 22 - ruby3.2 23 - rust (provided.al2) 24 - rust (provided.al2023) Runtime: 24 Based on your selections, the only Package type available is Zip. We will proceed to selecting the Package type as Zip. Based on your selections, the only dependency manager available is cargo. We will proceed copying the template using cargo. Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: ENTER Would you like to enable monitoring using CloudWatch Application Insights? For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER Project name [sam-app]: hello-rust ----------------------- Generating application: ----------------------- Name: hello-rust Runtime: rust (provided.al2023) Architectures: x86_64 Dependency Manager: cargo Application Template: hello-world Output Directory: . Configuration file: hello-rust/samconfig.toml Next steps can be found in the README file at hello-rust/README.md Commands you can use next ========================= [*] Create pipeline: cd hello-rust && sam pipeline init --bootstrap [*] Validate SAM template: cd hello-rust && sam validate [*] Test Function in the Cloud: cd hello-rust && sam sync --stack-name {stack-name} --watch

Hello World 애플리케이션의 구조는 다음과 같습니다.

hello-rust
├── README.md
├── events
│   └── event.json
├── rust_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── samconfig.toml
└── template.yaml

AWS SAM 템플릿에서 Rust 함수는 다음과 같이 정의됩니다.

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 ... Resources: HelloWorldFunction: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda Properties: CodeUri: ./rust_app Handler: bootstrap Runtime: provided.al2023 Architectures: - x86_64 Events: HelloWorld: Type: Api Properties: Path: /hello Method: get

다음으로 애플리케이션을 빌드하고 배포를 준비하기 위해 sam build를 실행합니다. AWS SAMCLI는 .aws-sam 디렉터리를 생성하고 여기에 빌드 아티팩트를 구성합니다. 함수는 Cargo Lambda를 사용하여 빌드되고 .aws-sam/build/HelloWorldFunction/bootstrap에 실행 가능한 바이너리로 저장됩니다.

참고

MacOS 에서 sam local invoke 명령을 실행하려는 경우 간접적으로 호출하기 전에 다른 함수를 빌드해야 합니다. 이렇게 하려면 다음 명령을 사용합니다.

  • SAM_BUILD_MODE=debug sam build

이 명령은 로컬 테스트를 수행하는 경우에만 필요합니다. 배포를 위해 빌드할 때는 권장되지 않습니다.

hello-rust$ sam build Starting Build use cache Cache is invalid, running build and copying resources for following functions (HelloWorldFunction) Building codeuri: /Users/.../hello-rust/rust_app runtime: provided.al2023 metadata: {'BuildMethod': 'rust-cargolambda'} architecture: x86_64 functions: HelloWorldFunction Running RustCargoLambdaBuilder:CargoLambdaBuild Running RustCargoLambdaBuilder:RustCopyAndRename Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Validate SAM template: sam validate [*] Invoke Function: sam local invoke [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch [*] Deploy: sam deploy --guided

다음으로 sam deploy --guided를 사용하여 애플리케이션을 배포합니다.

hello-rust$ sam deploy --guided Configuring SAM deploy ====================== Looking for config file [samconfig.toml] : Found Reading default arguments : Success Setting default arguments for 'sam deploy' ========================================= Stack Name [hello-rust]: ENTER AWS Region [us-west-2]: ENTER #Shows you resources changes to be deployed and require a 'Y' to initiate deploy Confirm changes before deploy [Y/n]: ENTER #SAM needs permission to be able to create roles to connect to the resources in your template Allow SAM CLI IAM role creation [Y/n]: ENTER #Preserves the state of previously provisioned resources when an operation fails Disable rollback [y/N]: ENTER HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y Save arguments to configuration file [Y/n]: ENTER SAM configuration file [samconfig.toml]: ENTER SAM configuration environment [default]: ENTER Looking for resources needed for deployment: ... Uploading to hello-rust/56ba6585d80577dd82a7eaaee5945c0b 817973 / 817973 (100.00%) Deploying with following values =============================== Stack name : hello-rust Region : us-west-2 Confirm changeset : True Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr Capabilities : ["CAPABILITY_IAM"] Parameter overrides : {} Signing Profiles : {} Initiating deployment ===================== Uploading to hello-rust/a4fc54cb6ab75dd0129e4cdb564b5e89.template 1239 / 1239 (100.00%) Waiting for changeset to be created.. CloudFormation stack changeset --------------------------------------------------------------------------------------------------------- Operation LogicalResourceId ResourceType Replacement --------------------------------------------------------------------------------------------------------- + Add HelloWorldFunctionHelloW AWS::Lambda::Permission N/A orldPermissionProd ... --------------------------------------------------------------------------------------------------------- Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1681427201/f0ef1563-5ab6-4b07-9361-864ca3de6ad6 Previewing CloudFormation changeset before deployment ====================================================== Deploy this changeset? [y/N]: y 2023-04-13 13:07:17 - Waiting for stack create/update to complete CloudFormation events from stack operations (refresh every 5.0 seconds) --------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason --------------------------------------------------------------------------------------------------------- CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole - CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole Resource creation ... --------------------------------------------------------------------------------------------------------- CloudFormation outputs from deployed stack --------------------------------------------------------------------------------------------------------- Outputs --------------------------------------------------------------------------------------------------------- Key HelloWorldFunctionIamRole Description Implicit IAM Role created for Hello World function Value arn:aws:iam::012345678910:role/hello-rust-HelloWorldFunctionRole-10II2P13AUDUY Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:us-west-2:012345678910:function:hello-rust-HelloWorldFunction- yk4HzGzYeZBj --------------------------------------------------------------------------------------------------------- Successfully created/updated stack - hello-rust in us-west-2

테스트를 위해 API 엔드포인트를 사용하여 Lambda 함수를 호출할 수 있습니다.

$ curl https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/ Hello World!%

함수를 로컬에서 테스트하려면 먼저 함수의 Architectures 속성이 로컬 시스템과 일치하는지 확인합니다.

... Resources: HelloWorldFunction: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Metadata: BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda Properties: CodeUri: ./rust_app # Points to dir of Cargo.toml Handler: bootstrap # Do not change, as this is the default executable name produced by Cargo Lambda Runtime: provided.al2023 Architectures: - arm64 ...

이 예제에서는 아키텍처를 x86_64에서 arm64로 수정했으므로 빌드 아티팩트를 업데이트하기 위해 sam build를 실행합니다. 그런 다음 sam local invoke를 실행하여 함수를 로컬에서 호출합니다.

hello-rust$ sam local invoke Invoking bootstrap (provided.al2023) Local image was not found. Removing rapid images for repo public.ecr.aws/sam/emulation-provided.al2023 Building image..................................................................................................................................... Using local image: public.ecr.aws/lambda/provided:al2023-rapid-arm64. Mounting /Users/.../hello-rust/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container START RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Version: $LATEST {"statusCode":200,"body":"Hello World!"}END RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 REPORT RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Init Duration: 0.68 ms Duration: 130.63 ms Billed Duration: 131 ms Memory Size: 128 MB Max Memory Used: 128 MB

단일 Lambda 함수 프로젝트

다음은 Rust Lambda 함수 하나를 포함하는 서버리스 애플리케이션의 예입니다.

프로젝트 디렉터리 구조:

.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── template.yaml

AWS SAM 템플릿:

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 ... Resources: MyFunction: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda Properties: CodeUri: ./ Handler: bootstrap Runtime: provided.al2023 ...

다중 Lambda 함수 프로젝트

다음은 Cargo 워크스페이스로 구성된 여러 Rust Lambda 함수를 포함하는 서버리스 애플리케이션의 예입니다.

여러 Rust Lambda 함수가 있는 애플리케이션에는 Cargo 워크스페이스를 사용하는 것이 좋습니다. 각 함수는 자체 패키지이므로 함수는 라이브러리 패키지를 통해 공통 코드를 공유하면서 독립적인 종속성을 선언할 수 있습니다. 각 패키지는 패키지 이름의 단일 바이너리를 생성하므로 Binary 빌드 속성을 설정할 필요가 없습니다.

프로젝트 디렉터리 구조:

.
├── Cargo.lock
├── Cargo.toml
├── function_a
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── function_b
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── template.yaml

프로젝트의 루트에 있는 Workspace Cargo.toml 파일:

[workspace] resolver = "2" members = [ "function_a", "function_b", ] [workspace.dependencies] lambda_runtime = "0.13" serde = { version = "1", features = ["derive"] } tokio = { version = "1", features = ["macros", "rt"] }

Cargo.toml와 같은 각 함수에 대한 파일function_a/Cargo.toml:

[package] name = "function_a" version = "0.1.0" edition = "2021" [dependencies] lambda_runtime = { workspace = true } serde = { workspace = true } tokio = { workspace = true }

AWS SAM 템플릿. 각 함수CodeUri의는 해당 함수의 패키지 디렉터리를 가리킵니다.

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 ... Resources: FunctionA: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda Properties: CodeUri: ./function_a Handler: bootstrap Runtime: provided.al2023 FunctionB: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda Properties: CodeUri: ./function_b Handler: bootstrap Runtime: provided.al2023
참고

는 AWS SAM CLI 워크스페이스의 모든 함수를 워크스페이스의 공유 target 디렉터리에 빌드하므로는 각 함수에 대해 한 번 대신 한 번 공유 종속성을 Cargo컴파일합니다. 이 동작에는 버전 1.165.0 이상이 필요합니다 AWS SAM CLI. 이전 버전에서는 각 함수가 자체 target 디렉터리에 구축되고 모든 함수에 대해 전체 종속성 트리가 다시 컴파일되므로 함수를 추가할 때 빌드 속도가 느려집니다.

각 함수 패키지에 고유한 이진 이름을 지정합니다. 패키지 이름은 워크스페이스 내에서 고유하므로 기본 바이너리 이름은 이미 고유합니다. [[bin]] 섹션으로 바이너리 이름을 재정의하는 경우 두 패키지에 동일한 바이너리 이름을 지정하지 마십시오. 공유 target 디렉터리의 동일한 경로로 컴파일되고 서로 덮어씁니다. 는 이를 감지하면 경고를 AWS SAM CLI 기록합니다.

또는 단일 패키지가 여러 바이너리를 정의할 수 있습니다. 이 경우 Binary 빌드 속성을 사용하여 각 함수의 바이너리를 선택합니다.

Resources: FunctionA: Type: AWS::Serverless::Function Metadata: BuildMethod: rust-cargolambda BuildProperties: Binary: function_a Properties: CodeUri: ./ Handler: bootstrap Runtime: provided.al2023

에서 Rust 빌드 최적화 GitHub Actions

Rust 빌드는 컴퓨팅 집약적이며 지속적 통합 실행기는 컴파일된 아티팩트 없이 시작됩니다. 와 같이 대규모 종속성을 공유하는 여러 함수가 있는 애플리케이션은 대부분의 빌드 시간을 동일한 종속성을 컴파일하는 데 소비할 AWS SDK수 있습니다. 다음 방법은의 빌드 시간을 줄입니다GitHub Actions.

워크스페이스에 버전 1.165.0 이상 사용 AWS SAM CLI

버전 1.165.0 이상은 Cargo 워크스페이스의 모든 멤버를 워크스페이스의 공유 target 디렉터리에 빌드하므로 공유 종속성은 각 함수에 대해 한 번이 아닌 빌드당 한 번 컴파일됩니다. 빌드가 자동으로 느린 동작으로 돌아가지 않도록를 설치할 AWS SAM CLI 때 최소 버전을 지정합니다.

Cargo 레지스트리 및 target 디렉터리 캐시

실행 사이에 Cargo 레지스트리(~/.cargo/registry~/.cargo/git/db)와 워크스페이스 target 디렉터리를 캐시하여 변경되지 않은 종속성이 다시 컴파일되는 대신 복원되도록 합니다. 각 컴파일 대상에 대해 별도의 캐시를 사용합니다. 에 대한 릴리스 아티팩트를 교차 컴파일하는 작업은에 대해 기본적으로 컴파일되는 작업과 다른 아티팩트를 arm64 생성x86_64하므로 공유 캐시가 일치하지 않습니다.

캐시 키에 빌드 설정 포함

Cargo 에는 컴파일된 아티팩트를 재사용할 수 있는지 여부를 결정하는 데 사용하는 지문codegen-unitsopt-level 및와 같은 설정이 포함되어 있습니다. 캐시 키를 변경하지 않고 워크스페이스 Cargo.toml 파일의 [profile.release] 섹션을 변경하면 캐시가 복원되지만 모든 상자는 어쨌든 다시 컴파일됩니다. 프로필 설정을 변경하면 새 캐시가 시작되도록 캐시 키에 워크스페이스 Cargo.toml 파일의 해시를 포함합니다.

Cargo.lock 파일 커밋

Lambda 함수는 실행 파일이므로 Cargo.lock 파일을 커밋합니다. 이렇게 하면 복제 가능한 빌드와 종속성이 변경될 때만 변경되는 안정적인 캐시 키가 제공됩니다.

빌드 시간 및 콜드 스타트에 대한 릴리스 프로파일 조정

함수 코드는 종속성보다 자주 변경되므로 실행할 때마다 다시 컴파일됩니다. 기본 릴리스 프로파일은 많은 Lambda 함수가 필요하지 않은 런타임 처리량을 최적화합니다. 크기를 최적화하면 더 작은 바이너리가 생성되므로 콜드 스타트 시간에도 도움이 되며 코드 생성 단위 수를 늘리면 컴파일 중에 병렬 처리가 증가합니다. 컴파일 속도가 느려지므로 링크 시간 최적화(lto)는 비활성화된 상태로 둡니다. 워크스페이스 Cargo.toml 파일에 다음을 추가합니다.

[profile.release] opt-level = "s" codegen-units = 256 lto = false strip = true

자체 애플리케이션에 미치는 영향을 측정합니다. 이러한 설정은 빌드 시간 및 바이너리 크기에 대해 소량의 런타임 성능을 보상합니다.

중복 워크플로 실행 방지

pushpull_request 이벤트 모두에서 실행되는 워크플로는 동일한 커밋에 대해 두 번 실행됩니다. GitHub Actions 캐시는 브랜치 및 풀 요청에 의해 범위가 지정되므로 두 개는 서로 다른 캐시 범위에 대한 쓰기를 실행하고 다른 캐시를 재사용하지 않습니다. 하나의 실행만 각 커밋을 빌드하도록 헤드 커밋에 키가 지정된 동시성 그룹을 사용합니다.

다음 워크플로는에 대한 Rust Lambda 함수의 Cargo 워크스페이스를 빌드arm64하고 이전 사례를 적용합니다.

name: Build on: push: branches: [main] pull_request: # Collapse the push and pull_request runs for the same commit into a single run. concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.head.sha || github.sha }} cancel-in-progress: true jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - uses: dtolnay/rust-toolchain@stable with: targets: aarch64-unknown-linux-gnu # Cache the Cargo registry and the workspace target directory. The key covers # the compilation target, Cargo.lock, and the workspace Cargo.toml, so that # changing a dependency or a release profile setting starts a new cache # instead of restoring one whose artifacts Cargo discards. - uses: actions/cache@v4 with: path: | ~/.cargo/registry/index ~/.cargo/registry/cache ~/.cargo/git/db target key: cargo-arm64-${{ hashFiles('Cargo.lock', 'Cargo.toml') }} restore-keys: | cargo-arm64- - name: Install build tools run: pip install cargo-lambda 'aws-sam-cli>=1.165.0' - name: Build run: sam build

restore-keys 항목을 사용하면 키가 정확히 일치하지 않을 때 가장 최근 캐시에서 실행을 시작할 수 있으므로 종속성 변경은 모든 항목을 다시 컴파일하는 대신 변경되지 않은 상자를 재사용합니다.