0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AWS CloudFormation】packageコマンドについて

0
Posted at

はじめに

今回はAWS CloudFormationを使用するうえで便利なpackageコマンドについてまとめてみました。

概要

aws cloudformation packageコマンドは、CloudFormationテンプレート内のローカルファイル参照をS3参照に変換するためのコマンドです。

以下のようなケースでよく使用されます:
・ネストスタックのテンプレート(TemplateURL)
・Lambdaのコード(zipやディレクトリ)
・Step Functions定義
・AppSyncスキーマ

内部処理

packageコマンドは内部で以下の処理をおこないます。

  1. テンプレート内のローカルパスを検出
  2. 対象ファイルをS3にアップロード
  3. テンプレート内のパスをS3 URLに書き換え
  4. 新しいテンプレートを出力

Lambda関数の例

Code:にローカルパスを直接書ける。

before-template.yaml
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code: ./lambda
      Handler: index.handler
      Runtime: nodejs20.x

packageコマンド実行(自動でzip化 & S3アップロード)

zsh
aws cloudformation package \
  --template-file before-template.yaml \
  --s3-bucket my-bucket \
  --output-template-file after-template.yaml

package後(S3参照に自動変換されている)

after-template.yaml
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        S3Bucket: my-bucket
        S3Key: 1a2b3c4d5e6f.zip
      Handler: index.handler
      Runtime: nodejs20.x

ネストスタックの例

TemplateURL:にローカルパスを直接書ける。

before-template.yaml
Resources:
  ChildStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: ./child.yaml

packageコマンド実行

zsh
aws cloudformation package \
  --template-file before-template.yaml \
  --s3-bucket my-bucket \
  --output-template-file after-template.yaml

package後(S3参照に自動変換されている)

after-template.yaml
Resources:
  ChildStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://s3.amazonaws.com/my-bucket/abc123.yaml

deployコマンドとの関係

通常はスクリプトなどに記述し、セットで使います。

sh
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オプションを使う
・ファイル名を変える
・ハッシュ付きキーを使う

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?