ちょっと話題の記事

CloudFormationのCLI実行ツール Rain がイケてそうなので紹介したい

2021.02.19

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

AWS事業本部の梶原@福岡オフィスです。

とりあえず、公式動画をみるといいと思う

asciicast

AWS CLI でCloudFormationをやってる人は大きな声では言いづらい辛みを感じたことがあると思います。

  • はっきりいうと初回スタックのdeployに失敗すると残るから一度消さないといけないです。
  • パラメータの指定や変更がめんどくさいです
  • 進捗がわかんないです。(そのためにコンソール画面もあげて見てたりします)
  • そもそもCloudFormationのテンプレートって、よく誤字らないです?- の位置わかります?私はタイポが多い方なのでいらっとします

上記のちょっとイラっとした(?)部分を Rain が解消してくれそうな雰囲気を感じたんで
ぜひ、みんなに使ってもらって、フィードバック、プルリクをおくって、もっとイケてるツールにしてほしいと思います(なにとぞ、お頼み申し上げます

バージョンとしては1.1.1ですが、プレビュー扱いだと思います。
本番で使うときは十分に検証してください

Rain 公式ページ

https://github.com/aws-cloudformation/rain

Rain is also a command line tool for working with AWS CloudFormation templates and stacks.

一応公式のAWSのcloudformationリポジトリ内のツールになります。 とくにAWSのブログなどではまだ紹介されていないっぽいです。一部海外のblackbeltで観測しましたが、あまりまだ情報がないです

Rainの特徴

Interactive deployments: With rain deploy, rain packages your CloudFormation templates using aws cloudformation package, prompts you for any parameters that have not yet been defined, shows you a summary of the changes that will be made, and then displays real-time updates as your stack is being deployed. Once finished, you get a summary of the outcome along with any error messages collected along the way - including errors messages for stacks that have been rolled back and no longer exist.

$rain deploy <テンプレートファイル> スタック名

って、するだけで、パラメータを提示してくれて(EnterのみだとDefault) で、差分リソースを表示してくれ、実行すると、進捗を表示してくれ、エラーを表示してくれます。(すばら) あと スタック重複したら自動で消して実行することもできます。

Consistent formatting of CloudFormation templates: Using rain fmt, you can format your CloudFormation templates to a consistent standard or reformat a template from JSON to YAML (or YAML to JSON if you prefer). Rain preserves your comments when using YAML and switches use of intrinsic functions to use the short syntax where possible.

$rain fmt <テンプレートファイル>

cfn-flip とかと同じですが、いい感じに整形してくれます。 人のyamlって読みにくい時ありますよね?JSONはそもそも(自粛)

Combined logs for nested stacks with sensible filtering: When you run rain log, you will see a combined stream of logs from the stack you specified along with any nested stack associated with it. Rain also filters out uninteresting log messages by default so you just see the errors that require attention.

ブわ!!ってlogがでないです。あとネステッドスタックしてるものを一緒に表示してくれます。もう最高

Build new CloudFormation templates: rain build generates new CloudFormation templates containing skeleton resources that you specify. This saves you having to look up which properties are available and which are required vs. optional.

$rain build リソースタイプ

個人的にこれがもっともイケてると思います CloudFormationの空のテンプレートを生成してくれます どれが、必須パラメータか、オプションかわかるので定義しやすいです 定義のネストした子供の部分も提示してくれます。公式ドキュメントで追っていった頃が懐かしいです。(まぁ見る必要はあるんですが) よく、YAMLの空白まちがったりしませんか?私の目には空白が見えないのでめちゃ助かります

と、これくらいにして、使ってみましょう

んで、CLIといえば、AWS CloudShellでしょ! (実際はご自分の環境にいれてみてください。

INSTALL

AWSコンソールの上にあるこんなの[>_] AWS CloudShellをクリックしてください

Install homebrew & GCC

とりあえず、brewがないので、brewをいれる(これが思ったよりデカい)

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
$ echo 'eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)' >> /home/cloudshell-user/.bash_profile
$ eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)
$ brew --version
Homebrew 3.0.1
Homebrew/linuxbrew-core (git revision eb39d; last commit 2021-02-18)

ちょっと時間かかる gcc が必要っていわれたのでgccもいれました

$ sudo yum install gcc -y

Install Rain

brew が入ってれば、一発です

$ brew install rain
$ rain --version
Rain v1.1.1 linux/amd64
$ rain
Rain is a command line tool for working with AWS CloudFormation templates and stacks

Usage:
  rain [command]

Stack commands:
  cat         Get the CloudFormation template from a running stack
  deploy      Deploy a CloudFormation stack from a local template
  logs        Show the event log for the named stack
  ls          List running CloudFormation stacks
  rm          Delete a running CloudFormation stack
  watch       Display an updating view of a CloudFormation stack

Template commands:
  build       Create CloudFormation templates
  diff        Compare CloudFormation templates
  fmt         Format CloudFormation templates
  merge       Merge two or more CloudFormation templates
  tree        Find dependencies of Resources and Outputs in a local template

Other Commands:
  console     Login to the AWS console
  help        Help about any command
  info        Show your current configuration

Build S3 Bucket Template

ってことで、S3バケットを作ってみます! さっそく、サンプルテンプレートを作成してみます

$ rain build AWS::S3::Bucket > S3.yml

S3.yml

AWSTemplateFormatVersion: "2010-09-09"

Description: Template generated by rain

Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      AccelerateConfiguration: # Optional
        AccelerationStatus: CHANGEME
      AccessControl: CHANGEME # Optional
      AnalyticsConfigurations:
        - Id: CHANGEME
          Prefix: CHANGEME # Optional
          StorageClassAnalysis:
            DataExport: # Optional
              Destination:
                BucketAccountId: CHANGEME # Optional
                BucketArn: CHANGEME
                Format: CHANGEME
                Prefix: CHANGEME # Optional
              OutputSchemaVersion: CHANGEME
          TagFilters: # Optional
          
省略...

すいません、さすがS3ですね。大量の設定項目です。出しすぎましたw こんなテンプレートを生成してくれます。 かるく説明すると #Optional は必須ではない項目 ない部分は必須項目です。

スタックのデプロイ Deploy Stack (Error)

このままでは、何もしてないんで普通にエラーするんですがとりあえず流してみます
スタック名を省略するとテンプレート名(拡張子なし)になります

$ rain deploy S3.yml
CloudFormation will make the following changes:
Stack S3:
  + AWS::S3::Bucket MyBucket
Do you wish to continue? (Y/n) [Enter]
Deploying template 'S3.yml' as stack 'S3' in ap-northeast-1.
Stack S3: ROLLBACK_COMPLETE
Messages:
  - MyBucket: Valud of property 1970-01-01 00:00:00 must be valid date time format
failed deploying stack 'S3'

エラーメッセージは違うかもしれませんがなにもしてないのでエラーしますよね。
とはいえ、従来のCLIだと結果を見たりするのも結構めんどいので、めっちゃ楽です。

スタックのデプロイ Deploy Stack

気を取り直して最低限のS3のテンプレートにしておきます。 (先頭7行までリダイレクトしてS3.ymlとして保存します。

rain build AWS::S3::Bucket | head -n7 > S3.yml

S3.yml

AWSTemplateFormatVersion: "2010-09-09"

Description: Template generated by rain

Resources:
  MyBucket:
    Type: AWS::S3::Bucket

短くなりましたw再度挑戦!

ここからが、めっちゃ楽ポイントです!!!!

通常、全開前回エラーしたスタックを消さないといけないですよね?

気にせずやれます!。やります!

$ rain deploy S3.yml
Deleted existing, empty stack.
CloudFormation will make the following changes:
Stack S3:
  + AWS::S3::Bucket MyBucket
Do you wish to continue? (Y/n) Y (EnterでもOKす)
Deploying template 'S3.yml' as stack 'S3' in ap-northeast-1.
Stack S3: CREATE_COMPLETE
Successfully deployed S3

これ!!!!

Deleted existing, empty stack.

エラーしたりした同じテンプレートがあると消してくれます。 で、スタックのデプロイが開始されます。まじ楽。

スタックの更新(Update Stack)

PublicAcceeBlockを有効にしてみます

CLIでリダイレクト追記してますが、普通にテンプレートを更新してもらっても問題ないです。

cat <<EOL >> S3.yml
    Properties:
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
Outputs:
  MyBucket:
    Value: !Ref MyBucket
EOL

もうお分かりに頂けるとおもいますが。同じdeployコマンドでいけます。

$ rain deploy S3.yml
CloudFormation will make the following changes:
Stack S3:
Do you wish to continue? (Y/n) 
Deploying template 'S3.yml' as stack 'S3' in ap-northeast-1.
Stack S3: UPDATE_COMPLETE
  Outputs:
    MyBucket: s3-mybucket-hogehoge

はい。便利

スタックの削除 Delete Stack

では、消してみます。

$ rain rm S3
Stack S3: UPDATE_COMPLETE
Are you sure you want to delete this stack? (Y/n) [Enter]
Successfully deleted stack 'S3'

個人的には削除なのにYがデフォルトっていうのは怖いのですが、今後に期待します。

まとめ

個人的にはかなりイケてると思う。もっと普及していい感じになってほしいです。
ほかにもfmtとかmergeとかdiffとかあるので、検証してみてください。

参考URL

rain リポジトリ https://github.com/aws-cloudformation/rain