1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【AWS】CloudFormationで必要最低限なCLIをまとめてみた

Last updated at Posted at 2023-05-20

CloudFormaitonのスタック作成はAWSコンソールからだとポチポチが必要な以上、少し手間だったりします。特にスタック作成がうまくいかないときのやり直しはけっこうしんどいです。なのでTerraformライクを目指して、CLIのコマンドをまとめてみました。なお、コマンドは重要度の高い順で記載してます:pencil:

※GUIでのスタック作成はこちら↓

deploy

まずはデプロイからです。create-stackだと、スタックがあると実行できませんが、こっちのdeployなら削除せずに更新が可能です。Terraformのapply的な使い方ができます。ただし更新内容などは表示されず、コマンド一発で更新がかかるのでそこだけ注意しましょう。(更新は次の項で説明するオプションで回避可能です)

aws cloudformation deploy --stack-name test-stack --template-file template.yaml --parameter-overrides $(cat parameter.yaml)

パラメータの引数は単にコマンド上で記載できますが、あえて外だししています。記述の仕方は単にパラメータを縦に並べるだけでOKです。下記はキーペアとIPをパラメータに指定した場合の記述例です。

template.yaml
KeyName=test-stack
MyIP=192.168.1.1/32

--no-execute-changeset(オプション)

deployコマンドは自動的に変更セットを更新しますが、このオプションを付ければ更新されなくなります。要するに更新内容の確認ができるということです。Terraformでいうplanをイメージしていただければよいです。

aws cloudformation deploy --stack-name test-stack --template-file template.yaml --parameter-overrides $(cat parameter.yaml) --no-execute-changeset

基本的にこのdeployコマンドをメインにすればよいですが、一応スタンダードはxxx-stackコマンドです。また、スタックが失敗した場合にdeployは流せなくなるので、delete-stackは必須なコマンドになります。

xxx-stack

create-stack

その名の通りスタックを作成するコマンドです。

aws cloudformation create-stack --stack-name test-stack --template-body file://template.yaml --parameters file://parameter.yaml

こちらの場合のパラメータは以下のような形式で作成します。

parameter.yaml
[
  {
    "ParameterKey": "KeyName",
    "ParameterValue": "test-stack"
  },
  {
    "ParameterKey": "MyIP",
    "ParameterValue": "192.168.1.1/32"
  }
]

delete-stack

スタックを削除するコマンドです。

aws cloudformation delete-stack --stack-name test-stack

list-stacks

スタックの一覧を取得するコマンドです。

aws cloudformation list-stacks --query "StackSummaries[].{StackName:StackName,CreationTime:CreationTime,StackStatus:StackStatus}" --output table

一覧だと大量でてしまう場合などは、stack-status-filterオプションを使いスタックのステータスで絞ることも可能です。以下のコマンドではステータスをCREATE_COMPLETEに絞っています。

aws cloudformation list-stacks --query "StackSummaries[].{StackName:StackName,CreationTime:CreationTime,StackStatus:StackStatus}" --output table --stack-status-filter CREATE_COMPLETE

なお、スタック名でも絞ったり出来たりしないかなと思ったのですが、該当するオプションはなさそうでした。

validate-template

テンプレートファイルのチェックが可能です。VSCodeの拡張機能などを使っていればチェック必要性はないかもしれませんが、パラメータも出力できるのでパラメータのチェックにも使えます。

aws cloudformation validate-template --template-body file://test-stack.yaml

以上です。これでCloudFormationもCLIで流せるようになるでしょう:sparkles:

参考にさせていただいた記事

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?