公式ドキュメントに記載された AWS CLI のコマンドが「Template format error」で失敗するときの対処方法

2022.03.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

困っていた内容

AWS公式ドキュメントを参考に ECS に CloudWatch エージェント をデプロイしています。ドキュメントの通りにコマンドを実行するとTemplate format error: unsupported structureというエラーが表示されます。 実行するコマンドは変えてないので、特にエラーにはならないはずですが、対処方法を教えてください。

Amazon ECS で EC2 インスタンスレベルのメトリクスを収集するための CloudWatch エージェントのデプロイ - Amazon CloudWatch

$ aws cloudformation create-stack --stack-name CWAgentECS-${ClusterName}-${Region} \
    --template-body https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json \
    --parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
                 ParameterKey=CreateIAMRoles,ParameterValue=True \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${Region}

An error occurred (ValidationError) when calling the CreateStack operation: Template format error: unsupported structure.

どう対応すればいいの?

テンプレートファイルをダウンロードし--template-bodyの値を、ダウンロードしたファイルを指定する値に置き換えて、再度実行してください。

# 変更前
$ aws cloudformation create-stack --stack-name CWAgentECS-${ClusterName}-${Region} \
    --template-body https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json \
    --parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
                 ParameterKey=CreateIAMRoles,ParameterValue=True \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${Region}
    
# 変更後
$ aws cloudformation create-stack --stack-name CWAgentECS-${ClusterName}-${Region} \
    --template-body file://cwagent-ecs-instance-metric-cfn.json \
    --parameters ParameterKey=ClusterName,ParameterValue=${ClusterName} \
                 ParameterKey=CreateIAMRoles,ParameterValue=True \
    --capabilities CAPABILITY_NAMED_IAM \
    --region ${Region}

上記の変更で解決した場合、原因は AWS CLI バージョン 2 の仕様変更によるものです。

AWS CLI バージョン1 ではhttp://もしくはhttps://で始まる値を指定した場合、指定したURLの内容を取得して、取得した内容を値として使用する仕様でした。一方で、AWS CLI バージョン2では、http://もしくはhttps://で始まる値を指定しても、指定した値(URL)をそのまま使用します。

そのため、AWS CLI バージョン2をご使用で、ドキュメント等を参考にする際はhttp://もしくはhttps://で始まる値は、ファイルをダウンロードして、ファイルを指定する値もしくはファイルの中身の値に置換が必要な場合があるとご認識ください。

※指定したファイル内容を取得して、値として使用するfile://構文はAWS CLI バージョン2でも引き続き使用できます。

参考資料

AWS CLI バージョン 2 では、パラメータの http:// または https:// URL が自動的に取得されなくなりました