AWS CLIのインストールなどはこちら
今回の構成は以下の通り
├── functions
│ └── lambda_function.py
└── template.yaml
実行するUserにはCloudformationのCreateChangeSet(変更)とExecuteChangeSet(実行)の許可が必要 ハマりどころなので注意!
サービスはcloudformationを選択 以下にチェック CreateChangeSet ExecuteChangeSet
JSONで表すと以下
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"cloudformation:CreateChangeSet",
"cloudformation:ExecuteChangeSet"
],
"Resource": "*"
}
]
}
パッケージングしたデータは一旦S3に保存されるのでバケットを作成する ※同じリージョンで同一の名前は作成出来ないので注意!
aws s3 mb s3://sam-sample-xxxxxxx
- 今回のTemplateの名前はtemplate.yaml
- Resources直下はLambdaの関数名(任意)
- Roleは必要な権限を(CreateChangeSetとExecuteChangeSetのポリシーを忘れずに)
- Runtimeは使用する言語
- HandlerはLambdaのhandlerをPathから指定
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Create Lambda function by using AWS SAM.
Resources:
SamSampleLambda:
Type: AWS::Serverless::Function
Properties:
Handler: functions/lambda_function.lambda_handler
Runtime: python3.6
Role: arn:aws:iam::111111111111:role/xxxxxxxx
Timeout: 30
Template、Package後のファイル名(packaged-template.yaml)、保存先のs3-bucket名を指定しPackage
aws cloudformation package \
--template-file template.yaml \
--s3-bucket sam-sample-xxxxxx \
--output-template-file packaged-template.yaml \
--profile xxxxx
パッケージングしたテンプレート(packaged-template.yaml)を用いて Cfn の実行
aws cloudformation deploy \
--template-file packaged-template.yaml \
--stack-name sam-sample-stack \
--capabilities CAPABILITY_IAM \
--profile xxxxx
成功するとLambdaに関数が作成されている
ネットなどにあまり情報が無くて困ったエラー(個人的に)
このエラーはCloudformation上にStackも作成されていない(はず)
An error occurred (AccessDenied) when calling the CreateChangeSet operation: User: arn:aws:iam::111111111111:user/user is not authorized to perform: cloudformation:CreateChangeSet on resource: arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:stack/sam-sample-stack/*
このエラーはCloudformation上にStackの作成は成功しロールの問題で失敗している
Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: User: arn:aws:iam::111111111111:user/username is not authorized to perform: cloudformation:CreateChangeSet on resource: arn:aws:cloudformation:ap-northeast-1:aws:transform/Serverless-2016-10-31
- 上記に説明したUserにCreateChangeSetとExecuteChangeSetの権限を付与
- ロールにLamdaのアクセス権限があるか確認
- ロールが存在するものか確認
Failed to create the changeset: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Invalid template property or properties XXXXXX
XXXXXXの部分がヒント
こちら拝見し理解したところをメモにしています AWS Serverless Application Model 入門ハンズオンシリーズ(http://www.ketancho.net/entry/aws_sam)
ちょうど不明だった箇所が解消されました。ありがとうございます。
(CloudFrontの権限を付与していなかったので、、)
サーバーレスアプリケーション開発ガイドにも、CloudFrontの権限には言及していませんでした。(まだ、途中ですが、、)