実践!AWS CDK #30 よく使う CDK コマンド

題字・息子たち
2021.12.21

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

はじめに

今回は少し足を止めて、よく利用する CDK コマンドとそのオプションをまとめます。

前回の記事はこちら。

$ npm install -g aws-cdk

CDK のインストールやアップデートを実行するコマンドです。

特定のバージョンをインストールしたい場合は、以下のようにバージョンを指定します。

$ npm install -g aws-cdk@2.1.0

実行例

$ npm install -g aws-cdk

removed 7 packages, changed 198 packages, and audited 199 packages in 4s

found 0 vulnerabilities

$ cdk --version

現在インストールされている CDK のバージョンを確認するコマンドです。

実行例

$ cdk --version

2.2.0 (build 4f5c27c)

$ cdk init

CDK プロジェクトを作成するコマンドです。

--language オプションでプログラミング言語を指定します。
現在サポートされている言語は以下 7 つです。

  • csharp
  • fsharp
  • go
  • java
  • javascript
  • python
  • typescript

git リポジトリの初期化やパッケージのインストールを行いたくない場合は --generate-only オプションを付けます。

$ cdk init app --language=typescript --generate-only

実行例

$ cdk init app --language=typescript

Applying project template app for typescript
# Welcome to your CDK TypeScript project!

This is a blank project for TypeScript development with CDK.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

 * `npm run build`   compile typescript to js
 * `npm run watch`   watch for changes and compile
 * `npm run test`    perform the jest unit tests
 * `cdk deploy`      deploy this stack to your default AWS account/region
 * `cdk diff`        compare deployed stack with current state
 * `cdk synth`       emits the synthesized CloudFormation template

Initializing a new git repository...
Executing npm install...
✅ All done!

$ cdk bootstrap

CDK アプリをデプロイするために必要なリソースをプロビジョニングするコマンドです。

初回デプロイ前に アカウント & リージョン ごとに実行する必要があります。(1 回で OK)

実行例

$ cdk bootstrap

 ⏳  Bootstrapping environment aws://060405383263/ap-northeast-1...
Trusted accounts for deployment: (none)
Trusted accounts for lookup: (none)
Using default execution policy of 'arn:aws:iam::aws:policy/AdministratorAccess'. Pass '--cloudformation-execution-policies' to customize.
CDKToolkit: creating CloudFormation changeset...

 ✅  Environment aws://060405383263/ap-northeast-1 bootstrapped.

$ cdk ls

CDK アプリに含まれるスタックの一覧を確認するコマンドです。

実行例

$ cdk ls

DevioStack
IamStack
VpcStack

$ cdk synth

CDK アプリで定義されたスタックを CFn テンプレートに合成するコマンドです。

特定のスタックを出力したい場合はスタック ID を指定します。
※ diff, deploy, destroy コマンドでも有効です

$ cdk synth VpcStack

Context を設定したい場合は --context または -c オプションを使用し、--context key=value の形式でキーと値を指定します。
※ diff, deploy コマンドでも有効です

$ cdk synth -c systemName=starwars

リソースごとの Metadata を削除したい場合は --path-metadata false オプションを付けます。
※ diff, deploy コマンドでも有効です

$ cdk synth --path-metadata false

CFn テンプレートを出力したくない場合は --quiet または -q オプションを付けます。
プログラム内に記述した console.log() のみを出力したい場合などに利用します。

$ cdk synth -q

実行例

$ cdk synth -c envType=prd --path-metadata false VpcStack

Resources:
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      Tags:
        - Key: Name
          Value: devio-prd-vpc
  ~ 省略 ~

$ cdk diff

現在の CDK アプリのバージョンと既にデプロイされているバージョンとを比較し、変更点を一覧で出力するコマンドです。

実行例

VPC の IPv4 CIDR を 10.0.0.0/16 から 192.168.0.0/16 に変更しようとした場合の例です。

$ cdk diff

Resources
[~] AWS::EC2::VPC Vpc Vpc replace
 └─ [~] CidrBlock (requires replacement)
     ├─ [-] 10.0.0.0/16
     └─ [+] 192.168.0.0/16

$ cdk deploy

CDK アプリを AWS 環境にデプロイするコマンドです。

すべてのスタックをデプロイしたい場合は "*" または --all オプションを付けます。

$ cdk deploy --all

また、機密性の高いデプロイの場合は次のような確認が発生します。

This deployment will make potentially sensitive changes according to your current security approval level (--require-approval broadening).
Please confirm you intend to make the following modifications:

~ 省略 ~

(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Do you wish to deploy these changes (y/n)?

この確認をスキップしたい場合は --require-approval never オプションを付けます。

$ cdk deploy IamStack --require-approval never

実行例

$ cdk deploy VpcStack

VpcStack (devio-stg-stack-vpc): deploying...
[0%] start: Publishing 43a722702e0fab774c06bc992cc9a174259cba138b25dc5d6129543da143eb9d:current_account-current_region
[100%] success: Published 43a722702e0fab774c06bc992cc9a174259cba138b25dc5d6129543da143eb9d:current_account-current_region
devio-stg-stack-vpc: creating CloudFormation changeset...

 ✅  VpcStack (devio-stg-stack-vpc)

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:060405383263:stack/devio-stg-stack-vpc/1981b430-6163-11ec-863c-0667b1f1cb83

$ cdk destroy

デプロイしたスタックを削除するコマンドです。

特定のスタックのみを削除することも可能です。

通常、削除前は次のような確認が発生します。

Are you sure you want to delete: VpcStack, IamStack, DevioStack (y/n)?

この確認をスキップしたい場合は --force または -f オプションを付けます。

$ cdk destroy --force

実行例

$ cdk destroy --all -f

VpcStack (devio-stg-stack-vpc): destroying...

 ✅  VpcStack (devio-stg-stack-vpc): destroyed
IamStack (devio-stg-stack-iam): destroying...

 ✅  IamStack (devio-stg-stack-iam): destroyed
DevioStack: destroying...

 ✅  DevioStack: destroyed

$ tsc && npm test

CDK アプリのテストを実行するコマンドです。

パラメーターにファイルパスを指定することで、そのファイルに書かれているテストのみを実行することもできます。

$ tsc && npm test test/stack/iam-stack.test.ts

実行例

$ tsc && npm test

> devio@0.1.0 test
> jest

 PASS  test/stack/iam-stack.test.ts
 PASS  test/stack/vpc-stack.test.ts (5.016 s)

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        5.464 s, estimated 6 s
Ran all test suites.

$ cdk xxx --help

困った時のヘルプコマンドです。

そのコマンドの使い方を確認したい場合は --help または -h オプションを付けます。

実行例

$ cdk init --help

cdk init [TEMPLATE]

Create a new, empty CDK project from a template.

オプション:
  -a, --app                 REQUIRED: command-line for executing your app or a
                            cloud assembly directory (e.g. "node bin/my-app.js")
                                                                        [文字列]
  -c, --context             Add contextual string parameter (KEY=VALUE)   [配列]

  ~ 省略 ~

  -h, --help                ヘルプを表示                                  [真偽]

おわりに

以上が私のよく利用する CDK コマンドとそのオプションです。これらを覚えておけば CDK プロジェクトの初期設定からリソースのデプロイまで一通りの作業が実施できます。CDK で開発を行う際の参考にしてみてください。

リンク