AWS CDK Intro Workshop
SQS/SNS
cdk init
code:bash
$ cdk init app --language python
pipenv にて管理
code:bash
$ rm -rf .venv
$ rm source.bat
code:bash
$ pipenv --python /Users/r0306/.pyenv/versions/3.10.0/bin/python
$ pipenv shell
$ pipenv install --skip-lock
アプリのエントリポイント
code:bash
import aws_cdk as cdk
from workshop.workshop_stack import WorkshopStack
app = cdk.App()
WorkshopStack(app, "workshop")
app.synth()
メインスタック
code:bash
$ cat workshop/workshop_stack.py
from constructs import Construct
from aws_cdk import (
Duration,
Stack,
aws_iam as iam,
aws_sqs as sqs,
aws_sns as sns,
aws_sns_subscriptions as subs,
)
class WorkshopStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
queue = sqs.Queue(
self, "WorkshopQueue",
visibility_timeout=Duration.seconds(300),
)
topic = sns.Topic(
self, "WorkshopTopic"
)
topic.add_subscription(subs.SqsSubscription(queue))
アプリからテンプレートを生成
code:bash
$ cdk synth
cdk.out 配下に書き出される
環境の初期構築
code:bash
$ cdk bootstrap
S3 バケットとか作られる
デプロイ
code:bash
$ cdk deploy
API Gateway/Lambda
上記の SQS と SNS の記述を削除
workshop/workshop_stack.py
差分チェック
code:bash
$ cdk diff
リソース削除
code:bash
$ cdk deploy
Lambda の準備で最上位のディレクトリと同階層に lambda ディレクトリを作成
lambda/hello.py
code:python
import json
def handler(event, context):
print('request: {}'.format(json.dump(event)))
return {
'statusCode': 200,
'headers': {
'Content-Type': 'text/plain'
},
'body': 'Hello CDK {}\n'.format(event)
}
Lambda 関数をスタックに追加
workshop/workshop_stack.py
code:python
from constructs import Construct
from aws_cdk import (
Duration,
Stack,
aws_lambda as _lambda,
)
class WorkshopStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Lambda
hello = _lambda.Function(
self, 'HelloHandler',
runtime=_lambda.Runtime.PYTHON_3_9,
code=_lambda.Code.from_asset('lambda'),
handler='hello.handler',
)
差分チェック
code:bash
$ cdk diff
デプロイ
code:bash
$ cdk deploy