aws-cliからCloudFormationを使う

CloudFormationを使うにはテンプレートファイルが必要になるのだが、今回は、AWSが提供しているテンプレートをローカルに持ってきて使う。

ローカルのテンプレートファイルを指定してスタックを作成するには以下のコマンドを実行する。

$ aws cloudformation create-stack \
  --stack-name sample \
  --template-body file:///home/nowtom/sample.template \
  --parameters ParameterKey=KeyName,ParameterValue=sample-keypair \
               ParameterKey=VpcId,ParameterValue=vpc-xxxxxxxx \
               ParameterKey=SubnetId,ParameterValue=subnet-xxxxxxxx
{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:stack/sample/95338e20-5af8-11e3-9c5c-506cf9a1c096"
}


スタックの状態を確認するには、以下のコマンドを実行する。

$ aws cloudformation describe-stacks --stack-name sample

スタックが作成中だとStackStatusがCREATE_IN_PROGRESSになっていて、問題なければそのうちCREATE_COMPLETEになる。


状態がROLLBACK_IN_PROGRESSとかになって、スタックの作成が失敗した場合は以下のコマンドで理由が調べられる。
ResourceStatusReasonに失敗した理由が格納されている。
マネジメントコンソールから見えない場合も、コマンドからなら見える場合がある。

$ aws cloudformation describe-stack-events --stack-name sample


スタックを削除するには、以下のコマンドを実行する。
忘れずに消さないと課金される。

$ aws cloudformation delete-stack --stack-name sample