CloudFormation で「User data is limited to 16384 bytes」になったときの対処方法

2024.03.11

困っていた内容

CloudFormation で EC2 インスタンスを作成したいです。
作成した CloudFormation テンプレートを実行したところUser data is limited to 16384 bytesで失敗しました。
原因と対処方法を教えてください

状況の理由

User data is limited to 16384 bytes (Service: AmazonEC2; Status Code: 400; Error Code: InvalidParameterValue; Request ID: 1234abcd-12ab-34cd-56ef-1234567890ab; Proxy: null)

どう対応すればいいの?

ユーザーデータのサイズを削減してください。

EC2 インスタンス起動時に実行するコマンドやスクリプトをユーザーデータとして設定できます。ユーザーデータは 16 KBのサイズ上限があり、上限を超えるユーザーデータを指定するとInvalidParameterValueエラーとなります。

AWS::EC2::Instance - AWS CloudFormation

User data is limited to 16 KB.

そのため、サイズを確認し、サイズの削減をお試しください。

なお、一つの削減方法として、実行する内容をシェルスクリプトとして S3 に配置し、ユーザーデータにはシェルスクリプトのダウンロードと実行だけにする方法があります。

ユーザーデータの設定例

#!/bin/bash
aws s3 cp s3://${UserDataBucket}/${UserDataShell} /tmp/${UserDataShell}
chmod +x /tmp/${UserDataShell}
./tmp/${UserDataShell}

参考資料

UserData

The parameters or scripts to store as user data. Any scripts in user data are run when you launch the instance. User data is limited to 16 KB.

ユーザーデータは raw 形式の 16 KB に制限されます

InvalidParameterValue

A value specified in a parameter is not valid, is unsupported, or cannot be used. Ensure that you specify a resource by using its full ID. The returned message provides an explanation of the error value.