AWS EmulatorでCloudFormationのスタックを作る

​​AWS Emulator​AWS CLI,CloudFormation,S3,SQS

CloudFormation のテンプレートを本物の AWS にデプロイする前に、手元でスタックを作って動きを確かめられます。AWS Emulator に AWS CLI を向ければ、aws cloudformation create-stack でスタックができ、テンプレートに書いた S3 のバケットや SQS のキューも、エミュレーターの中に実際に作られます。テンプレートの手直しを、アカウントも料金も気にせずにくり返したいときに使えます。スタックの作成、変更セットでの更新、作成に失敗したときのロールバック、削除の順に、実際のコマンドと出力で確かめます。

補足

検証環境は Ubuntu 24.04(x86_64)、AWS Emulator 1.0.531(2026年11月19日リリース)、AWS CLI 2.41.2 です。AWS のアカウントと認証情報は使っていません。本物の CloudFormation での動き(作成や削除にかかる時間、料金、エラーメッセージの細かい文面、ドリフトの検出)は確かめていません。本物の AWS について書いたところは、公式ドキュメントを出どころにしています。使ったリソースの種類は S3 のバケットと SQS のキューだけで、IAM のリソースやネストしたスタック、AWS CDK・AWS SAM からのデプロイは試していません。

AWS Emulator を入れて、AWS CLI を向ける

AWS Emulator は、AWS の API を手元で受け付けるエミュレーターです。AWS のアカウントは要らず、リクエストは AWS に送られません。Ubuntu では、Linux 向けのインストール手順にある Debian パッケージを使います。私は、公式の手順にあるパッケージの署名の確かめ方に沿って、gpg で署名を確かめてから入れました。そのため、ファイル名は署名ファイル(aws-emulator_amd64.deb.sig)と合わせて aws-emulator_amd64.deb にしています。下のコマンドは公式の手順どおり sudo を付けていますが、私は root で作業したので、sudo を付けずに実行しました。AWS CLI v2 は、AWS CLI の公式のインストール手順にある Linux 用の zip で入れました。

bash
curl -fsSLo aws-emulator_amd64.deb https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y ./aws-emulator_amd64.deb
aws-emulator -t off

-t off は、利用状況のデータ(テレメトリー)を送らない指定です。エミュレーターはその端末で動き続けるので、別の端末で公式ドキュメントにある環境変数を設定します。最後の AWS_PAGER は、AWS CLI の出力をページャーで開かずにそのまま表示するために、私が足したものです。

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
export AWS_PAGER=""
注意

公式ドキュメントによると、AWS_ENDPOINT_URL が設定されていないシェルでは、見つかった認証情報を使って本物の AWS にリクエストが送られます。本物の AWS の認証情報があるマシンでは、上の環境変数がそろっていることを確かめてから実行してください。本物の AWS でスタックを作ると、テンプレートにあるリソースの料金がかかります。

エミュレーターにつながっていれば、aws sts get-caller-identity のユーザー名が emulator になります。この記事の出力では、12桁のアカウントIDを <12桁のアカウントID> に置き換えています。そのため、表の形の出力は縦線の位置が少しずれています。

console
$ aws sts get-caller-identity --query Arn --output text
arn:aws:iam::<12桁のアカウントID>:user/emulator

試したテンプレート

S3 のバケットと SQS のキューを1つずつ作るテンプレートです。パラメーター Env で名前の末尾を dev か prod に切り替え、出力(Outputs)にバケット名、キューの URL、キューの ARN を出します。AWS::SQS::Queue のリファレンスによると、キューに Ref を使うとキューの URL が、!GetAtt NekoQueue.Arn で ARN が返ります。AWS::S3::Bucket のリファレンスによると、バケットの Ref はバケット名です。

yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Neko demo stack (S3 bucket and SQS queue)
Parameters:
  Env:
    Type: String
    Default: dev
    AllowedValues: [dev, prod]
Resources:
  NekoBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub "neko-demo-${Env}"
  NekoQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "neko-queue-${Env}"
      VisibilityTimeout: 60
Outputs:
  BucketName:
    Value: !Ref NekoBucket
  QueueUrl:
    Value: !Ref NekoQueue
  QueueArn:
    Value: !GetAtt NekoQueue.Arn

出力を読みやすくするために、バケットに名前を付けています。S3 のバケット名の決まりでは、汎用バケットの名前は、同じパーティションのすべての AWS アカウントで重ならないものにする必要があります。本物の AWS にこのテンプレートを使うときは、名前を変えるか、BucketName を書かずに CloudFormation に名前を作らせてください。

validate-template を送ると、テンプレートの説明とパラメーターが返りました。

console
$ aws cloudformation validate-template --template-body file://template.yaml
{
    "Parameters": [
        {
            "ParameterKey": "Env",
            "DefaultValue": "dev",
            "NoEcho": false
        }
    ],
    "Description": "Neko demo stack (S3 bucket and SQS queue)"
}

create-stack でスタックを作る

create-stack は、受け付けたことを示すスタックの ID を返してすぐに終わります。作り終わるまで待つには wait stack-create-complete を使います。待つコマンドにかかった時間を time で測ると、検証環境では約0.5秒でした。

console
$ aws cloudformation create-stack --stack-name neko-demo --template-body file://template.yaml
{
    "StackId": "arn:aws:cloudformation:us-east-1:<12桁のアカウントID>:stack/neko-demo/3f1d4873-1f37-dbbb-fe3c-0938f4f7b5c7",
    "OperationId": "a197e419-683e-e00d-7e67-4f122efb5fa5"
}
$ time aws cloudformation wait stack-create-complete --stack-name neko-demo

real	0m0.531s
user	0m0.488s
sys	0m0.041s

スタックの状態は CREATE_COMPLETE になり、パラメーターは既定の dev が使われました。

console
$ aws cloudformation describe-stacks --stack-name neko-demo --query 'Stacks[0].[StackStatus,Parameters]'
[
    "CREATE_COMPLETE",
    [
        {
            "ParameterKey": "Env",
            "ParameterValue": "dev"
        }
    ]
]

出力には、!Sub で組み立てた名前と、Ref・GetAtt の値が入っていました。

console
$ aws cloudformation describe-stacks --stack-name neko-demo --query 'Stacks[0].Outputs' --output table
-----------------------------------------------------------------------------------
|                                 DescribeStacks                                  |
+------------+--------------------------------------------------------------------+
|  OutputKey |                            OutputValue                             |
+------------+--------------------------------------------------------------------+
|  BucketName|  neko-demo-dev                                                     |
|  QueueUrl  |  https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/neko-queue-dev   |
|  QueueArn  |  arn:aws:sqs:us-east-1:<12桁のアカウントID>:neko-queue-dev                 |
+------------+--------------------------------------------------------------------+

キューの URL のホスト名は sqs.us-east-1.amazonaws.com です。検証環境(AWS CLI 2.41.2、AWS_ENDPOINT_URL を設定済み)では、この URL を --queue-url に渡した下の get-queue-attributes にも、エミュレーターから値が返りました。

スタックが作ったリソースを確かめる

list-stack-resources で、テンプレートの論理 ID(NekoBucket など)と、実際にできたリソースの名前の対応が分かります。

console
$ aws cloudformation list-stack-resources --stack-name neko-demo --query 'StackResourceSummaries[].[LogicalResourceId,PhysicalResourceId,ResourceType,ResourceStatus]' --output table
-------------------------------------------------------------------------------------------------------------------------
|                                                  ListStackResources                                                   |
+------------+-------------------------------------------------------------------+------------------+-------------------+
|  NekoBucket|  neko-demo-dev                                                    |  AWS::S3::Bucket |  CREATE_COMPLETE  |
|  NekoQueue |  https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/neko-queue-dev  |  AWS::SQS::Queue |  CREATE_COMPLETE  |
+------------+-------------------------------------------------------------------+------------------+-------------------+

CloudFormation の外から、S3 と SQS の API でも確かめました。バケットはあり、キューの VisibilityTimeout はテンプレートに書いた60秒でした。キューの URL は、スタックの出力から取り出して使っています。

console
$ QUEUE_URL=$(aws cloudformation describe-stacks --stack-name neko-demo --query "Stacks[0].Outputs[?OutputKey==\`QueueUrl\`].OutputValue" --output text)
$ aws s3api list-buckets --query 'Buckets[].Name'
[
    "neko-demo-dev"
]
$ aws sqs get-queue-attributes --queue-url "$QUEUE_URL" --attribute-names VisibilityTimeout
{
    "Attributes": {
        "VisibilityTimeout": "60"
    }
}

作成の流れは describe-stack-events で見られます。新しいイベントが先に返るので、reverse で古い順に並べ替えました。

console
$ aws cloudformation describe-stack-events --stack-name neko-demo --query 'reverse(StackEvents)[].[LogicalResourceId,ResourceStatus]' --output text
neko-demo	CREATE_IN_PROGRESS
NekoBucket	CREATE_IN_PROGRESS
NekoQueue	CREATE_IN_PROGRESS
NekoBucket	CREATE_IN_PROGRESS
NekoQueue	CREATE_IN_PROGRESS
NekoBucket	CREATE_COMPLETE
NekoQueue	CREATE_COMPLETE
neko-demo	CREATE_COMPLETE

変更セットで中身を見てから更新する

変更セットの説明によると、変更セットは、スタックに何が起きるかを先に見るためのものです。作っただけではスタックは変わらず、実行したときに初めて変更が入ります。キューの VisibilityTimeout を60秒から120秒に変えたテンプレートで試しました。

console
$ sed 's/VisibilityTimeout: 60/VisibilityTimeout: 120/' template.yaml > template-v2.yaml
$ aws cloudformation create-change-set --stack-name neko-demo --change-set-name raise-timeout --template-body file://template-v2.yaml --query Id --output text
arn:aws:cloudformation:us-east-1:<12桁のアカウントID>:changeSet/raise-timeout/5aaba044-73cf-fa8d-15b2-89c53cec5442
$ aws cloudformation wait change-set-create-complete --stack-name neko-demo --change-set-name raise-timeout
$ aws cloudformation describe-change-set --stack-name neko-demo --change-set-name raise-timeout --query 'Changes[].ResourceChange.{Action:Action,Resource:LogicalResourceId,Replacement:Replacement,Scope:Scope}'
[
    {
        "Action": "Modify",
        "Resource": "NekoQueue",
        "Replacement": "False",
        "Scope": [
            "Properties"
        ]
    }
]

変わるのは NekoQueue のプロパティだけで、Replacement が False なので、キューを作り直さずに設定を変える、という内容でした。AWS::SQS::Queue のリファレンスでも、VisibilityTimeout の変更は中断なし(No interruption)、QueueName の変更は作り直し(Replacement)とされています。

この時点では、スタックの状態もキューの設定も変わっていませんでした。

console
$ aws cloudformation describe-stacks --stack-name neko-demo --query 'Stacks[0].StackStatus'
"CREATE_COMPLETE"
$ aws sqs get-queue-attributes --queue-url "$QUEUE_URL" --attribute-names VisibilityTimeout
{
    "Attributes": {
        "VisibilityTimeout": "60"
    }
}

execute-change-set で実行すると、スタックは UPDATE_COMPLETE になり、キューの設定が120秒に変わりました。

console
$ aws cloudformation execute-change-set --stack-name neko-demo --change-set-name raise-timeout
$ aws cloudformation wait stack-update-complete --stack-name neko-demo
$ aws cloudformation describe-stacks --stack-name neko-demo --query 'Stacks[0].StackStatus'
"UPDATE_COMPLETE"
$ aws sqs get-queue-attributes --queue-url "$QUEUE_URL" --attribute-names VisibilityTimeout
{
    "Attributes": {
        "VisibilityTimeout": "120"
    }
}

作成に失敗すると、途中まで作ったリソースも消える

失敗したときの動きを見るために、キューを2つ作り、2つ目に範囲外の VisibilityTimeout を書いたテンプレートを用意しました。AWS::SQS::Queue のリファレンスでは、この値は0〜43,200秒です。DependsOn で、1つ目の FirstQueue を先に作らせています。

yaml
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  FirstQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: neko-first-queue
  BadQueue:
    Type: AWS::SQS::Queue
    DependsOn: FirstQueue
    Properties:
      QueueName: neko-bad-queue
      VisibilityTimeout: 99999

create-stack は受け付けられ、wait stack-create-complete は、スタックが ROLLBACK_COMPLETE になったところでエラーで終わりました。

console
$ aws cloudformation create-stack --stack-name neko-broken --template-body file://broken.yaml --query StackId --output text
arn:aws:cloudformation:us-east-1:<12桁のアカウントID>:stack/neko-broken/108f8fce-2941-7712-e1eb-b847047a2f3a
$ aws cloudformation wait stack-create-complete --stack-name neko-broken

aws: [ERROR]: Waiter StackCreateComplete failed: Waiter encountered a terminal failure state: For expression "Stacks[].StackStatus" we matched expected path: "ROLLBACK_COMPLETE" at least once

イベントを古い順に並べると、FirstQueue ができたあとで BadQueue が CREATE_FAILED になり、ロールバックで FirstQueue も消されたことが分かります。失敗の理由は ResourceStatusReason に出ます。

console
$ aws cloudformation describe-stack-events --stack-name neko-broken --query 'reverse(StackEvents)[].[LogicalResourceId,ResourceStatus,ResourceStatusReason]' --output text
neko-broken	CREATE_IN_PROGRESS	User Initiated
FirstQueue	CREATE_IN_PROGRESS	None
FirstQueue	CREATE_IN_PROGRESS	Resource creation Initiated
FirstQueue	CREATE_COMPLETE	None
BadQueue	CREATE_IN_PROGRESS	None
BadQueue	CREATE_FAILED	Resource handler returned message: "Invalid value for the parameter VisibilityTimeout." (RequestToken: a9e22e76-4a43-73f2-e100-3937e046d8be, HandlerErrorCode: InvalidRequest)
neko-broken	ROLLBACK_IN_PROGRESS	The following resource(s) failed to create: [BadQueue]. Rollback requested by user.
BadQueue	DELETE_COMPLETE	None
FirstQueue	DELETE_IN_PROGRESS	None
FirstQueue	DELETE_COMPLETE	None
neko-broken	ROLLBACK_COMPLETE	None

キューの一覧に残っていたのは、先に作った neko-demo スタックのキューだけでした。

console
$ aws sqs list-queues
{
    "QueueUrls": [
        "https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/neko-queue-dev"
    ]
}

ROLLBACK_COMPLETE のスタックは、正しいテンプレートで更新しようとしてもエラーになりました。スタックの状態の一覧でも、この状態のスタックにできるのは削除だけとされています。delete-stack で消すことはできました。

console
$ aws cloudformation update-stack --stack-name neko-broken --template-body file://template.yaml

aws: [ERROR]: An error occurred (ValidationError) when calling the UpdateStack operation: Stack:arn:aws:cloudformation:us-east-1:<12桁のアカウントID>:stack/neko-broken/108f8fce-2941-7712-e1eb-b847047a2f3a is in ROLLBACK_COMPLETE state and can not be updated.
$ aws cloudformation delete-stack --stack-name neko-broken
$ aws cloudformation wait stack-delete-complete --stack-name neko-broken

ここまでのスタックの状態の移り変わりを、図にまとめました。

成功したときは CREATE_COMPLETE、UPDATE_COMPLETE、DELETE_COMPLETE と進み、作成の途中で BadQueue が CREATE_FAILED になると、スタックは ROLLBACK_IN_PROGRESS を経て ROLLBACK_COMPLETE になる図
検証環境で確認したスタックの状態の移り変わり(更新中・削除中の状態は省略)

aws cloudformation deploy で作成と更新をまとめる

aws cloudformation deploy のリファレンスによると、このコマンドは変更セットを作ってから実行します。スタックがなければ作り、あれば更新します。パラメーターは --parameter-overrides に キー=値 の形で渡します。

Env=prod で neko-prod スタックを作ると、出力のバケット名は neko-demo-prod になりました。

console
$ aws cloudformation deploy --stack-name neko-prod --template-file template.yaml --parameter-overrides Env=prod

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - neko-prod
$ aws cloudformation describe-stacks --stack-name neko-prod --query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue' --output text
neko-demo-prod

同じ内容でもう一度実行すると、変更がないことが表示され、終了コードは0でした。リファレンスによると、変更がないときに0以外で終わらせたいなら --fail-on-empty-changeset を付けます。

console
$ aws cloudformation deploy --stack-name neko-prod --template-file template.yaml --parameter-overrides Env=prod

Waiting for changeset to be created..

No changes to deploy. Stack neko-prod is up to date

AllowedValues にない値を渡すと、変更セットを作る段階でエラーになりました。

console
$ aws cloudformation deploy --stack-name neko-prod --template-file template.yaml --parameter-overrides Env=stg

aws: [ERROR]: An error occurred (ValidationError) when calling the CreateChangeSet operation: Parameter 'Env' must be one of AllowedValues

delete-stack でリソースごと消す

delete-stack でスタックを消すと、スタックが作ったバケットとキューも消えました。残っているのは neko-prod スタックのものだけです。

console
$ aws cloudformation delete-stack --stack-name neko-demo
$ aws cloudformation wait stack-delete-complete --stack-name neko-demo
$ aws cloudformation describe-stacks --stack-name neko-demo

aws: [ERROR]: An error occurred (ValidationError) when calling the DescribeStacks operation: Stack with id neko-demo does not exist
$ aws s3api list-buckets --query 'Buckets[].Name'
[
    "neko-demo-prod"
]
$ aws sqs list-queues
{
    "QueueUrls": [
        "https://sqs.us-east-1.amazonaws.com/<12桁のアカウントID>/neko-queue-prod"
    ]
}

消したスタックは、list-stacks には DELETE_COMPLETE として残りました。スタックの状態の一覧によると、本物の CloudFormation では、削除したスタックを90日間見ることができます。

console
$ aws cloudformation list-stacks --query 'StackSummaries[].[StackName,StackStatus]' --output text
neko-demo	DELETE_COMPLETE
neko-broken	DELETE_COMPLETE
neko-prod	CREATE_COMPLETE

AWS Emulator の制限の説明によると、エミュレーターはリソースをメモリーに置き、止めるとすべて消します。同じ説明には、起動し直すとテストをまっさらな状態から始められる、とも書かれています。また、CloudFormation のような IaC(Infrastructure as Code)のツールへの対応の度合いはサービスごとに違う、とエミュレーターがどこまで AWS と同じに動くか(fidelity)についての公式の説明にあります。S3 と SQS 以外のリソースを使うテンプレートは、そのリソースでも同じように作れるかを確かめてから使ってください。

​Posted by 86