この件、SAMでも試してみました。
SAMが対応しているか見てみた
個人的に待ちに待った対応だったので、早速調べてみたら、嬉しいことにSAM側も既に対応されていました。
該当のCommitはこれでしょうか。
該当のCommitが含まれている、aws-sam-translatorの 1.6.0
が2018/6/12
にリリースなので、少し前から対応されていたようです。最新は 1.6.1
が昨日2018/6/29
にリリースされています。
数日前に入れ直した手元の環境も 1.6.0で対応済みでした。
$ pip show aws-sam-translator Name: aws-sam-translator Version: 1.6.0 Summary: AWS SAM Translator is a library that transform SAM templates into AWS CloudFormation templates Home-page: https://github.com/awslabs/serverless-application-model Author: Amazon Web Services Author-email: aws-sam-developers@amazon.com License: Apache License 2.0 Location: /home/yomon8/.local/lib/python2.7/site-packages Requires: boto3, jsonschema, enum34, six Required-by: aws-sam-cli
動かしてみる
Exampleがあるそうなので、早速動かしてみました。まずはリポジトリをダウンロードして該当のExampleがあるディレクトリに移動します。
$ git clone https://github.com/awslabs/serverless-application-model.git $ cd serverless-application-model/examples/2016-10-31/sqs/
ExampleのLamdaは受け取ったメッセージをログ出力するだけの単純なものです。
async function handler (event, context) { // TODO: Handle message... const records = event.Records console.log(records) return {} } module.exports.handler = handler
このLambdaのEventsの項目に Type:SQS
が設定されています。
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: Example of processing messages on an SQS queue with Lambda Resources: MySQSQueueFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./index.js Handler: index.handler Runtime: nodejs8.10 Events: MySQSEvent: Type: SQS Properties: Queue: !GetAtt MySqsQueue.Arn BatchSize: 10 MySqsQueue: Type: AWS::SQS::Queue
READMEに沿って以下のコマンドでデプロイします。YOUR_S3_ARTIFACTS_BUCKET
の変数には自分の用意したバケット名を入れます。
$ YOUR_S3_ARTIFACTS_BUCKET='YOUR_S3_ARTIFACTS_BUCKET'; \ sam package --s3-bucket $YOUR_S3_ARTIFACTS_BUCKET --template-file ./template.yaml --output-template-file ./packaged.yaml $ sam deploy --template-file ./packaged.yaml --stack-name lambda-sqs-processor --capabilities CAPABILITY_IAM
ManagementコンソールでもSQSがイベントソースになっていること確認できます。
適当なJSON形式のメッセージ送信してみます。
$ aws sqs send-message --queue-url https://sqs.ap-northeast-1.amazonaws.com/123456789012/lambda-sqs-processor-MySqsQueue-A5JVJF7JR1FP --message-body "{\"Message\":\"Test Message\"}"
SQSのキューを見ると既にキューは空で、Lambdaが動いて送信したメッセージが表示されました。