# AWS CDKに入門する ## 概要 https://qiita.com/Brutus/items/6c8d9bfaab7af53d154a Pythonなどのプログラミング言語を使用して、AWSリソースを定義し、Terraformの様にInfrastructure as Code(以降、IaC)を実現する手段として、クラウドインフラのリソースをプロビジョニングすることができます。 CDKでは高いレベルの抽象化を使用して少ないコード量でインフラストラクチャを定義できますが、その裏ではCloudFormationが使用されています。 ## メリット - CloudFormationが裏で使用されているメリットとして、自動ロールバックやドリフト検出などを享受できます。 - Terraformとか、SDKと異なるところ ## Pythonでやってみる ### CDKコマンドのインストール https://qiita.com/uhooi/items/e0883aebb24abc5b55f5 ### 資料 https://dev.classmethod.jp/articles/api-with-dynamodb-using-aws-cdk-in-python/ ### ステータス クラメソ資料の ``` pip install -r requirements.txt ``` ## 20221021 ### 以下を参考にVPC、サブネットを記述 https://dev.classmethod.jp/articles/create-vpc-with-cdk-python/ ### コーディング #### app/vpc_stack.pyを作る ```python= from aws_cdk import ( Stack, aws_ec2 as ec2 ) from constructs import Construct VPC_CIDR = '192.168.0.0/16' class ThreeTierStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) self.vpc = ec2.Vpc( self, 'three-tier', cidr=VPC_CIDR, max_azs=2, subnet_configuration=[ ec2.SubnetConfiguration( name='public', subnet_type=ec2.SubnetType.PUBLIC ), ec2.SubnetConfiguration( name='private', subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT ), ec2.SubnetConfiguration( name='isolated', subnet_type=ec2.SubnetType.PRIVATE_ISOLATED ) ] ) ``` #### app.pyを変更 ```python= #!/usr/bin/env python3 import os import aws_cdk as cdk from app.vpc_stack import ThreeTierStack app = cdk.App() vpc_stack = ThreeTierStack(app, "ThreeTierVPC") cdk.Tags.of(vpc_stack).add('Project', 'three-tier') app.synth() ``` ### cdk bootstrap PowerUserAccess権限のIAMのクレデンシャルをローカルにセット(aws configure)し、 `cdk bootstrap` を叩くとエラー。 どうやらAdministoratorAccessがないとダメらしい。 このコマンドを行うと、CDKがスタックをデプロイするためのS3バケットが作成される。 ### cdk deploy このコマンドを叩くと、CDKで定義したリソースがデプロイされる。 ![](https://i.imgur.com/j9nHRnk.png)