CloudFormation のパラメータを JSON ファイルで簡単に渡す方法
こんにちは、インフラエンジニアの土肥です。
CloudFormarion でCLIからスタックを作成する時には以下のようにパラメータを渡します。
$ aws cloudformation deploy \
--template-file template.yml \
--stack-name sample-stack \
--parameter-overrides ParameterKey=Param1,ParameterValue=value1 ....--parameter-overridesの部分が非常に長いし、パラメータは外部ファイルに切り出したいですよね。
今までは以下のようにシェルコマンドを使って対応することが多かったかと思います。
$ aws cloudformation deploy \
--template-file template.yml \
--stack-name sample-stack \
--parameter-overrides `cat <parameter_file>` or `jq <jq_filter> <parameter_file>`AWS CLI v2から
--parameter-overridesが複数のフォーマットのJSONファイルに対応しました。
今まで冗長だったり、シェルコマンドに頼らざるを得なかったパラメーターの受け渡しですが以下の記述で実行可能になりました。
$ aws cloudformation deploy \
--template-file template.yml \
--stack-name sample-stack \
--parameter-overrides "file://<parameter_file>"パラメータのフォーマット
渡せるJSONの書式には3つのパターンがあります。
create-stackやcreate-change-setで使い回す場合を考えると、CloudFormation like formatが良いのかなと思います。
Original format
[
"Key1=Value1",
"Key2=Value2"
]CloudFormation like format
create-stackやcreate-change-setの—parametersオプションでパラメータを渡す場合はこの形でないといけません。
[
{
"ParameterKey": "Key1",
"ParameterValue": "Value1"
},
{
"ParameterKey": "Key2",
"ParameterValue": "Value2"
}
]ParameterKeyとParameterValueのキーは変更すると読み込めなくなるので注意してください。
Only ParameterKey and ParameterValue are expected keys, command will throw an exception if receives unexpected keys (e.g. UsePreviousValue or ResolvedValue).
https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy/index.html
CodePipeline like format
公式ドキュメントでは一番外側が[]になっておりますが、それだとうまく読み込んでくれませんでしたので{}に変更しております。
{
"Parameters": {
"Key1": "Value1",
"Key2": "Value2"
}
}実際にやってみた
S3バケットを作成するテンプレートです。
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
Project:
Type: String
TagKey:
Type: String
TagValue:
Type: String
Resources:
##----------------------------------##
# S3 Bucket
##----------------------------------##
Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub ${Project}-sample-bucket
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: True
BlockPublicPolicy: True
IgnorePublicAcls: True
RestrictPublicBuckets: True
Tags:
- Key: !Ref TagKey
Value: !Ref TagValue3つのパラメータをCodePipeline like formatで渡してスタックを作成します。
[
{
"ParameterKey": "Project",
"ParameterValue": "aitp-tech-blog"
},
{
"ParameterKey": "TagKey",
"ParameterValue": "key"
},
{
"ParameterKey": "TagValue",
"ParameterValue": "value"
}
]無事スタックが作成されたことが確認できます。
$ aws cloudformation deploy \
--template-file ./cloudformation-template.yml \
--stack-name param-sample \
--parameter-overrides "file://params/param3.json"
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - param-sample最後に
CLI v1の時に描いたスクリプトなどは、かなりスッキリ書き直せますのでお試しを!
参考リンク
https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy/index.html