継続は力なり

タイトル通り定期的な更新を心掛けるブログです。

「AWS Cloud Development Kit」に対応した Python コードを実践!

タダです.

以前,「AWS Cloud Development Kit」(以下、CDK)の記事を書きました.当時は対応言語に Python がサポートされてませんでしたが, AWS Developer Blog で CDK の Python コードやドキュメントが公開されていました.早速, Python で CDK を使ってみます。

AWS Developer Blog の記事

aws.amazon.com

関連記事

sadayoshi-tada.hatenablog.com

チュートリアルプロジェクトの実行

初期設定

下記のチュートリアルに沿って CDK を実行します. プロジェクトを初期化し、pip install -r requirements.txtでライブラリをインストールします.

docs.aws.amazon.com

$ mkdir hello-cdk && cd hello-cdk
$ cdk init --language python sample-app
Applying project template sample-app for python
Initializing a new git repository...
Executing Creating virtualenv...

# Welcome to your CDK Python project!

You should explore the contents of this template. It demonstrates a CDK app with two instances of
a stack (`HelloStack`) which also uses a user-defined construct (`HelloConstruct`).

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

This project is set up like a standard Python project.  The initialization process also creates
a virtualenv within this project, stored under the .env directory.  To create the virtualenv 
it assumes that there is a `python3` executable in your path with access to the `venv` package.
If for any reason the automatic creation of the virtualenv fails, you can create the virtualenv
manually once the init process completes.

To manually create a virtualenv on MacOS and Linux:

$ python3 -m venv .env


After the init process completes and the virtualenv is created, you can use the following
step to activate your virtualenv.

$ source .env/bin/activate

If you are a Windows platform, you would activate the virtualenv like this:

% .env\Scripts\activate.bat

Once the virtualenv is activated, you can install the required dependencies.

$ pip install -r requirements.txt

At this point you can now synthesize the CloudFormation template for this code.

$ cdk synth

You can now begin exploring the source code, contained in the hello directory.
There is also a very trivial test included that can be run like this:

$ pytest

To add additional dependencies, for example other CDK libraries, just add to
your requirements.txt file and rerun the `pip install -r requirements.txt`
command.

# Useful commands

 * `cdk ls`          list all stacks in the app
 * `cdk synth`       emits the synthesized CloudFormation template
 * `cdk deploy`      deploy this stack to your default AWS account/region
 * `cdk diff`        compare deployed stack with current state
 * `cdk docs`        open CDK documentation

Enjoy!
$ python3 -m venv .env
$ source .env/bin/activate
(.env) $ pip install -r requirements.txt 
Obtaining file:///Users/tada/work/cdk_python_sample (from -r requirements.txt (line 1))
Collecting pytest (from -r requirements.txt (line 2))
〜中略〜
uccessfully installed atomicwrites-1.3.0 attrs-19.1.0 aws-cdk.assets-0.31.0 aws-cdk.aws-autoscaling-api-0.31.0 aws-cdk.aws-cloudwatch-0.31.0 aws-cdk.aws-ec2-0.31.0 aws-cdk.aws-events-0.31.0 aws-cdk.aws-iam-0.31.0 aws-cdk.aws-kms-0.31.0 aws-cdk.aws-lambda-0.31.0 aws-cdk.aws-logs-0.31.0 aws-cdk.aws-s3-0.31.0 aws-cdk.aws-s3-notifications-0.31.0 aws-cdk.aws-sns-0.31.0 aws-cdk.aws-sqs-0.31.0 aws-cdk.aws-stepfunctions-0.31.0 aws-cdk.cdk-0.31.0 aws-cdk.cx-api-0.31.0 aws-cdk.region-info-0.31.0 cattrs-0.9.0 hello jsii-0.10.5 more-itertools-7.0.0 mypy-extensions-0.4.1 pluggy-0.11.0 publication-0.0.3 py-1.8.0 pytest-4.4.2 python-dateutil-2.8.0 six-1.12.0 typing-extensions-3.7.2
You are using pip version 19.0.3, however version 19.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

因みにプロジェクトを作ると以下のようなディレクトリ構造が作成されます.Python のコードで構成されているのがわかります.

$ tree
├── README.md
├── app.py
├── cdk.json
├── hello_cdk
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-37.pyc
│   │   └── hello_cdk_stack.cpython-37.pyc
│   ├── hello_cdk.egg-info
│   │   ├── PKG-INFO
│   │   ├── SOURCES.txt
│   │   ├── dependency_links.txt
│   │   ├── requires.txt
│   │   └── top_level.txt
│   └── hello_cdk_stack.py
├── requirements.txt
└── setup.py

デプロイ

次にデプロイをしていきます。まずcdk synthで CloudFormation テンプレートを合成し,次にcdk deployでデプロイをします.

$ cdk synth
Resources:
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Modules: aws-cdk=0.30.0,@aws-cdk/cdk=0.31.0,@aws-cdk/cx-api=0.31.0,jsii-runtime=Python/3.7.3


$ cdk deploy
HelloCdkStack: deploying...
HelloCdkStack: creating CloudFormation changeset...
 0/2 | 09:18:25 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata | CDKMetadata 
 0/2 | 09:18:28 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata | CDKMetadata Resource creation Initiated
 1/2 | 09:18:29 | CREATE_COMPLETE      | AWS::CDK::Metadata | CDKMetadata 
 2/2 | 09:18:31 | CREATE_COMPLETE      | AWS::CloudFormation::Stack | HelloCdkStack 

 ✅  HelloCdkStack

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxx:stack/HelloCdkStack/6ef54dd0-744b-11e9-aada-0e842c318628

CloudFormationのスタックが完成していました.バージョニングと暗号化したS3バケットを作るのみですがサクッと作れました. f:id:sadayoshi_tada:20190512095953p:plain

後片付け

作成したリソースの削除はcdk destroyで完結します.

cdk destroy
Are you sure you want to delete: HelloCdkStack (y/n)? y
HelloCdkStack: destroying...
   0 | 01:27:57 | DELETE_IN_PROGRESS   | AWS::CloudFormation::Stack | HelloCdkStack User Initiated
   0 | 01:27:59 | DELETE_IN_PROGRESS   | AWS::CDK::Metadata | CDKMetadata 
   0 | 01:27:59 | DELETE_SKIPPED       | AWS::S3::Bucket    | HelloCdkBucket (HelloCdkBucketA63BB9B1) 

 ✅  HelloCdkStack: destroyed

Pulumi との利用比較

CDK」と似たようなツールとして「Pulumi」があります.「Pulumi」も JavaScript,Golang,TypeScriptの他に Python に対応したプログラミング言語でのプロビジョニングツールです.最後に2つのツールを使い分けていくにあたって利用比較を自分なりに調べてみたものをまとめます。

www.pulumi.com

Pulumi と CDK の比較

  • Pulumi」のプロビジョニングはマルチクラウド対応しているが, 「CDK」のプロビジョニングは AWS対応のみ
  • Pulumi」は利用形態に応じて利用料がかかるが, 「CDK」は利用料不要で利用可能
  • Pulumi」には独自 GUI 管理の画面があるが, 「CDK」は管理画面はなくターミナルでの操作中心 f:id:sadayoshi_tada:20190516011949p:plain

AWS を普段使うため僕は引き続き「CDK」でのプロビジョニングの勉強をしていきます💪

まとめ

CDK」の Python 対応したコードを試してみました.Python のコードの情報が出てきているのでこれは PythonAWS を利用している人にとっては朗報かと思います.僕もしっかり使いこなして Python でアプリケーションの開発,デプロイまで完結できるようにドキュメントを読み込んだり,実践していきたいです!

CDK の関連情報

公式ドキュメント(Get Started)

docs.aws.amazon.com

リファレンスドキュメント

docs.aws.amazon.com

Python のサンプルコード

github.com