あめがえるのITブログ

あめがえるのITブログ

頑張りすぎない。ほどほどに頑張るブログ。

【AWS】CloudFrontでログ機能が拡充されたので調べてみた


CloudFrontでログ機能が拡充されたので調べてみた
aws.amazon.com


CloudFrontのディストリビューション内にLoggingタブができてます!

ログの出力先にCloudWatchLogsとKinesisFirehoseが追加されてます!
以前までのログ出力設定はS3(レガシー)になってます。

S3(レガシー)の設定項目はこちら

S3の設定項目はこちら
ログ形式にJSONなどが指定できるようになってます。

KinesisFirehoseの設定項目はこちら

CloudWatchLogsはこちら
こちらもログ形式にJSONなどが指定できるようになってます。

新たに追加なった出力先では出力するフィールドも選択できます。

ここからS3バケットを作成するとログ転送に必要なバケットポリシーを自動で設定してくれます。


aws cdk(typescript)でVPC他を作ってみた

aws cdkを少しでも覚えたいのでとりあえずなにかを作ってみた。

やること

aws cdk(TypeScript)でVPCを作成する。

実践!

1.プロジェクト作成
1-1.PowerShellで下記を実行

> cdk init app --language typescript
PS C:\typescript> cdk init app --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...
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!


2.コード作成
2-1.lib/typescript-stack.tsを開き、下記を入力
※importの2行と、export classからsuperまでの3行は必ず使う文言なのでおまじないとして覚える。

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
// import * as sqs from 'aws-cdk-lib/aws-sqs';
import { Vpc } from 'aws-cdk-lib/aws-ec2';

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

    new Vpc(this, 'Vpc');
  }
}


3.作成
3-1.PowerShellで下記を実行

> cdk bootstrap --profile <Profile名>
PS C:\typescript> cdk bootstrap --profile testvault
 ⏳  Bootstrapping environment aws://xxxxxxxxxxxx/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.
 ✅  Environment aws://xxxxxxxxxxxx/ap-northeast-1 bootstrapped (no changes).

3-2.PowerShellで下記を実行

> cdk deploy --profile <Profile名>
PS C:\typescript> cdk deploy --profile testvault

✨  Synthesis time: 6.25s

TypescriptStack:  start: Building ee7de53d64cc9d6248fa6aa550f92358f6c907b5efd6f3298aeab1b5e7ea358a:current_account-current_region
TypescriptStack:  success: Built ee7de53d64cc9d6248fa6aa550f92358f6c907b5efd6f3298aeab1b5e7ea358a:current_account-current_region
TypescriptStack:  start: Building 6c8accc9ce1df3c3e70991c10bcf3807d91862f3f1de732b98e7f54e2b9555dc:current_account-current_region
TypescriptStack:  success: Built 6c8accc9ce1df3c3e70991c10bcf3807d91862f3f1de732b98e7f54e2b9555dc:current_account-current_region
TypescriptStack:  start: Publishing ee7de53d64cc9d6248fa6aa550f92358f6c907b5efd6f3298aeab1b5e7ea358a:current_account-current_region
TypescriptStack:  start: Publishing 6c8accc9ce1df3c3e70991c10bcf3807d91862f3f1de732b98e7f54e2b9555dc:current_account-current_region
TypescriptStack:  success: Published 6c8accc9ce1df3c3e70991c10bcf3807d91862f3f1de732b98e7f54e2b9555dc:current_account-current_region
TypescriptStack:  success: Published ee7de53d64cc9d6248fa6aa550f92358f6c907b5efd6f3298aeab1b5e7ea358a:current_account-current_region
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:

IAM Statement Changes
┌───┬─────────────┬────────┬─────────────┬─────────────┬───────────────┐
│   │ Resource    │ Effect │ Action      │ Principal   │ Condition     │ 
├───┼─────────────┼────────┼─────────────┼─────────────┼───────────────┤ 
│ + │ ${Custom::V │ Allow  │ sts:AssumeR │ Service:lam │               │ 
│   │ pcRestrictD │        │ ole         │ bda.amazona │               │ 
│   │ efaultSGCus │        │             │ ws.com      │               │ 
│   │ tomResource │        │             │             │               │ 
│   │ Provider/Ro │        │             │             │               │ 
│   │ le.Arn}     │        │             │             │               │ 
├───┼─────────────┼────────┼─────────────┼─────────────┼───────────────┤ 
│ + │ arn:${AWS:: │ Allow  │ ec2:Authori │ AWS:${Custo │               │ 
│   │ Partition}: │        │ zeSecurityG │ m::VpcRestr │               │ 
│   │ ec2:${AWS:: │        │ roupEgress  │ ictDefaultS │               │ 
│   │ Region}:${A │        │ ec2:Authori │ GCustomReso │               │ 
│   │ WS::Account │        │ zeSecurityG │ urceProvide │               │ 
│   │ Id}:securit │        │ roupIngress │ r/Role}     │               │ 
│   │ y-group/${V │        │ ec2:RevokeS │             │               │ 
│   │ pc8378EB38. │        │ ecurityGrou │             │               │ 
│   │ DefaultSecu │        │ pEgress     │             │               │ 
│   │ rityGroup}  │        │ ec2:RevokeS │             │               │ 
│   │             │        │ ecurityGrou │             │               │ 
│   │             │        │ pIngress    │             │               │ 
└───┴─────────────┴────────┴─────────────┴─────────────┴───────────────┘ 
IAM Policy Changes
┌───┬────────────────────────────────┬─────────────────────────────────┐
│   │ Resource                       │ Managed Policy ARN              │ 
├───┼────────────────────────────────┼─────────────────────────────────┤ 
│ + │ ${Custom::VpcRestrictDefaultSG │ {"Fn::Sub":"arn:${AWS::Partitio │ 
│   │ CustomResourceProvider/Role}   │ n}:iam::aws:policy/service-role │ 
│   │                                │ /AWSLambdaBasicExecutionRole"}  │ 
└───┴────────────────────────────────┴─────────────────────────────────┘ 
(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)? y
TypescriptStack: deploying... [1/1]
TypescriptStack: creating CloudFormation changeset...
TypescriptStack |  0/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::VPC                         | Vpc (Vpc8378EB38) Resource creation Initiated 
TypescriptStack |  0/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C) Eventual consistency check initiated
TypescriptStack |  0/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87) Eventual consistency check initiated
TypescriptStack |  0/28 | 21:10:23 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669) Eventual consistency check initiated
TypescriptStack |  0/28 | 21:10:10 | REVIEW_IN_PROGRESS   | AWS::CloudFormation::Stack            | TypescriptStack User Initiated
TypescriptStack |  0/28 | 21:10:17 | CREATE_IN_PROGRESS   | AWS::CloudFormation::Stack            | TypescriptStack User Initiated
TypescriptStack |  0/28 | 21:10:20 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
TypescriptStack |  0/28 | 21:10:20 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669)
TypescriptStack |  0/28 | 21:10:20 | CREATE_IN_PROGRESS   | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C)
TypescriptStack |  0/28 | 21:10:21 | CREATE_IN_PROGRESS   | AWS::EC2::VPC                         | Vpc (Vpc8378EB38)
TypescriptStack |  0/28 | 21:10:21 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87)
TypescriptStack |  0/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C) Resource creation Initiated
TypescriptStack |  0/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata) Resource creation Initiated
TypescriptStack |  1/28 | 21:10:22 | CREATE_COMPLETE      | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
TypescriptStack |  1/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87) Resource creation Initiated
TypescriptStack |  1/28 | 21:10:22 | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:33 | CREATE_COMPLETE      | AWS::EC2::VPC                         | Vpc (Vpc8378EB38)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::VPCGatewayAttachment        | Vpc/VPCGW (VpcVPCGWBF912B6E)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet2/RouteTable (VpcPublicSubnet2RouteTable94F7E489)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet2/Subnet (VpcPublicSubnet2Subnet691E08A3)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A)
TypescriptStack |  2/28 | 21:10:34 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet1/Subnet (VpcPublicSubnet1Subnet5C2D37C4)
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0) 
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::VPCGatewayAttachment        | Vpc/VPCGW (VpcVPCGWBF912B6E) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet2/Subnet (VpcPublicSubnet2Subnet691E08A3) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet2/RouteTable (VpcPublicSubnet2RouteTable94F7E489) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:35 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet1/Subnet (VpcPublicSubnet1Subnet5C2D37C4) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet2/RouteTable (VpcPublicSubnet2RouteTable94F7E489) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A) Eventual consistency check initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0) Resource creation Initiated
TypescriptStack |  2/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet2/RouteTableAssociation (VpcPrivateSubnet2RouteTableAssociationA89CAD56)
TypescriptStack |  3/28 | 21:10:36 | CREATE_COMPLETE      | AWS::EC2::VPCGatewayAttachment        | Vpc/VPCGW (VpcVPCGWBF912B6E)
TypescriptStack |  3/28 | 21:10:36 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet1/RouteTableAssociation (VpcPrivateSubnet1RouteTableAssociation70C59FA6)
TypescriptStack |  4/28 | 21:10:37 | CREATE_COMPLETE      | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C)
TypescriptStack |  5/28 | 21:10:37 | CREATE_COMPLETE      | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87)
TypescriptStack |  6/28 | 21:10:37 | CREATE_COMPLETE      | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669)
TypescriptStack |  7/28 | 21:10:38 | CREATE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1)
TypescriptStack |  7/28 | 21:10:38 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet2/RouteTableAssociation (VpcPrivateSubnet2RouteTableAssociationA89CAD56) Resource creation Initiated  
TypescriptStack |  7/28 | 21:10:38 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet1/RouteTableAssociation (VpcPrivateSubnet1RouteTableAssociation70C59FA6) Resource creation Initiated  
TypescriptStack |  8/28 | 21:10:38 | CREATE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PublicSubnet2/Subnet (VpcPublicSubnet2Subnet691E08A3)
TypescriptStack |  9/28 | 21:10:38 | CREATE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A)
TypescriptStack | 10/28 | 21:10:38 | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet2/RouteTableAssociation (VpcPrivateSubnet2RouteTableAssociationA89CAD56)
TypescriptStack | 11/28 | 21:10:38 | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet1/RouteTableAssociation (VpcPrivateSubnet1RouteTableAssociation70C59FA6)
TypescriptStack | 12/28 | 21:10:39 | CREATE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PublicSubnet1/Subnet (VpcPublicSubnet1Subnet5C2D37C4)
TypescriptStack | 12/28 | 21:10:39 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet2/RouteTableAssociation (VpcPublicSubnet2RouteTableAssociationDD5762D8)
TypescriptStack | 12/28 | 21:10:39 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet1/RouteTableAssociation (VpcPublicSubnet1RouteTableAssociation97140677)
TypescriptStack | 12/28 | 21:10:40 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet2/RouteTableAssociation (VpcPublicSubnet2RouteTableAssociationDD5762D8) Resource creation Initiated    
TypescriptStack | 13/28 | 21:10:40 | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet2/RouteTableAssociation (VpcPublicSubnet2RouteTableAssociationDD5762D8)
TypescriptStack | 13/28 | 21:10:41 | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet1/RouteTableAssociation (VpcPublicSubnet1RouteTableAssociation97140677) Resource creation Initiated    
TypescriptStack | 14/28 | 21:10:41 | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet1/RouteTableAssociation (VpcPublicSubnet1RouteTableAssociation97140677)
TypescriptStack | 15/28 | 21:10:46 | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500)
TypescriptStack | 16/28 | 21:10:46 | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B)
TypescriptStack | 17/28 | 21:10:46 | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PublicSubnet2/RouteTable (VpcPublicSubnet2RouteTable94F7E489)
TypescriptStack | 18/28 | 21:10:46 | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E)
TypescriptStack | 18/28 | 21:10:46 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet2/DefaultRoute (VpcPublicSubnet2DefaultRoute97F91067)
TypescriptStack | 18/28 | 21:10:46 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet1/DefaultRoute (VpcPublicSubnet1DefaultRoute3DA9E72A)
TypescriptStack | 18/28 | 21:10:47 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet2/DefaultRoute (VpcPublicSubnet2DefaultRoute97F91067) Resource creation Initiated
TypescriptStack | 18/28 | 21:10:48 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet1/DefaultRoute (VpcPublicSubnet1DefaultRoute3DA9E72A) Resource creation Initiated
TypescriptStack | 19/28 | 21:10:48 | CREATE_COMPLETE      | AWS::EC2::Route                       | Vpc/PublicSubnet2/DefaultRoute (VpcPublicSubnet2DefaultRoute97F91067)
TypescriptStack | 20/28 | 21:10:48 | CREATE_COMPLETE      | AWS::EC2::Route                       | Vpc/PublicSubnet1/DefaultRoute (VpcPublicSubnet1DefaultRoute3DA9E72A)
TypescriptStack | 20/28 | 21:10:49 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D)
TypescriptStack | 20/28 | 21:10:49 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA)
TypescriptStack | 20/28 | 21:10:50 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D) Resource creation Initiated
TypescriptStack | 20/28 | 21:10:50 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA) Resource creation Initiated
TypescriptStack | 21/28 | 21:10:53 | CREATE_COMPLETE      | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0) 
TypescriptStack | 21/28 | 21:10:54 | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
TypescriptStack | 21/28 | 21:10:56 | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E) Resource creation Initiated
TypescriptStack | 21/28 | 21:10:56 | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E) Eventual consistency check initiated
TypescriptStack | 21/28 | 21:10:59 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D) Eventual consistency check initiated
TypescriptStack | 21/28 | 21:10:59 | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA) Eventual consistency check initiated
TypescriptStack | 22/28 | 21:11:01 | CREATE_COMPLETE      | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
TypescriptStack | 22/28 | 21:11:02 | CREATE_IN_PROGRESS   | Custom::VpcRestrictDefaultSG          | Vpc/RestrictDefaultSecurityGroupCustomResource/Default (VpcRestrictDefaultSecurityGroupCustomResourceC73DA2BE)
TypescriptStack | 22/28 | 21:11:12 | CREATE_IN_PROGRESS   | Custom::VpcRestrictDefaultSG          | Vpc/RestrictDefaultSecurityGroupCustomResource/Default (VpcRestrictDefaultSecurityGroupCustomResourceC73DA2BE) Resource creation Initiated
TypescriptStack | 23/28 | 21:11:12 | CREATE_COMPLETE      | Custom::VpcRestrictDefaultSG          | Vpc/RestrictDefaultSecurityGroupCustomResource/Default (VpcRestrictDefaultSecurityGroupCustomResourceC73DA2BE)
23/28 Currently in progress: TypescriptStack, VpcPublicSubnet2NATGateway9182C01D, VpcPublicSubnet1NATGateway4D7517AA
TypescriptStack | 24/28 | 21:12:30 | CREATE_COMPLETE      | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D)
TypescriptStack | 24/28 | 21:12:31 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet2/DefaultRoute (VpcPrivateSubnet2DefaultRoute060D2087)
TypescriptStack | 24/28 | 21:12:32 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet2/DefaultRoute (VpcPrivateSubnet2DefaultRoute060D2087) Resource creation Initiated
TypescriptStack | 25/28 | 21:12:32 | CREATE_COMPLETE      | AWS::EC2::Route                       | Vpc/PrivateSubnet2/DefaultRoute (VpcPrivateSubnet2DefaultRoute060D2087)
TypescriptStack | 26/28 | 21:12:41 | CREATE_COMPLETE      | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA)
TypescriptStack | 26/28 | 21:12:41 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet1/DefaultRoute (VpcPrivateSubnet1DefaultRouteBE02A9ED)
TypescriptStack | 26/28 | 21:12:43 | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet1/DefaultRoute (VpcPrivateSubnet1DefaultRouteBE02A9ED) Resource creation Initiated
TypescriptStack | 27/28 | 21:12:43 | CREATE_COMPLETE      | AWS::EC2::Route                       | Vpc/PrivateSubnet1/DefaultRoute (VpcPrivateSubnet1DefaultRouteBE02A9ED)
TypescriptStack | 28/28 | 21:12:44 | CREATE_COMPLETE      | AWS::CloudFormation::Stack            | TypescriptStack

 ✅  TypescriptStack

✨  Deployment time: 159.7s

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:stack/TypescriptStack/aa941280-4e6c-11ef-91cc-06379fe07e43

✨  Total time: 165.94s


4.確認
4-1.Powershellで下記を実行

Unable to locate credentials. You can configure credentials by running "aws configure".
PS C:\typescript> aws ec2 describe-vpcs --profile testvault
{
    "Vpcs": [
        {
            "CidrBlock": "10.0.0.0/16",
            "DhcpOptionsId": "dopt-88aca5ec",
            "State": "available",
            "VpcId": "vpc-0d2edd272e6645f19",
            "OwnerId": "xxxxxxxxxxxx",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-09ef88e14bf656e37", 
                    "CidrBlock": "10.0.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "TypescriptStack/Vpc"
                },
                {
                    "Key": "aws:cloudformation:stack-name",
                    "Value": "TypescriptStack"
                },
                {
                    "Key": "aws:cloudformation:logical-id",
                    "Value": "Vpc8378EB38"
                },
                {
                    "Key": "aws:cloudformation:stack-id",
                    "Value": "arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:stack/TypescriptStack/aa941280-4e6c-11ef-91cc-06379fe07e43"      
                }
            ]
        }
    ]
}

VPC以外にもいろいろなリソースが作成されている。

VPCクラスを指定した場合デフォルトの設定では、次のようなリソースが作成されます:

3つのアベイラビリティゾーンにわたる3つのパブリックサブネット。 3つのアベイラビリティゾーンにわたる3つのプライベートサブネット。 パブリックサブネットごとに1つのNATゲートウェイ。 それぞれのサブネット用のルートテーブル。


5.削除
5-1.PowerShellで下記を実行

> cdk destroy --profile <Profile名>
PS C:\typescript> cdk destroy --profile testvault          
Are you sure you want to delete: TypescriptStack (y/n)? y
TypescriptStack: destroying... [1/1]
TypescriptStack |   0 | 21:24:49 | DELETE_IN_PROGRESS   | AWS::CloudFormation::Stack            | TypescriptStack User Initiated
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet1/DefaultRoute (VpcPrivateSubnet1DefaultRouteBE02A9ED)
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PrivateSubnet2/DefaultRoute (VpcPrivateSubnet2DefaultRoute060D2087)
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet2/RouteTableAssociation (VpcPrivateSubnet2RouteTableAssociationA89CAD56)
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | Custom::VpcRestrictDefaultSG          | Vpc/RestrictDefaultSecurityGroupCustomResource/Default (VpcRestrictDefaultSecurityGroupCustomResourceC73DA2BE)
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
TypescriptStack |   0 | 21:24:51 | DELETE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet1/RouteTableAssociation (VpcPrivateSubnet1RouteTableAssociation70C59FA6)
TypescriptStack |   1 | 21:24:52 | DELETE_COMPLETE      | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
TypescriptStack |   2 | 21:24:52 | DELETE_COMPLETE      | AWS::EC2::Route                       | Vpc/PrivateSubnet1/DefaultRoute (VpcPrivateSubnet1DefaultRouteBE02A9ED)
TypescriptStack |   3 | 21:24:53 | DELETE_COMPLETE      | AWS::EC2::Route                       | Vpc/PrivateSubnet2/DefaultRoute (VpcPrivateSubnet2DefaultRoute060D2087)
TypescriptStack |   3 | 21:24:53 | DELETE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA)
TypescriptStack |   3 | 21:24:53 | DELETE_IN_PROGRESS   | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D)
TypescriptStack |   4 | 21:25:01 | DELETE_COMPLETE      | Custom::VpcRestrictDefaultSG          | Vpc/RestrictDefaultSecurityGroupCustomResource/Default (VpcRestrictDefaultSecurityGroupCustomResourceC73DA2BE)
TypescriptStack |   4 | 21:25:01 | DELETE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
TypescriptStack |   5 | 21:25:05 | DELETE_COMPLETE      | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
TypescriptStack |   5 | 21:25:05 | DELETE_IN_PROGRESS   | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0)   
TypescriptStack |   6 | 21:25:07 | DELETE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet2/RouteTableAssociation (VpcPrivateSubnet2RouteTableAssociationA89CAD56)
TypescriptStack |   7 | 21:25:08 | DELETE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PrivateSubnet1/RouteTableAssociation (VpcPrivateSubnet1RouteTableAssociation70C59FA6)
TypescriptStack |   7 | 21:25:08 | DELETE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1)
TypescriptStack |   7 | 21:25:08 | DELETE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B)
TypescriptStack |   7 | 21:25:08 | DELETE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500)
TypescriptStack |   7 | 21:25:08 | DELETE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A)
TypescriptStack |   8 | 21:25:09 | DELETE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet2/RouteTable (VpcPrivateSubnet2RouteTableA678073B)
TypescriptStack |   9 | 21:25:10 | DELETE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PrivateSubnet1/RouteTable (VpcPrivateSubnet1RouteTableB2C5B500)
TypescriptStack |  10 | 21:25:10 | DELETE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PrivateSubnet2/Subnet (VpcPrivateSubnet2Subnet3788AAA1)
TypescriptStack |  11 | 21:25:10 | DELETE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PrivateSubnet1/Subnet (VpcPrivateSubnet1Subnet536B997A)
TypescriptStack |  12 | 21:25:20 | DELETE_COMPLETE      | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0)   
TypescriptStack |  13 | 21:25:31 | DELETE_COMPLETE      | AWS::EC2::NatGateway                  | Vpc/PublicSubnet1/NATGateway (VpcPublicSubnet1NATGateway4D7517AA)
TypescriptStack |  13 | 21:25:32 | DELETE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet1/RouteTableAssociation (VpcPublicSubnet1RouteTableAssociation97140677)
TypescriptStack |  13 | 21:25:32 | DELETE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet1/DefaultRoute (VpcPublicSubnet1DefaultRoute3DA9E72A)
TypescriptStack |  13 | 21:25:32 | DELETE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669)
TypescriptStack |  14 | 21:25:33 | DELETE_COMPLETE      | AWS::EC2::Route                       | Vpc/PublicSubnet1/DefaultRoute (VpcPublicSubnet1DefaultRoute3DA9E72A)
TypescriptStack |  15 | 21:25:33 | DELETE_COMPLETE      | AWS::EC2::EIP                         | Vpc/PublicSubnet1/EIP (VpcPublicSubnet1EIPD7E02669)
TypescriptStack |  16 | 21:25:48 | DELETE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet1/RouteTableAssociation (VpcPublicSubnet1RouteTableAssociation97140677)
TypescriptStack |  16 | 21:25:48 | DELETE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E)
TypescriptStack |  16 | 21:25:48 | DELETE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet1/Subnet (VpcPublicSubnet1Subnet5C2D37C4)
TypescriptStack |  17 | 21:25:50 | DELETE_COMPLETE      | AWS::EC2::RouteTable                  | Vpc/PublicSubnet1/RouteTable (VpcPublicSubnet1RouteTable6C95E38E)
TypescriptStack |  18 | 21:25:50 | DELETE_COMPLETE      | AWS::EC2::Subnet                      | Vpc/PublicSubnet1/Subnet (VpcPublicSubnet1Subnet5C2D37C4)
TypescriptStack |  19 | 21:25:57 | DELETE_COMPLETE      | AWS::EC2::NatGateway                  | Vpc/PublicSubnet2/NATGateway (VpcPublicSubnet2NATGateway9182C01D)
TypescriptStack |  19 | 21:25:57 | DELETE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet2/RouteTableAssociation (VpcPublicSubnet2RouteTableAssociationDD5762D8)
TypescriptStack |  19 | 21:25:57 | DELETE_IN_PROGRESS   | AWS::EC2::Route                       | Vpc/PublicSubnet2/DefaultRoute (VpcPublicSubnet2DefaultRoute97F91067)
TypescriptStack |  19 | 21:25:57 | DELETE_IN_PROGRESS   | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87)
TypescriptStack |  20 | 21:25:59 | DELETE_COMPLETE      | AWS::EC2::Route                       | Vpc/PublicSubnet2/DefaultRoute (VpcPublicSubnet2DefaultRoute97F91067)
TypescriptStack |  21 | 21:25:59 | DELETE_COMPLETE      | AWS::EC2::EIP                         | Vpc/PublicSubnet2/EIP (VpcPublicSubnet2EIP3C605A87)
TypescriptStack |  21 | 21:25:59 | DELETE_IN_PROGRESS   | AWS::EC2::VPCGatewayAttachment        | Vpc/VPCGW (VpcVPCGWBF912B6E)
TypescriptStack |  22 | 21:26:00 | DELETE_COMPLETE      | AWS::EC2::VPCGatewayAttachment        | Vpc/VPCGW (VpcVPCGWBF912B6E)
TypescriptStack |  22 | 21:26:01 | DELETE_IN_PROGRESS   | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C)
TypescriptStack |  23 | 21:26:02 | DELETE_COMPLETE      | AWS::EC2::InternetGateway             | Vpc/IGW (VpcIGWD7BA715C)
TypescriptStack |  24 | 21:26:14 | DELETE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | Vpc/PublicSubnet2/RouteTableAssociation (VpcPublicSubnet2RouteTableAssociationDD5762D8)
TypescriptStack |  24 | 21:26:14 | DELETE_IN_PROGRESS   | AWS::EC2::Subnet                      | Vpc/PublicSubnet2/Subnet (VpcPublicSubnet2Subnet691E08A3)
TypescriptStack |  24 | 21:26:14 | DELETE_IN_PROGRESS   | AWS::EC2::RouteTable                  | Vpc/PublicSubnet2/RouteTable (VpcPublicSubnet2RouteTable94F7E489)

 ✅  TypescriptStack: destroyed



感想

ちょっとわかってきた(´ω`)

aws cdkでLambda(Node.js20)+S3環境を作ってみた


aws cdkをそろそろ本気で覚えたくなったのでとりあえず使ってみた。

やること

aws cdkでLambda(Node.js20)とS3バケットを作成。S3バケット内にtest.txtを配置する。

前提

 aws cdkの利用準備ができていること
 ※まだの場合、下記を参考に手順2まで実施する。
amegaeru.hatenablog.jp

実践!

1.cdk プロジェクト作成
1-1.PowerShellを開き下記を実行

> mkdir cdk-s3-lambda
> cd cdk-s3-lambda
> cdk init app --language typescript


2.コード作成
2-1.lib/cdk-s3-lambda-stack.tsを開き下記を入力

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as s3deploy from 'aws-cdk-lib/aws-s3-deployment';
import * as path from 'path';

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

    // S3バケットの作成
    const bucket = new s3.Bucket(this, 'MyBucket', {
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
    });

    // アセットディレクトリの作成
    const asset = s3deploy.Source.asset(path.join(__dirname, 'assets'));

    // S3バケットにファイルを配置
    new s3deploy.BucketDeployment(this, 'DeployTestTxt', {
      sources: [asset],
      destinationBucket: bucket,
    });

    // Lambda関数の作成
    const lambdaFunction = new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_20_X, // 修正箇所
      handler: 'index.handler',
      code: lambda.Code.fromAsset(path.join(__dirname, 'lambda')),
      environment: {
        BUCKET_NAME: bucket.bucketName,
      },
    });

    // Lambda関数にS3バケットへのアクセス権を付与
    bucket.grantRead(lambdaFunction);

    // Lambda関数のIAMロールにS3アクセス権限を追加
    lambdaFunction.addToRolePolicy(new iam.PolicyStatement({
      actions: ['s3:GetObject'],
      resources: [`${bucket.bucketArn}/*`],
    }));
  }
}


3.Lambda関数作成
3-1.lib/lambdaフォルダを作成
3-2.lib/lambdaフォルダ内にindex.jsファイルを作成
3-3.index.jsファイルを開き下記を入力

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

exports.handler = async (event) => {
    const bucketName = process.env.BUCKET_NAME;
    const key = 'test.txt';

    try {
        const data = await s3.getObject({ Bucket: bucketName, Key: key }).promise();
        const fileContent = data.Body.toString('utf-8');
        console.log('File Content:', fileContent);
    } catch (error) {
        console.error('Error getting object from S3:', error);
    }
};


4.S3バケット内にindex.txtファイルを作成
4-1.lib/assetsフォルダを作成
4-2.lib/assetsフォルダー内にindex.txtファイルを作成

5.cdkデプロイ
5-1.PowerShellで下記を実行

> cdk bootstrap --profile <profile名>
PS C:\cdk-s3-lambda> cdk bootstrap --profile testvault
 ⏳  Bootstrapping environment aws://xxxxxxxxxxxx/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...
CDKToolkit | 0/4 | 20:27:20 | UPDATE_IN_PROGRESS   | AWS::CloudFormation::Stack | CDKToolkit User Initiated
CDKToolkit | 0/4 | 20:27:24 | UPDATE_IN_PROGRESS   | AWS::SSM::Parameter     | CdkBootstrapVersion
CDKToolkit | 1/4 | 20:27:25 | UPDATE_COMPLETE      | AWS::SSM::Parameter     | CdkBootstrapVersion
CDKToolkit | 1/4 | 20:27:27 | UPDATE_IN_PROGRESS   | AWS::IAM::Role          | DeploymentActionRole 
CDKToolkit | 2/4 | 20:27:44 | UPDATE_COMPLETE      | AWS::IAM::Role          | DeploymentActionRole 
CDKToolkit | 3/4 | 20:27:45 | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack | CDKToolkit 
CDKToolkit | 4/4 | 20:27:47 | UPDATE_COMPLETE      | AWS::CloudFormation::Stack | CDKToolkit
 ✅  Environment aws://xxxxxxxxxxxx/ap-northeast-1 bootstrapped.

5-2.PowerShellで下記を実行

> cdk deploy --profile <profile名>
PS C:\cdk-s3-lambda> cdk deploy --profile testvault

✨  Synthesis time: 6.31s

CdkS3LambdaStack:  start: Building 3322b7049fb0ed2b7cbb644a2ada8d1116ff80c32dca89e6ada846b5de26f961:current_account-current_region
CdkS3LambdaStack:  success: Built 3322b7049fb0ed2b7cbb644a2ada8d1116ff80c32dca89e6ada846b5de26f961:current_account-current_region
CdkS3LambdaStack:  start: Building 2d56e153cac88d3e0c2f842e8e6f6783b8725bf91f95e0673b4725448a56e96d:current_account-current_region
CdkS3LambdaStack:  success: Built 2d56e153cac88d3e0c2f842e8e6f6783b8725bf91f95e0673b4725448a56e96d:current_account-current_region
CdkS3LambdaStack:  start: Publishing 3322b7049fb0ed2b7cbb644a2ada8d1116ff80c32dca89e6ada846b5de26f961:current_account-current_region
CdkS3LambdaStack:  start: Building 0a92ae4f0ff7188d013fc02ca4812b731af9e914f9ebaeffe18cb1c818b50d28:current_account-current_region
CdkS3LambdaStack:  success: Built 0a92ae4f0ff7188d013fc02ca4812b731af9e914f9ebaeffe18cb1c818b50d28:current_account-current_region
CdkS3LambdaStack:  start: Publishing 2d56e153cac88d3e0c2f842e8e6f6783b8725bf91f95e0673b4725448a56e96d:current_account-current_region
CdkS3LambdaStack:  start: Publishing 0a92ae4f0ff7188d013fc02ca4812b731af9e914f9ebaeffe18cb1c818b50d28:current_account-current_region
CdkS3LambdaStack:  start: Building d863e43b5651fd751e08d2380e4a998a67ca0774fffc4c236f6f2dee371d1419:current_account-current_region
CdkS3LambdaStack:  success: Built d863e43b5651fd751e08d2380e4a998a67ca0774fffc4c236f6f2dee371d1419:current_account-current_region
CdkS3LambdaStack:  start: Publishing d863e43b5651fd751e08d2380e4a998a67ca0774fffc4c236f6f2dee371d1419:current_account-current_region
CdkS3LambdaStack:  start: Building 8203404b07eea758f452b7933e4f308adcba25d7ef3330871a46c2c10bdb895c:current_account-current_region
CdkS3LambdaStack:  success: Built 8203404b07eea758f452b7933e4f308adcba25d7ef3330871a46c2c10bdb895c:current_account-current_region
CdkS3LambdaStack:  start: Publishing 8203404b07eea758f452b7933e4f308adcba25d7ef3330871a46c2c10bdb895c:current_account-current_region
CdkS3LambdaStack:  success: Published d863e43b5651fd751e08d2380e4a998a67ca0774fffc4c236f6f2dee371d1419:current_account-current_region
CdkS3LambdaStack:  success: Published 2d56e153cac88d3e0c2f842e8e6f6783b8725bf91f95e0673b4725448a56e96d:current_account-current_region
CdkS3LambdaStack:  success: Published 0a92ae4f0ff7188d013fc02ca4812b731af9e914f9ebaeffe18cb1c818b50d28:current_account-current_region
CdkS3LambdaStack:  success: Published 8203404b07eea758f452b7933e4f308adcba25d7ef3330871a46c2c10bdb895c:current_account-current_region
CdkS3LambdaStack:  success: Published 3322b7049fb0ed2b7cbb644a2ada8d1116ff80c32dca89e6ada846b5de26f961:current_account-current_region
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:

IAM Statement Changes
┌───┬───────────────────────────────┬────────┬───────────────────────────────┬────────────────────────────────┬───────────┐
│   │ Resource                      │ Effect │ Action                        │ Principal                      │ Condition │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ ${Custom::CDKBucketDeployment │ Allow  │ sts:AssumeRole                │ Service:lambda.amazonaws.com   │           │ 
│   │ 8693BB64968944B69AAFB0CC9EB87 │        │                               │                                │           │ 
│   │ 56C/ServiceRole.Arn}          │        │                               │                                │           │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ ${Custom::S3AutoDeleteObjects │ Allow  │ sts:AssumeRole                │ Service:lambda.amazonaws.com   │           │ 
│   │ CustomResourceProvider/Role.A │        │                               │                                │           │ 
│   │ rn}                           │        │                               │                                │           │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ ${MyBucket.Arn}               │ Allow  │ s3:DeleteObject*              │ AWS:${Custom::S3AutoDeleteObje │           │ 
│   │ ${MyBucket.Arn}/*             │        │ s3:GetBucket*                 │ ctsCustomResourceProvider/Role │           │ 
│   │                               │        │ s3:List*                      │ .Arn}                          │           │ 
│   │                               │        │ s3:PutBucketPolicy            │                                │           │ 
│ + │ ${MyBucket.Arn}               │ Allow  │ s3:Abort*                     │ AWS:${Custom::CDKBucketDeploym │           │ 
│   │ ${MyBucket.Arn}/*             │        │ s3:DeleteObject*              │ ent8693BB64968944B69AAFB0CC9EB │           │ 
│   │                               │        │ s3:GetBucket*                 │ 8756C/ServiceRole}             │           │ 
│   │                               │        │ s3:GetObject*                 │                                │           │ 
│   │                               │        │ s3:List*                      │                                │           │ 
│   │                               │        │ s3:PutObject                  │                                │           │ 
│   │                               │        │ s3:PutObjectLegalHold         │                                │           │ 
│   │                               │        │ s3:PutObjectRetention         │                                │           │ 
│   │                               │        │ s3:PutObjectTagging           │                                │           │ 
│   │                               │        │ s3:PutObjectVersionTagging    │                                │           │ 
│ + │ ${MyBucket.Arn}               │ Allow  │ s3:GetBucket*                 │ AWS:${MyFunction/ServiceRole}  │           │ 
│   │ ${MyBucket.Arn}/*             │        │ s3:GetObject*                 │                                │           │ 
│   │                               │        │ s3:List*                      │                                │           │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ ${MyBucket.Arn}/*             │ Allow  │ s3:GetObject                  │ AWS:${MyFunction/ServiceRole}  │           │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ ${MyFunction/ServiceRole.Arn} │ Allow  │ sts:AssumeRole                │ Service:lambda.amazonaws.com   │           │ 
├───┼───────────────────────────────┼────────┼───────────────────────────────┼────────────────────────────────┼───────────┤ 
│ + │ arn:${AWS::Partition}:s3:::{" │ Allow  │ s3:GetBucket*                 │ AWS:${Custom::CDKBucketDeploym │           │ 
│   │ Fn::Sub":"cdk-hnb659fds-asset │        │ s3:GetObject*                 │ ent8693BB64968944B69AAFB0CC9EB │           │ 
│   │ s-${AWS::AccountId}-${AWS::Re │        │ s3:List*                      │ 8756C/ServiceRole}             │           │ 
│   │ gion}"}                       │        │                               │                                │           │ 
│   │ arn:${AWS::Partition}:s3:::{" │        │                               │                                │           │ 
│   │ Fn::Sub":"cdk-hnb659fds-asset │        │                               │                                │           │ 
│   │ s-${AWS::AccountId}-${AWS::Re │        │                               │                                │           │ 
│   │ gion}"}/*                     │        │                               │                                │           │ 
└───┴───────────────────────────────┴────────┴───────────────────────────────┴────────────────────────────────┴───────────┘ 
IAM Policy Changes
┌───┬──────────────────────────────────────────────────────────┬──────────────────────────────────────────────────────────┐ 
│   │ Resource                                                 │ Managed Policy ARN                                       │ 
├───┼──────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────┤ 
│ + │ ${Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB │ arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLa │ 
│   │ 8756C/ServiceRole}                                       │ mbdaBasicExecutionRole                                   │ 
├───┼──────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────┤ 
│ + │ ${Custom::S3AutoDeleteObjectsCustomResourceProvider/Role │ {"Fn::Sub":"arn:${AWS::Partition}:iam::aws:policy/servic │ 
│   │ }                                                        │ e-role/AWSLambdaBasicExecutionRole"}                     │ 
├───┼──────────────────────────────────────────────────────────┼──────────────────────────────────────────────────────────┤ 
│ + │ ${MyFunction/ServiceRole}                                │ arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLa │ 
│   │                                                          │ mbdaBasicExecutionRole                                   │ 
└───┴──────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────┘ 
(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)? y 

CdkS3LambdaStack:  start: Building d7c71b0feef6812e8923395620bb28e50c0d5413572c070f5fc30f549a5ef3ec:current_account-current_region
CdkS3LambdaStack:  success: Built d7c71b0feef6812e8923395620bb28e50c0d5413572c070f5fc30f549a5ef3ec:current_account-current_region
CdkS3LambdaStack:  start: Publishing d7c71b0feef6812e8923395620bb28e50c0d5413572c070f5fc30f549a5ef3ec:current_account-current_region
CdkS3LambdaStack:  success: Published d7c71b0feef6812e8923395620bb28e50c0d5413572c070f5fc30f549a5ef3ec:current_account-current_region
CdkS3LambdaStack: deploying... [1/1]
CdkS3LambdaStack: creating CloudFormation changeset...
CdkS3LambdaStack |  0/15 | 20:34:06 | REVIEW_IN_PROGRESS   | AWS::CloudFormation::Stack  | CdkS3LambdaStack User Initiated
CdkS3LambdaStack |  0/15 | 20:34:13 | CREATE_IN_PROGRESS   | AWS::CloudFormation::Stack  | CdkS3LambdaStack User Initiated  
CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | MyFunction/ServiceRole (MyFunctionServiceRole3C357FF2)
CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265)       
CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::S3::Bucket             | MyBucket (MyBucketF68F3FF0)      
CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata          | CDKMetadata/Default (CDKMetadata)

CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::Lambda::LayerVersion   | DeployTestTxt/AwsCliLayer (DeployTestTxtAwsCliLayerEBD84BF7)
CdkS3LambdaStack |  0/15 | 20:34:17 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092)
CdkS3LambdaStack |  0/15 | 20:34:18 | CREATE_IN_PROGRESS   | AWS::CDK::Metadata          | CDKMetadata/Default (CDKMetadata)
 Resource creation Initiated
CdkS3LambdaStack |  0/15 | 20:34:18 | CREATE_IN_PROGRESS   | AWS::S3::Bucket             | MyBucket (MyBucketF68F3FF0) Resource creation Initiated
CdkS3LambdaStack |  0/15 | 20:34:18 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | MyFunction/ServiceRole (MyFunctionServiceRole3C357FF2) Resource creation Initiated
CdkS3LambdaStack |  0/15 | 20:34:18 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265) Resource creation Initiated
CdkS3LambdaStack |  0/15 | 20:34:18 | CREATE_IN_PROGRESS   | AWS::IAM::Role              | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092) Resource creation Initiated
CdkS3LambdaStack |  1/15 | 20:34:19 | CREATE_COMPLETE      | AWS::CDK::Metadata          | CDKMetadata/Default (CDKMetadata)

CdkS3LambdaStack |  1/15 | 20:34:24 | CREATE_IN_PROGRESS   | AWS::Lambda::LayerVersion   | DeployTestTxt/AwsCliLayer (DeployTestTxtAwsCliLayerEBD84BF7) Resource creation Initiated
CdkS3LambdaStack |  2/15 | 20:34:24 | CREATE_COMPLETE      | AWS::Lambda::LayerVersion   | DeployTestTxt/AwsCliLayer (DeployTestTxtAwsCliLayerEBD84BF7)
CdkS3LambdaStack |  3/15 | 20:34:32 | CREATE_COMPLETE      | AWS::S3::Bucket             | MyBucket (MyBucketF68F3FF0) 
CdkS3LambdaStack |  4/15 | 20:34:35 | CREATE_COMPLETE      | AWS::IAM::Role              | MyFunction/ServiceRole (MyFunctionServiceRole3C357FF2)
CdkS3LambdaStack |  5/15 | 20:34:35 | CREATE_COMPLETE      | AWS::IAM::Role              | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265)       
CdkS3LambdaStack |  6/15 | 20:34:35 | CREATE_COMPLETE      | AWS::IAM::Role              | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092)
CdkS3LambdaStack |  6/15 | 20:34:36 | CREATE_IN_PROGRESS   | AWS::IAM::Policy            | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole/DefaultPolicy (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF)
CdkS3LambdaStack |  6/15 | 20:34:36 | CREATE_IN_PROGRESS   | AWS::IAM::Policy            | MyFunction/ServiceRole/DefaultPolicy (MyFunctionServiceRoleDefaultPolicyB705ABD4)
CdkS3LambdaStack |  6/15 | 20:34:36 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)
CdkS3LambdaStack |  6/15 | 20:34:37 | CREATE_IN_PROGRESS   | AWS::S3::BucketPolicy       | MyBucket/Policy (MyBucketPolicyE7FBAC7B)
CdkS3LambdaStack |  6/15 | 20:34:37 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) Resource creation Initiated       
CdkS3LambdaStack |  6/15 | 20:34:38 | CREATE_IN_PROGRESS   | AWS::IAM::Policy            | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole/DefaultPolicy (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF) Resource creation Initiated
CdkS3LambdaStack |  6/15 | 20:34:38 | CREATE_IN_PROGRESS   | AWS::IAM::Policy            | MyFunction/ServiceRole/DefaultPolicy (MyFunctionServiceRoleDefaultPolicyB705ABD4) Resource creation Initiated
CdkS3LambdaStack |  6/15 | 20:34:38 | CREATE_IN_PROGRESS   | AWS::S3::BucketPolicy       | MyBucket/Policy (MyBucketPolicyE7FBAC7B) Resource creation Initiated
CdkS3LambdaStack |  6/15 | 20:34:38 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F) Eventual consistency check initiated
CdkS3LambdaStack |  7/15 | 20:34:39 | CREATE_COMPLETE      | AWS::S3::BucketPolicy       | MyBucket/Policy (MyBucketPolicyE7FBAC7B)
CdkS3LambdaStack |  8/15 | 20:34:43 | CREATE_COMPLETE      | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)
CdkS3LambdaStack |  8/15 | 20:34:44 | CREATE_IN_PROGRESS   | Custom::S3AutoDeleteObjects | MyBucket/AutoDeleteObjectsCustomResource/Default (MyBucketAutoDeleteObjectsCustomResource2C28D565)
CdkS3LambdaStack |  8/15 | 20:34:46 | CREATE_IN_PROGRESS   | Custom::S3AutoDeleteObjects | MyBucket/AutoDeleteObjectsCustomResource/Default (MyBucketAutoDeleteObjectsCustomResource2C28D565) Resource creation Initiated
CdkS3LambdaStack |  9/15 | 20:34:46 | CREATE_COMPLETE      | Custom::S3AutoDeleteObjects | MyBucket/AutoDeleteObjectsCustomResource/Default (MyBucketAutoDeleteObjectsCustomResource2C28D565)
CdkS3LambdaStack | 10/15 | 20:34:53 | CREATE_COMPLETE      | AWS::IAM::Policy            | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole/DefaultPolicy (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF)
CdkS3LambdaStack | 11/15 | 20:34:53 | CREATE_COMPLETE      | AWS::IAM::Policy            | MyFunction/ServiceRole/DefaultPolicy (MyFunctionServiceRoleDefaultPolicyB705ABD4)
CdkS3LambdaStack | 11/15 | 20:34:55 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536)
CdkS3LambdaStack | 11/15 | 20:34:55 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1)  
CdkS3LambdaStack | 11/15 | 20:34:56 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1) Resource creation Initiated
CdkS3LambdaStack | 11/15 | 20:34:57 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1) Eventual consistency check initiated
CdkS3LambdaStack | 11/15 | 20:35:00 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536) Resource creation Initiated  
CdkS3LambdaStack | 11/15 | 20:35:01 | CREATE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536) Eventual consistency check initiated
CdkS3LambdaStack | 12/15 | 20:35:02 | CREATE_COMPLETE      | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1)  
CdkS3LambdaStack | 13/15 | 20:35:06 | CREATE_COMPLETE      | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536)
CdkS3LambdaStack | 13/15 | 20:35:07 | CREATE_IN_PROGRESS   | Custom::CDKBucketDeployment | DeployTestTxt/CustomResource/Default (DeployTestTxtCustomResource5080A8AF)
13/15 Currently in progress: CdkS3LambdaStack, DeployTestTxtCustomResource5080A8AF
CdkS3LambdaStack | 13/15 | 20:35:53 | CREATE_IN_PROGRESS   | Custom::CDKBucketDeployment | DeployTestTxt/CustomResource/Default (DeployTestTxtCustomResource5080A8AF) Resource creation Initiated
CdkS3LambdaStack | 14/15 | 20:35:53 | CREATE_COMPLETE      | Custom::CDKBucketDeployment | DeployTestTxt/CustomResource/Default (DeployTestTxtCustomResource5080A8AF)
CdkS3LambdaStack | 15/15 | 20:35:54 | CREATE_COMPLETE      | AWS::CloudFormation::Stack  | CdkS3LambdaStack 

 ✅  CdkS3LambdaStack

✨  Deployment time: 116.88s

Stack ARN:
arn:aws:cloudformation:ap-northeast-1:xxxxxxxxxxxx:stack/CdkS3LambdaStack/786f4ca0-48e7-11ef-afc8-0eebc5a3269d

✨  Total time: 122.59s


6.作成確認
6-1.PowerShellで下記を実行

> aws s3 ls --profile <profile名>
PS C:\cdk-s3-lambda> aws s3 ls --profile testvault
2024-05-19 13:44:10 cdk-hnb659fds-assets-xxxxxxxxxxxx-ap-northeast-1

6-2.PowerShellで下記を実行

> aws lambda list-functions --profile <profile名>
PS C:\cdk-s3-lambda> aws lambda list-functions --profile testvault
{
    "Functions": [
        {
            "FunctionName": "CdkS3LambdaStack-MyFunction3BAA72D1-V4UWolFI00KO",
・・・・


7.お掃除
7-1.Powershellで下記を実行

> cdk destroy --profile <Profile名>
PS C:\cdk-s3-lambda> cdk destroy --profile testvault
Are you sure you want to delete: CdkS3LambdaStack (y/n)? y
CdkS3LambdaStack: destroying... [1/1]
CdkS3LambdaStack |   0 | 21:07:39 | DELETE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536)
CdkS3LambdaStack |   1 | 21:07:40 | DELETE_COMPLETE      | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1)    
CdkS3LambdaStack |   1 | 21:07:34 | DELETE_IN_PROGRESS   | AWS::CloudFormation::Stack  | CdkS3LambdaStack User Initiated    
CdkS3LambdaStack |   1 | 21:07:37 | DELETE_IN_PROGRESS   | AWS::CDK::Metadata          | CDKMetadata/Default (CDKMetadata)  
CdkS3LambdaStack |   1 | 21:07:37 | DELETE_IN_PROGRESS   | Custom::S3AutoDeleteObjects | MyBucket/AutoDeleteObjectsCustomResource/Default (MyBucketAutoDeleteObjectsCustomResource2C28D565)
CdkS3LambdaStack |   1 | 21:07:37 | DELETE_IN_PROGRESS   | Custom::CDKBucketDeployment | DeployTestTxt/CustomResource/Default (DeployTestTxtCustomResource5080A8AF)
CdkS3LambdaStack |   1 | 21:07:37 | DELETE_IN_PROGRESS   | AWS::Lambda::Function       | MyFunction (MyFunction3BAA72D1)    
CdkS3LambdaStack |   2 | 21:07:38 | DELETE_COMPLETE      | AWS::CDK::Metadata          | CDKMetadata/Default (CDKMetadata)  
CdkS3LambdaStack |   3 | 21:07:39 | DELETE_COMPLETE      | Custom::CDKBucketDeployment | DeployTestTxt/CustomResource/Default (DeployTestTxtCustomResource5080A8AF)
CdkS3LambdaStack |   3 | 21:07:41 | DELETE_IN_PROGRESS   | AWS::IAM::Policy            | MyFunction/ServiceRole/DefaultPolicy (MyFunctionServiceRoleDefaultPolicyB705ABD4)
CdkS3LambdaStack |   4 | 21:07:41 | DELETE_COMPLETE      | Custom::S3AutoDeleteObjects | MyBucket/AutoDeleteObjectsCustomResource/Default (MyBucketAutoDeleteObjectsCustomResource2C28D565)
CdkS3LambdaStack |   4 | 21:07:41 | DELETE_IN_PROGRESS   | AWS::S3::BucketPolicy       | MyBucket/Policy (MyBucketPolicyE7FBAC7B)
CdkS3LambdaStack |   4 | 21:07:41 | DELETE_IN_PROGRESS   | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)
CdkS3LambdaStack |   5 | 21:07:42 | DELETE_COMPLETE      | AWS::IAM::Policy            | MyFunction/ServiceRole/DefaultPolicy (MyFunctionServiceRoleDefaultPolicyB705ABD4)
CdkS3LambdaStack |   5 | 21:07:42 | DELETE_IN_PROGRESS   | AWS::IAM::Role              | MyFunction/ServiceRole (MyFunctionServiceRole3C357FF2)
CdkS3LambdaStack |   6 | 21:07:43 | DELETE_COMPLETE      | AWS::S3::BucketPolicy       | MyBucket/Policy (MyBucketPolicyE7FBAC7B)
CdkS3LambdaStack |   7 | 21:07:43 | DELETE_COMPLETE      | AWS::Lambda::Function       | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C81C01536)
CdkS3LambdaStack |   7 | 21:07:43 | DELETE_IN_PROGRESS   | AWS::IAM::Policy            | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole/DefaultPolicy (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF)
CdkS3LambdaStack |   7 | 21:07:43 | DELETE_IN_PROGRESS   | AWS::Lambda::LayerVersion   | DeployTestTxt/AwsCliLayer (DeployTestTxtAwsCliLayerEBD84BF7)
CdkS3LambdaStack |   8 | 21:07:44 | DELETE_COMPLETE      | AWS::IAM::Policy            | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole/DefaultPolicy (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRoleDefaultPolicy88902FDF)
CdkS3LambdaStack |   8 | 21:07:45 | DELETE_IN_PROGRESS   | AWS::IAM::Role              | Custom::CDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756C/ServiceRole (CustomCDKBucketDeployment8693BB64968944B69AAFB0CC9EB8756CServiceRole89A01265)
CdkS3LambdaStack |   9 | 21:07:45 | DELETE_COMPLETE      | AWS::Lambda::Function       | Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler (CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F)
CdkS3LambdaStack |   9 | 21:07:46 | DELETE_IN_PROGRESS   | AWS::IAM::Role              | Custom::S3AutoDeleteObjectsCustomResourceProvider/Role (CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092)
CdkS3LambdaStack |   9 | 21:07:46 | DELETE_IN_PROGRESS   | AWS::S3::Bucket             | MyBucket (MyBucketF68F3FF0)        
CdkS3LambdaStack |  10 | 21:07:47 | DELETE_COMPLETE      | AWS::S3::Bucket             | MyBucket (MyBucketF68F3FF0)        

 ✅  CdkS3LambdaStack: destroyed



感想

TypeScriptから勉強しないとよくわからないな、、、( ̄д ̄|||;

LightScreenを使ってみた


作業証跡を取る場合にWinShotを使用していたが、複数のディスプレイを使うことが増えた昨今、マルチディスプレイに対応していないので変わりがないか探してみたところ、LightScreenというものがあったので使ってみた。

LightScreenとは

スクリーンショットの保存と目録作成の面倒なプロセスを自動化できるシンプルなツール。ひとつ(または複数)のホットキーで呼び出すことができ、バックグラウンドプロセスとして動作し、ユーザの好みに応じてスクリーンショットファイルをディスクに保存できる。

ダウンロード

下記サイトからダウンロード
lightscreen.com.ar

使い方

インストールするとタスクバーに下記が追加される。

アイコンを右クリックをすると一覧が表示される
とりあえず[View Options]を表示してみる

[General]タブでは保存パスなども変更できる模様

[HotKey]タブでホットキーの変更も可能

取得してみる
右下にポップアップ(トーストというらしい。。)が表示される。



感想

ほとんどWinShotと同じように使えて、マルチスクリーンにも対応しているのでこれは便利。何気に取得したときにポップアップがあがるのがよい。
※WinShotはたまに取れてないときがあったりするので、、、

AWS IAM許可境界ポリシーについて調べてみた


IAM許可境界ポリシーとは

管理ポリシーを使用してアイデンティティベースのポリシーがIAMエンティティに付与できるアクセス許可の境界により、エンティティは、アイデンティティベースのポリシーとそのアクセス許可の境界の両方で許可されているアクションのみ実行できる。
??

まぁ簡潔にいうと下記の模様
 IAMポリシー & 許可境界ポリシー = 許可権限
※アンド条件のためどちらにも許可が含まれていないと許可されない

やること

S3と2つのLambdaを作成し、1つ目のLambdaにはS3からオブジェクトを取得できるポリシーを付与、2つ目のLambdaには1つ目と同じポリシーを付与し境界ポリシーでは取得ポリシーは付与しない形で作成し、1つ目のLambdaではS3からオブジェクトを取得でき、2つ目のLambdaでは取得できないという検証を行う。

実践

1.環境作成
1-1.下記CloudFormationを実行

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  BucketName:
    Type: String
    Description: 'The name of the S3 bucket'
    Default: 'my-default-s3-bucket'

Resources:
  MyBucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: !Ref BucketName

  LambdaS3GetBoundaryPolicy:
    Type: 'AWS::IAM::ManagedPolicy'
    Properties:
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: 'Allow'
            Action:
              - 'logs:*'
              - 's3:ListBucket'
            Resource: '*'

  LambdaExecutionRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: 'Allow'
            Principal:
              Service: 'lambda.amazonaws.com'
            Action: 'sts:AssumeRole'
      Policies:
        - PolicyName: 'LambdaS3AccessPolicy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: 'Allow'
                Action: 
                  - 's3:GetObject'
                Resource: 
                  - !Sub 'arn:aws:s3:::${BucketName}/*'

  LambdaExecutionRoleWithBoundary:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: 'Allow'
            Principal:
              Service: 'lambda.amazonaws.com'
            Action: 'sts:AssumeRole'
      Policies:
        - PolicyName: 'LambdaS3AccessPolicy'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: 'Allow'
                Action: 
                  - 's3:GetObject'
                Resource: 
                  - !Sub 'arn:aws:s3:::${BucketName}/*'
      PermissionsBoundary: !Ref LambdaS3GetBoundaryPolicy

  LambdaFunction1:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: 'LambdaFunction1'
      Handler: 'index.handler'
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        ZipFile: |
          import boto3
          import os

          def handler(event, context):
              s3 = boto3.client('s3')
              bucket_name = os.environ['BUCKET_NAME']
              key = 'test.txt'
              
              try:
                  response = s3.get_object(Bucket=bucket_name, Key=key)
                  data = response['Body'].read().decode('utf-8')
                  print('Data:', data)
              except Exception as e:
                  print('Error:', str(e))
      Runtime: 'python3.9'
      Environment:
        Variables:
          BUCKET_NAME: !Ref BucketName

  LambdaFunction2:
    Type: 'AWS::Lambda::Function'
    Properties:
      FunctionName: 'LambdaFunction2'
      Handler: 'index.handler'
      Role: !GetAtt LambdaExecutionRoleWithBoundary.Arn
      Code:
        ZipFile: |
          import boto3
          import os

          def handler(event, context):
              s3 = boto3.client('s3')
              bucket_name = os.environ['BUCKET_NAME']
              key = 'test.txt'
              
              try:
                  response = s3.get_object(Bucket=bucket_name, Key=key)
                  data = response['Body'].read().decode('utf-8')
                  print('Data:', data)
              except Exception as e:
                  print('Error:', str(e))
      Runtime: 'python3.9'
      Environment:
        Variables:
          BUCKET_NAME: !Ref BucketName

※1つ目のLambdaのロールには許可境界ポリシーはなし

※2つ目のLambdaのロールには許可境界ポリシーはあり
 ただし許可境界ポリシーにはGetがないためオブジェクトは取得できない想定


2.準備
2-1.「test.txt」という名前のファイルを適当に作成し、作成したS3バケットにアップロード

3.Lambda実行
3-1.Lambda1でテストを実行し、test.txtの中身が取得できることを確認
※テストの中身はデフォルトで可

3-2.Lambda2でテストを実行し、AccessDenyでデータが取得できないことを確認



感想

ポリシーに追加したらよさそうだが、数が多くなると許可境界ポリシーが役に立つらしい。

AWS LambdaからS3への接続をS3Endpointを使用し、S3バケットポリシーで接続元を制限してみた

やること

こうではなく

こうする
バケットポリシーのconditionでS3Endpointのみを許可するように変更

実践!

1.環境作成
1-1.CloudFormationで下記を実行
※StringNotEqualsIfExists:に何かしらのアカウントを許可する。
 許可しないとファイルのアップロードができない。

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  MyVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: MyVPC

  InternetGateway:
    Type: AWS::EC2::InternetGateway

  AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref MyVPC
      InternetGatewayId: !Ref InternetGateway

  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true
      AvailabilityZone: !Select [0, !GetAZs '']

  PrivateSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MyVPC
      CidrBlock: 10.0.2.0/24
      AvailabilityZone: !Select [0, !GetAZs '']

  NatGatewayEIP:
    Type: AWS::EC2::EIP

  NatGateway:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGatewayEIP.AllocationId
      SubnetId: !Ref PublicSubnet

  PrivateSubnetRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC

  PublicSubnetRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref MyVPC

  PublicSubnetRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PublicSubnetRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PrivateSubnetRoute:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateSubnetRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref NatGateway

  PublicSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PublicSubnet
      RouteTableId: !Ref PublicSubnetRouteTable

  PrivateSubnetRouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref PrivateSubnet
      RouteTableId: !Ref PrivateSubnetRouteTable

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties: 
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - Effect: "Allow"
            Principal: 
              Service: "lambda.amazonaws.com"
            Action: "sts:AssumeRole"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
        - arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

  LambdaSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Allow Lambda access to VPC
      VpcId: !Ref MyVPC

  MyLambdaFunction:
    Type: AWS::Lambda::Function
    Properties:
      Handler: index.handler
      Role: !GetAtt LambdaExecutionRole.Arn
      Code:
        ZipFile: |
          import boto3
          def handler(event, context):
              s3 = boto3.client('s3')
              response = s3.get_object(Bucket='my-s3-bucket-example', Key='test.txt')
              data = response['Body'].read()
              print(data)
      Runtime: python3.9
      VpcConfig:
        SubnetIds:
          - !Ref PrivateSubnet
        SecurityGroupIds:
          - !Ref LambdaSecurityGroup

  MyS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-s3-bucket-example1234567899999
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  MyS3BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref MyS3Bucket
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Deny
            Principal: "*"
            Action: "s3:*"
            Resource:
              - !Sub "arn:aws:s3:::my-s3-bucket-example1234567899999"
              - !Sub "arn:aws:s3:::my-s3-bucket-example1234567899999/*"
            Condition:
              StringNotEquals:
                "aws:SourceVpce": !Ref S3VPCEndpoint
              StringNotEqualsIfExists:
                "aws:PrincipalArn": "arn:aws:iam::xxxxxxxxxxxx:root"

  S3VPCEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref MyVPC
      ServiceName: !Sub com.amazonaws.${AWS::Region}.s3
      VpcEndpointType: Gateway
      RouteTableIds:
        - !Ref PrivateSubnetRouteTable

2.テスト
2-1.作成したS3バケットにtest.txtをアップロード
2-2.作成したLambdaでテストを行い、test.txtの中身が表示されることを確認

感想

NatGateway通っている可能性あるので明示的にEndpointを指定したほうがよさげ

AWS KMSのデフォルトのキーポリシーにrootの権限がついている件


AWS KMSのデフォルトのキーポリシーにrootの権限がついている件について調べてみた。

理由

rootがあることでIAMポリシーからキーポリシーへアクセスるできるようになる模様。
KMSキーが管理不要になるリスクを回避するためにデフォルトでrootアカウントに権限を振っている模様。
docs.aws.amazon.com

調査

rootなしのキーポリシーを作成しIAMポリシーの権限でKMSキーにアクセスできないことを確認する。
その後rootを付与しIAMポリシーの権限でアクセスできることを確認する。

やること

CloudFormationでKMSで暗号化されているS3バケットと、S3へ接続するためのLambdaを作成し、キーポリシーを操作して接続有無を確認する。

実践!

1.環境構築
1-1.下記CloudFormationを実行
※キーポリシー内のユーザとログインしているユーザを合わせること。
※今回は[testuser]を作成し、そのユーザでAWSコンソールにログインしてCloudFormationを実行する。

AWSTemplateFormatVersion: '2010-09-09'
Resources:
  # KMSキーの作成
  MyKMSKey:
    Type: "AWS::KMS::Key"
    Properties: 
      Description: "KMS Key for S3 encryption"
      KeyPolicy: 
        Version: "2012-10-17"
        Id: "key-default-1"
        Statement: 
          - Sid: "Enable IAM User Permissions"
            Effect: "Allow"
            Principal: 
              AWS: 
                - !Sub "arn:aws:iam::${AWS::AccountId}:user/testuser"
            Action: "kms:*"
            Resource: "*"

  # IAMロールの作成
  MyLambdaExecutionRole:
    Type: "AWS::IAM::Role"
    Properties: 
      AssumeRolePolicyDocument: 
        Version: "2012-10-17"
        Statement: 
          - Effect: "Allow"
            Principal: 
              Service: 
                - "lambda.amazonaws.com"
            Action: 
              - "sts:AssumeRole"
      Policies:
        - PolicyName: "LambdaS3KMSEncryptionPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action:
                  - "s3:GetObject"
                  - "s3:PutObject"
                Resource: 
                  - !Sub "arn:aws:s3:::${MyS3Bucket}/*"
              - Effect: "Allow"
                Action:
                  - "kms:Decrypt"
                  - "kms:Encrypt"
                  - "kms:GenerateDataKey"
                Resource: 
                  - !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/${MyKMSKey}"
                  
  # S3バケットの作成
  MyS3Bucket:
    Type: "AWS::S3::Bucket"
    Properties: 
      BucketName: !Sub "${AWS::StackName}-mybucket"
      BucketEncryption: 
        ServerSideEncryptionConfiguration: 
          - ServerSideEncryptionByDefault: 
              SSEAlgorithm: "aws:kms"
              KMSMasterKeyID: !Ref MyKMSKey

  # Lambda関数の作成
  MyLambdaFunction:
    Type: "AWS::Lambda::Function"
    Properties: 
      FunctionName: !Sub "${AWS::StackName}-MyLambdaFunction"
      Handler: "index.handler"
      Role: !GetAtt MyLambdaExecutionRole.Arn
      Code: 
        ZipFile: |
          import json
          import boto3

          s3 = boto3.client('s3')

          def handler(event, context):
              bucket = event['bucket']
              key = event['key']
              response = s3.get_object(Bucket=bucket, Key=key)
              data = response['Body'].read().decode('utf-8')
              return {
                  'statusCode': 200,
                  'body': json.dumps(data)
              }
      Runtime: "python3.9"
      Environment: 
        Variables: 
          BUCKET_NAME: !Ref MyS3Bucket


2.S3バケットにサンプルファイルをアップロード
2-1.AWS - [S3] - 作成したS3バケットを選択

2-2.サンプルファイルをアップロード
※今回は[test.txt]というファイルをアップロードする。


3.Lambda実行(失敗パターン)
3-1.AWS - [Lambda] - 作成した関数を選択

3-2.[Test]

3-3.下記を入力
 イベント名:イベント名
 イベントJSON:下記を入力

{
  "key": "test.txt",
  "bucekt": "test-stack01-mybucket"
}


3-4.[保存]

3-5.[Test]

3-6.S3への接続に失敗すること


4.Lambda実行(成功パターン)
4-1.AWS - [KMS] - [カスタマー管理型のキー] - 作成したKMSキーを選択

4-2.キーポリシーの[編集]

4-3.下記に変更

{
    "Version": "2012-10-17",
    "Id": "key-default-1",
    "Statement": [
        {
            "Sid": "Enable IAM User Permissions",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxxxxxxxx:user/testuser"
            },
            "Action": "kms:*",
            "Resource": "*"
        },
        {
            "Sid": "Enable IAM User Permissions",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::xxxxxxxxxxxx:root"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}


4-4.[変更の保存]

4-5.AWS - [Lambda] - 作成した関数を選択

4-6.[Test]

4-7.200OKが返ってきて、S3にアップロードしたファイルの中身が表示されること
※キーポリシーにrootが追加されることでIAMに付与しているKMSポリシーが生き、接続できるようになる。



感想

KMSポリシーにIAMを設定しなくてもIAMポリシーのKMS設定が生きるロジックが不明だったが理解できた!