📘

CDK入門の学習記録

に公開

モチベ

業務でStepFunctionsを使った業務改善を進めていましたが、複数アカウントでほぼ同一のリソースを運用するので、二重管理回避のためにCDK化したいというモチベがありました。

とはいえ僕はCDKでAWSリソースを管理したことがないので、題材としてHelloWorldを出力するStepFunctionsを、CDKで作成・デプロイするのを目標として学習した記録を書いていきます。

SSO設定

CDKを使ってリソース管理する際は、CLIの認証情報を通してAWSリソースの操作を行うようです。
コマンド実行前にIAM Identity Centerから、ユーザ作成やアクセスのための許可セット割り当ての設定が事前に必要です。
設定後、CLIからSSOの認証情報を取得するためのコマンドを実行します。

aws configure sso

すると、下記のようにプロンプト上でのSSO設定を求められるので入力します。

  • SSO session name: 任意の文字列
  • SSO start URL: 「IAM Identity Center」の「AWS access portal URL」
  • SSO session name: 任意のリージョン
SSO session name (Recommended): ...
SSO start URL [None]: ...
SSO region [None]: ...
SSO registration scopes [sso:account:access]: ...
Attempting to automatically open the SSO authorization page in your default browser.
If the browser does not open or you wish to use a different device to authorize this request, open the following URL:

入力後はブラウザの認証画面が表示されてユーザ名やパスワードを求められるので、「IAM Identity Center」で設定したユーザ情報を入力します。

諸々の設定が問題ない場合は、コマンド実行時の出力として、CLIのプロファイル情報の入力が求めらレます。

CLI default client Region [...]: ...
CLI default output format [None]: ...
CLI profile name [...]: ...

入力を終えると下記のように出力されます。

...
To use this profile, specify the profile name using --profile, as shown:

aws s3 ls --profile ...

SSO設定は以上で終わりです。

CDK作成

CDKデプロイまでの流れは、リソース作成→ブートストラップ→デプロイという流れになります。
CDKプロジェクト開始前に、CDKインストールしてない場合はここを見て済ませておきます。
インストール済みなら、プロジェクトの空ディレクトリを作成して、下記コマンドを実行します。

cdk init --language typescript

実行後は下記のように出力されます。

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

This is a blank project for CDK development with TypeScript.

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
* `npx cdk deploy`  deploy this stack to your default AWS account/region
* `npx cdk diff`    compare deployed stack with current state
* `npx cdk synth`   emits the synthesized CloudFormation template

Initializing a new git repository...
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint:   git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint:   git branch -m <name>
Executing npm install...
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
✅ All done!

また、CDKをtypescriptで記述するためのテンプレートが作成されます。

スタック定義はlib配下のファイルで、bin配下がエントリーファイルです。

今回はhelloworldを出力するStepFunction作成をしたいので、lib配下のhello-stepfunctions-stack.tsをざざっと下記のように書き換えました。

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class HelloStepfunctionsStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const pass = new cdk.aws_stepfunctions.Pass(this, "Hello World", {
      parameters: {
        "result": "Hello World" }
      }
    });
    const succeed = new cdk.aws_stepfunctions.Succeed(this, 'End');
    const definition = pass.next(succeed);
    new cdk.aws_stepfunctions.StateMachine(this, 'HelloWorldStateMachine', {
      definition,
    });
  }
}

bin配下のhello-stepfunctions.tsを下記のように置き換えます。
スタックのデプロイ先のアカウント情報が必要なのでenv定義してます。

#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { HelloStepfunctionsStack } from '../lib/hello-stepfunctions-stack';
require('dotenv').config();

const app = new cdk.App();
new HelloStepfunctionsStack(app, 'HelloStepfunctionsStack', {
  env: { account: `${process.env.CDK_ACCOUNT}`, region: `${process.env.CDK_REGION}` },
});

CDKデプロイ

リソース定義がざっと終わったので、ターミナルからbootstrapコマンドを実行します。

cdk bootstrap
[WARNING] aws-cdk-lib.aws_stepfunctions.StateMachineProps#definition is deprecated.
  use definitionBody: DefinitionBody.fromChainable()
  This API will be removed in the next major release.
[WARNING] aws-cdk-lib.aws_stepfunctions.StateMachineProps#definition is deprecated.
  use definitionBody: DefinitionBody.fromChainable()
  This API will be removed in the next major release.
 ⏳  Bootstrapping environment ...
...

bootstrapコマンド実行後はデプロイコマンドを実行します。

cdk deploy
[WARNING] aws-cdk-lib.aws_stepfunctions.StateMachineProps#definition is deprecated.
  use definitionBody: DefinitionBody.fromChainable()
  This API will be removed in the next major release.
[WARNING] aws-cdk-lib.aws_stepfunctions.StateMachineProps#definition is deprecated.
  use definitionBody: DefinitionBody.fromChainable()
  This API will be removed in the next major release.

✨  Synthesis time: 3.55s

HelloStepfunctionsStack: start: Building HelloStepfunctionsStack Template
HelloStepfunctionsStack: success: Built HelloStepfunctionsStack Template
...
 ✅  HelloStepfunctionsStack

✨  Deployment time: 17.31s

...

✨  Total time: 20.85s

無事にデプロイ完了したので、ダッシュボードからStepFunctionsが作成されていることを確認します。

無事に作成されていました。

実行するとHello Worldの出力が確認できます。

終わり

CDK作成からデプロイまでの流れをざっくり記載しました。
初期設定さえ済ましておけば、CDKでのリソースデプロイ自体は簡単でした。
今回の題材が簡単なものだったので、CDK作成よりSSOの初期設定の方が時間がかかってたりします。
あとCDKのリソース定義ではL1、L2、L3などあるようですが、自分がどれで定義しているのか正直わかっていません。
より実践的なリソースを定義するなかで自然と意識する場面が増えると思うので、追々学習できればなといった感じです。また、どの程度のリソースをCDK化しておくべきなのか、今後導入予定のCI/CDパイプラインもCDKで作成できるのかなど、疑問はありますが少しずつキャッチアップしていきたいです。

コラボスタイル Developers

Discussion