はじめに
今回はAWS CloudFormationを使用するうえで便利なpackageコマンドについてまとめてみました。
概要
aws cloudformation packageコマンドは、CloudFormationテンプレート内のローカルファイル参照をS3参照に変換するためのコマンドです。
以下のようなケースでよく使用されます:
・ネストスタックのテンプレート(TemplateURL)
・Lambdaのコード(zipやディレクトリ)
・Step Functions定義
・AppSyncスキーマ
内部処理
packageコマンドは内部で以下の処理をおこないます。
- テンプレート内のローカルパスを検出
- 対象ファイルをS3にアップロード
- テンプレート内のパスをS3 URLに書き換え
- 新しいテンプレートを出力
Lambda関数の例
Code:にローカルパスを直接書ける。
Resources:
MyFunction:
Type: AWS::Lambda::Function
Properties:
Code: ./lambda
Handler: index.handler
Runtime: nodejs20.x
packageコマンド実行(自動でzip化 & S3アップロード)
aws cloudformation package \
--template-file before-template.yaml \
--s3-bucket my-bucket \
--output-template-file after-template.yaml
package後(S3参照に自動変換されている)
Resources:
MyFunction:
Type: AWS::Lambda::Function
Properties:
Code:
S3Bucket: my-bucket
S3Key: 1a2b3c4d5e6f.zip
Handler: index.handler
Runtime: nodejs20.x
ネストスタックの例
TemplateURL:にローカルパスを直接書ける。
Resources:
ChildStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: ./child.yaml
packageコマンド実行
aws cloudformation package \
--template-file before-template.yaml \
--s3-bucket my-bucket \
--output-template-file after-template.yaml
package後(S3参照に自動変換されている)
Resources:
ChildStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://s3.amazonaws.com/my-bucket/abc123.yaml
deployコマンドとの関係
通常はスクリプトなどに記述し、セットで使います。
aws cloudformation package \
--template-file template.yaml \
--s3-bucket my-bucket \
--output-template-file packaged.yaml
aws cloudformation deploy \
--template-file packaged.yaml \
--stack-name my-stack
※deployコマンド単体でも--s3-bucketオプションを指定すれば内部でpackageコマンドと似た処理が実行されますが、packageコマンドを明示的に使用する方がおすすめです。
注意点
packageコマンドを使用する際の注意点をいくつかまとめてみました。
① S3バケットは事前作成必須
packageコマンドは新規バケットを作成しないため、事前の用意が必要です。
② 差分が出ない
ローカルファイルが変わってもS3キーが同じ場合、差分が検知されません。
対策:
・--force-uploadオプションを使う
・ファイル名を変える
・ハッシュ付きキーを使う