Dev ContainersでAWS SAMの環境を構築する
Visual Studio CodeのDev Containersを利用すると、ローカルPCの環境を汚すことなく、アプリケーション等の実行環境を用意することができます。
今回は、AWSのサーバーレスアプリケーションの構築・実行をサポートする、AWS Serverless Application Model (AWS SAM) の実行環境をDev Containers上に構築してみます。
目次
はじめに
こんにちは。
クラウドソリューション第二グループのimai.kです。
みなさんは、AWS SAMを使用してLambda等のリソースを管理し、サーバーレスなアプリケーションを作りたいと思ったことがあると思います。
今回は、そんな気持ちが生まれたため、やってみたいと思います。
※なお、Mac(M1)で試しています。
準備
環境を構築するにあたり、DockerとVisual Studio Codeが必要となります。
ご利用の環境に合わせてインストールを行ってください。
アプリケーションがインストールできたら、任意のディレクトリに「.devcontainer」ディレクトリを作成し、devcontainer.jsonを作成しましょう。
devcontainer.jsonの中身は以下の通りです。
{
"image": "mcr.microsoft.com/devcontainers/typescript-node:1-20-bookworm",
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
"features": {
"ghcr.io/devcontainers/features/docker-in-docker:2.11.0": {
"enableNonRootDocker": "true",
"moby": "true"
},
"ghcr.io/devcontainers/features/aws-cli:1": {},
"ghcr.io/customink/codespaces-features/sam-cli:1": {},
"ghcr.io/devcontainers-contrib/features/aws-cdk:2": {}
}
}
VScodeでDev Containerを起動
次に、.devcontainerを配置したディレクトリ/プロジェクトをVisual Studio Codeで開きましょう。
以下のように「Reopen in Container」と表示されたら、ボタンをクリックして Dev Containerを起動しましょう。
Dev Containerが起動したら以下のようにターミナルが開くと思います。
AWS SAMのサンプルプロジェクト作成
ここまでで、AWS SAMが実行できる環境が組み上がったと思います。
以下の要領で、AWS SAMのサンプルプロジェクトを作成してみます。
node ➜ /workspaces/test $ sam init You can preselect a particular runtime or package type when using the `sam init` experience. Call `sam init --help` to learn more. 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 - Data processing 3 - Hello World Example with Powertools for AWS Lambda 4 - Multi-step workflow 5 - Scheduled task 6 - Standalone function 7 - Serverless API 8 - Infrastructure event management 9 - Lambda Response Streaming 10 - Serverless Connector Hello World Example 11 - Multi-step workflow with Connectors 12 - GraphQLApi Hello World Example 13 - Full Stack 14 - Lambda EFS example 15 - DynamoDB Example 16 - Machine Learning Template: 1 Use the most popular runtime and package type? (Python and zip) [y/N]: N Which runtime would you like to use? 1 - aot.dotnet7 (provided.al2) 2 - dotnet8 3 - dotnet6 4 - go (provided.al2) 5 - go (provided.al2023) 6 - graalvm.java11 (provided.al2) 7 - graalvm.java17 (provided.al2) 8 - java21 9 - java17 10 - java11 11 - java8.al2 12 - nodejs20.x 13 - nodejs18.x 14 - nodejs16.x 15 - python3.9 16 - python3.8 17 - python3.12 18 - python3.11 19 - python3.10 20 - ruby3.3 21 - ruby3.2 22 - rust (provided.al2) 23 - rust (provided.al2023) Runtime: 12 What package type would you like to use? 1 - Zip 2 - Image Package type: 1 Based on your selections, the only dependency manager available is npm. We will proceed copying the template using npm. Select your starter template 1 - Hello World Example 2 - Hello World Example TypeScript Template: 2 Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: N 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]: N Would you like to set Structured Logging in JSON format on your Lambda functions? [y/N]: N Project name [sam-app]: Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment) ----------------------- Generating application: ----------------------- Name: sam-app Runtime: nodejs20.x Architectures: x86_64 Dependency Manager: npm Application Template: hello-world-typescript Output Directory: . Configuration file: sam-app/samconfig.toml Next steps can be found in the README file at sam-app/README.md
Commands you can use next ========================= [*] Create pipeline: cd sam-app && sam pipeline init --bootstrap [*] Validate SAM template: cd sam-app && sam validate [*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch
関数のローカル起動
それでは、作成したサンプルプロジェクトの関数をローカル起動して、動作確認してみましょう。
まずは、サンプルプロジェクトのディレクトリに移動します。
node ➜ /workspaces/test $ cd sam-app
次に「sam build」でビルドを行います。
node ➜ /workspaces/test/sam-app $ sam build
Starting Build use cache
Manifest file is changed (new hash: 3a55b648027d1145164f225fad481127) or dependency folder (.aws-sam/deps/5cc8dceb-3435-4176-ae54-9bafe46a45de) is missing for (HelloWorldFunction), downloading dependencies and
copying/building source
Building codeuri: /workspaces/test/sam-app/hello-world runtime: nodejs20.x metadata: {'BuildMethod': 'esbuild', 'BuildProperties': {'Minify': True, 'Target': 'es2020', 'Sourcemap': True, 'EntryPoints':
['app.ts']}} architecture: x86_64 functions: HelloWorldFunction
Running NodejsNpmEsbuildBuilder:CopySource
Running NodejsNpmEsbuildBuilder:NpmInstall
Running NodejsNpmEsbuildBuilder:EsbuildBundle
Running NodejsNpmEsbuildBuilder:CleanUp
Running NodejsNpmEsbuildBuilder:MoveDependencies
Sourcemap set without --enable-source-maps, adding --enable-source-maps to function HelloWorldFunction NODE_OPTIONS
You are using source maps, note that this comes with a performance hit! Set Sourcemap to false and remove NODE_OPTIONS: --enable-source-maps to disable source maps.
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 local invoke」で、関数をローカル起動します。
以下のような結果が得られればOKです。
node ➜ /workspaces/test/sam-app $ sam local invoke
No current session found, using default AWS::AccountId
Invoking app.lambdaHandler (nodejs20.x)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-nodejs20.x
Building image........................................................................................................................................................................................................................................................................
Using local image: public.ecr.aws/lambda/nodejs:20-rapid-x86_64.
Mounting /workspaces/test/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: b0613233-1d2f-42cb-ab27-6af9ee52662a Version: $LATEST
END RequestId: 2dcac48f-1d10-46b2-9b1c-c2e7767aa6ba
REPORT RequestId: 2dcac48f-1d10-46b2-9b1c-c2e7767aa6ba Init Duration: 1.09 ms Duration: 1159.02 ms Billed Duration: 1160 ms Memory Size: 128 MB Max Memory Used: 128 MB
{"statusCode": 200, "body": "{\"message\":\"hello world\"}"}
さいごに
以上のように、かなり簡単にAWS SAMの実行環境が構築できたと思います。
サーバーレスな開発を行う際の選択肢の一つになれば良いなと感じます。
以上です。