iT邦幫忙

2023 iThome 鐵人賽

DAY 5
0
DevOps

CDK 從 0 開始打造靈活自如的 IaC系列 第 5

05 - 使用 CDK 定義 AWS 計算資源

  • 分享至 

  • xImage
  •  

本篇文章內有:

  • 使用 AWS CDK 定義 AWS EC2 執行個體 (Instance)
  • 使用 AWS CDK 定義 AWS Lambda 函數 (Function)

使用 AWS CDK 定義 AWS EC2 執行個體 (Instance)

在初步編寫簡單的 AWS CDK 之後,這次我們要來做稍微進階一點的應用,有了儲存檔案的地方,再來就是要有可以處理這些檔案的單元。

我們用同一個專案,繼續在下面新增程式碼。

new cdk.aws_ec2.Instance(this, 'instance');

結果發現下面有一條憤怒的紅色蚯蚓。

Expected 3 arguments, but got 2. ts(2554)

原來這次的屬性變成必填項目了,來看一下有哪些是一定要給的。

Type '{}' is missing the following properties from type 'InstanceProps': vpc, instanceType, machineImagets (2345)

所以在這之前,我們要先來建立 Amazon VPC 作為放置 AWS EC2 執行個體的地點,在上面加上這些程式碼。

const vpc = new cdk.aws_ec2.Vpc(this, 'vpc');	

接下來,可以把下面的屬性物件放進去,讓 AWS CDK 建立一台 AWS EC2 執行個體。

{
  vpc,
  instanceType: cdk.aws_ec2.InstanceType.of(
    cdk.aws_ec2.InstanceClass.BURSTABLE4_GRAVITON,
    cdk.aws_ec2.InstanceSize.SMALL,
  ),
  machineImage: new cdk.aws_ec2.AmazonLinuxImage({
    generation: cdk.aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
    cpuType: cdk.aws_ec2.AmazonLinuxCpuType.ARM_64,
  }),
}

這邊來解釋各個屬性的內容:

  • vpc:這是我們剛才新建立的 Amazon VPC 。
  • instanceType:描述了這個 AWS EC2 執行個體的類型,這裡選用的是涵蓋在免費試用項目中的機型 (t4g-small) 。
  • machineImage:指定這台 AWS EC2 執行個體要使用什麼 Amazon Machine Image (AMI) ,也就是他提供啟動執行個體所需的資訊以及映像,這同樣也是使用免費試用項目內的 Amazon Linux 2 AMI 。

這次的變更更誇張了,才兩個物件就造成這麼多資源的新增。

IAM Statement Changes
┌───┬────────┬────────┬────────┬────────┬──────────┐
│   │ Resour │ Effect │ Action │ Princi │ Conditio │ 
│   │ ce     │        │        │ pal    │ n        │ 
├───┼────────┼────────┼────────┼────────┼──────────┤ 
│ + │ ${Cust │ Allow  │ sts:As │ Servic │          │ 
│   │ om::Vp │        │ sumeRo │ e:lamb │          │ 
│   │ cRestr │        │ le     │ da.ama │          │ 
│   │ ictDef │        │        │ zonaws │          │ 
│   │ aultSG │        │        │ .com   │          │ 
│   │ Custom │        │        │        │          │ 
│   │ Resour │        │        │        │          │ 
│   │ ceProv │        │        │        │          │ 
│   │ ider/R │        │        │        │          │ 
│   │ ole.Ar │        │        │        │          │ 
│   │ n}     │        │        │        │          │ 
├───┼────────┼────────┼────────┼────────┼──────────┤ 
│ + │ ${inst │ Allow  │ sts:As │ Servic │          │ 
│   │ ance/I │        │ sumeRo │ e:ec2. │          │ 
│   │ nstanc │        │ le     │ amazon │          │ 
│   │ eRole. │        │        │ aws.co │          │ 
│   │ Arn}   │        │        │ m      │          │ 
├───┼────────┼────────┼────────┼────────┼──────────┤ 
│ + │ arn:${ │ Allow  │ ec2:Au │ AWS:${ │          │ 
│   │ AWS::P │        │ thoriz │ Custom │          │ 
│   │ artiti │        │ eSecur │ ::VpcR │          │ 
│   │ on}:ec │        │ ityGro │ estric │          │ 
│   │ 2:${AW │        │ upEgre │ tDefau │          │ 
│   │ S::Reg │        │ ss     │ ltSGCu │          │ 
│   │ ion}:$ │        │ ec2:Au │ stomRe │          │ 
│   │ {AWS:: │        │ thoriz │ source │          │ 
│   │ Accoun │        │ eSecur │ Provid │          │ 
│   │ tId}:s │        │ ityGro │ er/Rol │          │ 
│   │ ecurit │        │ upIngr │ e}     │          │ 
│   │ y-grou │        │ ess    │        │          │ 
│   │ p/${vp │        │ ec2:Re │        │          │ 
│   │ cA2121 │        │ vokeSe │        │          │ 
│   │ C38.De │        │ curity │        │          │ 
│   │ faultS │        │ GroupE │        │          │ 
│   │ ecurit │        │ gress  │        │          │ 
│   │ yGroup │        │ ec2:Re │        │          │ 
│   │ }      │        │ vokeSe │        │          │ 
│   │        │        │ curity │        │          │ 
│   │        │        │ GroupI │        │          │ 
│   │        │        │ ngress │        │          │ 
└───┴────────┴────────┴────────┴────────┴──────────┘ 
IAM Policy Changes
┌───┬──────────────────────┬───────────────────────┐ 
│   │ Resource             │ Managed Policy ARN    │ 
├───┼──────────────────────┼───────────────────────┤ 
│ + │ ${Custom::VpcRestric │ {"Fn::Sub":"arn:${AWS │ 
│   │ tDefaultSGCustomReso │ ::Partition}:iam::aws │ 
│   │ urceProvider/Role}   │ :policy/service-role/ │ 
│   │                      │ AWSLambdaBasicExecuti │ 
│   │                      │ onRole"}              │ 
└───┴──────────────────────┴───────────────────────┘ 
Security Group Changes
┌───┬────────────┬─────┬────────────┬──────────────┐
│   │ Group      │ Dir │ Protocol   │ Peer         │ 
├───┼────────────┼─────┼────────────┼──────────────┤ 
│ + │ ${instance │ Out │ Everything │ Everyone (IP │ 
│   │ /InstanceS │     │            │ v4)          │ 
│   │ ecurityGro │     │            │              │ 
│   │ up.GroupId │     │            │              │ 
│   │ }          │     │            │              │ 
└───┴────────────┴─────┴────────────┴──────────────┘ 
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)

Parameters
[+] Parameter SsmParameterValue:--aws--service--ami-amazon-linux-latest--amzn2-ami-hvm-arm64-gp2:C96584B6-F00A-464E-AD19-53AFF4B05118.Parameter SsmParameterValueawsserviceamiamazonlinuxlatestamzn2amihvmarm64gp2C96584B6F00A464EAD1953AFF4B05118Parameter: {"Type":"AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>","Default":"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-arm64-gp2"}

Resources
[+] AWS::EC2::VPC vpc vpcA2121C38
[+] AWS::EC2::Subnet vpc/PublicSubnet1/Subnet vpcPublicSubnet1Subnet2E65531E
[+] AWS::EC2::RouteTable vpc/PublicSubnet1/RouteTable
 vpcPublicSubnet1RouteTable48A2DF9B
[+] AWS::EC2::SubnetRouteTableAssociation vpc/PublicSubnet1/RouteTableAssociation vpcPublicSubnet1RouteTableAssociation5D3F4579
[+] AWS::EC2::Route vpc/PublicSubnet1/DefaultRoute vpcPublicSubnet1DefaultRoute10708846
[+] AWS::EC2::EIP vpc/PublicSubnet1/EIP vpcPublicSubnet1EIPDA49DCBE
[+] AWS::EC2::NatGateway vpc/PublicSubnet1/NATGateway
 vpcPublicSubnet1NATGateway9C16659E
[+] AWS::EC2::Subnet vpc/PublicSubnet2/Subnet vpcPublicSubnet2Subnet009B674F
[+] AWS::EC2::RouteTable vpc/PublicSubnet2/RouteTable
 vpcPublicSubnet2RouteTableEB40D4CB
[+] AWS::EC2::SubnetRouteTableAssociation vpc/PublicSubnet2/RouteTableAssociation vpcPublicSubnet2RouteTableAssociation21F81B59
[+] AWS::EC2::Route vpc/PublicSubnet2/DefaultRoute vpcPublicSubnet2DefaultRouteA1EC0F60
[+] AWS::EC2::EIP vpc/PublicSubnet2/EIP vpcPublicSubnet2EIP9B3743B1
[+] AWS::EC2::NatGateway vpc/PublicSubnet2/NATGateway
 vpcPublicSubnet2NATGateway9B8AE11A
[+] AWS::EC2::Subnet vpc/PrivateSubnet1/Subnet vpcPrivateSubnet1Subnet934893E8
[+] AWS::EC2::RouteTable vpc/PrivateSubnet1/RouteTable vpcPrivateSubnet1RouteTableB41A48CC
[+] AWS::EC2::SubnetRouteTableAssociation vpc/PrivateSubnet1/RouteTableAssociation vpcPrivateSubnet1RouteTableAssociation67945127
[+] AWS::EC2::Route vpc/PrivateSubnet1/DefaultRoute vpcPrivateSubnet1DefaultRoute1AA8E2E5
[+] AWS::EC2::Subnet vpc/PrivateSubnet2/Subnet vpcPrivateSubnet2Subnet7031C2BA
[+] AWS::EC2::RouteTable vpc/PrivateSubnet2/RouteTable vpcPrivateSubnet2RouteTable7280F23E
[+] AWS::EC2::SubnetRouteTableAssociation vpc/PrivateSubnet2/RouteTableAssociation vpcPrivateSubnet2RouteTableAssociation007E94D3
[+] AWS::EC2::Route vpc/PrivateSubnet2/DefaultRoute vpcPrivateSubnet2DefaultRouteB0E07F99
[+] AWS::EC2::InternetGateway vpc/IGW vpcIGWE57CBDCA 
[+] AWS::EC2::VPCGatewayAttachment vpc/VPCGW vpcVPCGW7984C166
[+] Custom::VpcRestrictDefaultSG vpc/RestrictDefaultSecurityGroupCustomResource vpcRestrictDefaultSecurityGroupCustomResourceA6EBC6D0
[+] AWS::IAM::Role Custom::VpcRestrictDefaultSGCustomResourceProvider/Role CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0
[+] AWS::Lambda::Function Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E
[+] AWS::EC2::SecurityGroup instance/InstanceSecurityGroup instanceInstanceSecurityGroup725C795D
[+] AWS::IAM::Role instance/InstanceRole instanceInstanceRoleF436EE92
[+] AWS::IAM::InstanceProfile instance/InstanceProfile instanceInstanceProfile931F14E3
[+] AWS::EC2::Instance instance instanceB7CCE687     

馬上就來把他們部署上去。

✨  Synthesis time: 4.26s

AppStack:  start: Building b654d8857488c1cce508a9c4eda24830e21e1c0fc9baf3633015b41338b9a337:current_account-current_region
AppStack:  success: Built b654d8857488c1cce508a9c4eda24830e21e1c0fc9baf3633015b41338b9a337:current_account-current_region
AppStack:  start: Publishing b654d8857488c1cce508a9c4eda24830e21e1c0fc9baf3633015b41338b9a337:current_account-current_region
AppStack:  success: Published b654d8857488c1cce508a9c4eda24830e21e1c0fc9baf3633015b41338b9a337: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
┌───┬────────┬────────┬────────┬────────┬──────────┐
│   │ Resour │ Effect │ Action │ Princi │ Conditio │
│   │ ce     │        │        │ pal    │ n        │
├───┼────────┼────────┼────────┼────────┼──────────┤
│ + │ ${Cust │ Allow  │ sts:As │ Servic │          │
│   │ om::Vp │        │ sumeRo │ e:lamb │          │
│   │ cRestr │        │ le     │ da.ama │          │
│   │ ictDef │        │        │ zonaws │          │
│   │ aultSG │        │        │ .com   │          │
│   │ Custom │        │        │        │          │
│   │ Resour │        │        │        │          │
│   │ ceProv │        │        │        │          │
│   │ ider/R │        │        │        │          │
│   │ ole.Ar │        │        │        │          │
│   │ n}     │        │        │        │          │
├───┼────────┼────────┼────────┼────────┼──────────┤
│ + │ ${inst │ Allow  │ sts:As │ Servic │          │
│   │ ance/I │        │ sumeRo │ e:ec2. │          │
│   │ nstanc │        │ le     │ amazon │          │
│   │ eRole. │        │        │ aws.co │          │
│   │ Arn}   │        │        │ m      │          │
├───┼────────┼────────┼────────┼────────┼──────────┤
│ + │ arn:${ │ Allow  │ ec2:Au │ AWS:${ │          │
│   │ AWS::P │        │ thoriz │ Custom │          │
│   │ artiti │        │ eSecur │ ::VpcR │          │
│   │ on}:ec │        │ ityGro │ estric │          │
│   │ 2:${AW │        │ upEgre │ tDefau │          │
│   │ S::Reg │        │ ss     │ ltSGCu │          │
│   │ ion}:$ │        │ ec2:Au │ stomRe │          │
│   │ {AWS:: │        │ thoriz │ source │          │
│   │ Accoun │        │ eSecur │ Provid │          │
│   │ tId}:s │        │ ityGro │ er/Rol │          │
│   │ ecurit │        │ upIngr │ e}     │          │
│   │ y-grou │        │ ess    │        │          │
│   │ p/${vp │        │ ec2:Re │        │          │
│   │ cA2121 │        │ vokeSe │        │          │
│   │ C38.De │        │ curity │        │          │
│   │ faultS │        │ GroupE │        │          │
│   │ ecurit │        │ gress  │        │          │
│   │ yGroup │        │ ec2:Re │        │          │
│   │ }      │        │ vokeSe │        │          │
│   │        │        │ curity │        │          │
│   │        │        │ GroupI │        │          │
│   │        │        │ ngress │        │          │
└───┴────────┴────────┴────────┴────────┴──────────┘
IAM Policy Changes
┌───┬──────────────────────┬───────────────────────┐
│   │ Resource             │ Managed Policy ARN    │
├───┼──────────────────────┼───────────────────────┤
│ + │ ${Custom::VpcRestric │ {"Fn::Sub":"arn:${AWS │
│   │ tDefaultSGCustomReso │ ::Partition}:iam::aws │
│   │ urceProvider/Role}   │ :policy/service-role/ │
│   │                      │ AWSLambdaBasicExecuti │
│   │                      │ onRole"}              │
└───┴──────────────────────┴───────────────────────┘
Security Group Changes
┌───┬────────────┬─────┬────────────┬──────────────┐
│   │ Group      │ Dir │ Protocol   │ Peer         │
├───┼────────────┼─────┼────────────┼──────────────┤
│ + │ ${instance │ Out │ Everything │ Everyone (IP │
│   │ /InstanceS │     │            │ v4)          │
│   │ ecurityGro │     │            │              │
│   │ up.GroupId │     │            │              │
│   │ }          │     │            │              │
└───┴────────────┴─────┴────────────┴──────────────┘
(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
AppStack: deploying... [1/1]
AppStack: creating CloudFormation changeset...
AppStack |  0/33 | 12:00:07 AM | UPDATE_IN_PROGRESS   | AWS::CloudFormation::Stack            | AppStack User Initiated
AppStack |  0/33 | 12:00:11 AM | CREATE_IN_PROGRESS   | AWS::EC2::InternetGateway             | vpc/IGW (vpcIGWE57CBDCA)
AppStack |  0/33 | 12:00:11 AM | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | vpc/PublicSubnet1/EIP (vpcPublicSubnet1EIPDA49DCBE)
AppStack |  0/33 | 12:00:11 AM | CREATE_IN_PROGRESS   | AWS::EC2::VPC                         | vpc (vpcA2121C38)
AppStack |  0/33 | 12:00:11 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | instance/InstanceRole (instanceInstanceRoleF436EE92)
AppStack |  0/33 | 12:00:11 AM | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | vpc/PublicSubnet2/EIP (vpcPublicSubnet2EIP9B3743B1)
AppStack |  0/33 | 12:00:12 AM | UPDATE_IN_PROGRESS   | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
AppStack |  0/33 | 12:00:12 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | instance/InstanceRole (instanceInstanceRoleF436EE92) Resource creation Initiated
AppStack |  0/33 | 12:00:12 AM | CREATE_IN_PROGRESS   | AWS::EC2::InternetGateway             | vpc/IGW (vpcIGWE57CBDCA) Resource creation Initiated
AppStack |  0/33 | 12:00:13 AM | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | vpc/PublicSubnet2/EIP (vpcPublicSubnet2EIP9B3743B1) Resource creation Initiated
AppStack |  0/33 | 12:00:13 AM | CREATE_IN_PROGRESS   | AWS::EC2::EIP                         | vpc/PublicSubnet1/EIP (vpcPublicSubnet1EIPDA49DCBE) Resource creation Initiated
AppStack |  1/33 | 12:00:13 AM | UPDATE_COMPLETE      | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
AppStack |  1/33 | 12:00:13 AM | CREATE_IN_PROGRESS   | AWS::EC2::VPC                         | vpc (vpcA2121C38) Resource creation Initiated
AppStack |  2/33 | 12:00:24 AM | CREATE_COMPLETE      | AWS::EC2::VPC                         | vpc (vpcA2121C38)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::SecurityGroup               | instance/InstanceSecurityGroup (instanceInstanceSecurityGroup725C795D)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PublicSubnet2/RouteTable (vpcPublicSubnet2RouteTableEB40D4CB)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PrivateSubnet1/RouteTable (vpcPrivateSubnet1RouteTableB41A48CC)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PrivateSubnet2/RouteTable (vpcPrivateSubnet2RouteTable7280F23E)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PublicSubnet1/RouteTable (vpcPublicSubnet1RouteTable48A2DF9B)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PublicSubnet2/Subnet (vpcPublicSubnet2Subnet009B674F)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PrivateSubnet2/Subnet (vpcPrivateSubnet2Subnet7031C2BA)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PublicSubnet1/Subnet (vpcPublicSubnet1Subnet2E65531E)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PrivateSubnet1/Subnet (vpcPrivateSubnet1Subnet934893E8)
AppStack |  2/33 | 12:00:25 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0)
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PublicSubnet2/RouteTable (vpcPublicSubnet2RouteTableEB40D4CB) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PrivateSubnet2/RouteTable (vpcPrivateSubnet2RouteTable7280F23E) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PublicSubnet1/RouteTable (vpcPublicSubnet1RouteTable48A2DF9B) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::RouteTable                  | vpc/PrivateSubnet1/RouteTable (vpcPrivateSubnet1RouteTableB41A48CC) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PrivateSubnet2/Subnet (vpcPrivateSubnet2Subnet7031C2BA) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PublicSubnet2/Subnet (vpcPublicSubnet2Subnet009B674F) Resource creation Initiated
AppStack |  2/33 | 12:00:26 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PublicSubnet1/Subnet (vpcPublicSubnet1Subnet2E65531E) Resource creation Initiated
AppStack |  2/33 | 12:00:27 AM | CREATE_IN_PROGRESS   | AWS::EC2::Subnet                      | vpc/PrivateSubnet1/Subnet (vpcPrivateSubnet1Subnet934893E8) Resource creation Initiated
AppStack |  3/33 | 12:00:27 AM | CREATE_COMPLETE      | AWS::IAM::Role                        | instance/InstanceRole (instanceInstanceRoleF436EE92)
AppStack |  4/33 | 12:00:28 AM | CREATE_COMPLETE      | AWS::EC2::InternetGateway             | vpc/IGW (vpcIGWE57CBDCA)
AppStack |  4/33 | 12:00:28 AM | CREATE_IN_PROGRESS   | AWS::IAM::InstanceProfile             | instance/InstanceProfile (instanceInstanceProfile931F14E3)
AppStack |  5/33 | 12:00:28 AM | CREATE_COMPLETE      | AWS::EC2::EIP                         | vpc/PublicSubnet2/EIP (vpcPublicSubnet2EIP9B3743B1)
AppStack |  6/33 | 12:00:29 AM | CREATE_COMPLETE      | AWS::EC2::EIP                         | vpc/PublicSubnet1/EIP (vpcPublicSubnet1EIPDA49DCBE)
AppStack |  6/33 | 12:00:29 AM | CREATE_IN_PROGRESS   | AWS::EC2::VPCGatewayAttachment        | vpc/VPCGW (vpcVPCGW7984C166)
AppStack |  7/33 | 12:00:29 AM | CREATE_COMPLETE      | AWS::EC2::Subnet                      | vpc/PrivateSubnet2/Subnet (vpcPrivateSubnet2Subnet7031C2BA)
AppStack |  7/33 | 12:00:29 AM | CREATE_IN_PROGRESS   | AWS::EC2::VPCGatewayAttachment        | vpc/VPCGW (vpcVPCGW7984C166) Resource creation Initiated
AppStack |  8/33 | 12:00:29 AM | CREATE_COMPLETE      | AWS::EC2::Subnet                      | vpc/PrivateSubnet1/Subnet (vpcPrivateSubnet1Subnet934893E8)
AppStack |  9/33 | 12:00:29 AM | CREATE_COMPLETE      | AWS::EC2::Subnet                      | vpc/PublicSubnet1/Subnet (vpcPublicSubnet1Subnet2E65531E)
AppStack | 10/33 | 12:00:29 AM | CREATE_COMPLETE      | AWS::EC2::Subnet                      | vpc/PublicSubnet2/Subnet (vpcPublicSubnet2Subnet009B674F)
AppStack | 10/33 | 12:00:29 AM | CREATE_IN_PROGRESS   | AWS::IAM::InstanceProfile             | instance/InstanceProfile (instanceInstanceProfile931F14E3) Resource creation Initiated
AppStack | 10/33 | 12:00:30 AM | CREATE_IN_PROGRESS   | AWS::EC2::SecurityGroup               | instance/InstanceSecurityGroup (instanceInstanceSecurityGroup725C795D) Resource creation Initiated
AppStack | 11/33 | 12:00:31 AM | CREATE_COMPLETE      | AWS::EC2::SecurityGroup               | instance/InstanceSecurityGroup (instanceInstanceSecurityGroup725C795D)
AppStack | 12/33 | 12:00:36 AM | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | vpc/PublicSubnet2/RouteTable (vpcPublicSubnet2RouteTableEB40D4CB)
AppStack | 13/33 | 12:00:36 AM | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | vpc/PrivateSubnet2/RouteTable (vpcPrivateSubnet2RouteTable7280F23E)
AppStack | 14/33 | 12:00:36 AM | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | vpc/PublicSubnet1/RouteTable (vpcPublicSubnet1RouteTable48A2DF9B)
AppStack | 14/33 | 12:00:37 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet2/RouteTableAssociation (vpcPrivateSubnet2RouteTableAssociation007E94D3)
AppStack | 14/33 | 12:00:37 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet2/RouteTableAssociation (vpcPublicSubnet2RouteTableAssociation21F81B59)
AppStack | 14/33 | 12:00:37 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet1/RouteTableAssociation (vpcPublicSubnet1RouteTableAssociation5D3F4579)
AppStack | 14/33 | 12:00:38 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet2/RouteTableAssociation (vpcPublicSubnet2RouteTableAssociation21F81B59) Resource creation Initiated
AppStack | 14/33 | 12:00:38 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet1/RouteTableAssociation (vpcPublicSubnet1RouteTableAssociation5D3F4579) Resource creation Initiated
AppStack | 14/33 | 12:00:39 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet2/RouteTableAssociation (vpcPrivateSubnet2RouteTableAssociation007E94D3) Resource creation Initiated
AppStack | 15/33 | 12:00:39 AM | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet2/RouteTableAssociation (vpcPrivateSubnet2RouteTableAssociation007E94D3)
AppStack | 16/33 | 12:00:42 AM | CREATE_COMPLETE      | AWS::EC2::RouteTable                  | vpc/PrivateSubnet1/RouteTable (vpcPrivateSubnet1RouteTableB41A48CC)
AppStack | 17/33 | 12:00:42 AM | CREATE_COMPLETE      | AWS::IAM::Role                        | Custom::VpcRestrictDefaultSGCustomResourceProvider/Role (CustomVpcRestrictDefaultSGCustomResourceProviderRole26592FE0)
AppStack | 17/33 | 12:00:42 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet1/RouteTableAssociation (vpcPrivateSubnet1RouteTableAssociation67945127)
AppStack | 17/33 | 12:00:43 AM | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
AppStack | 17/33 | 12:00:44 AM | CREATE_IN_PROGRESS   | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet1/RouteTableAssociation (vpcPrivateSubnet1RouteTableAssociation67945127) Resource creation Initiated
AppStack | 18/33 | 12:00:44 AM | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | vpc/PrivateSubnet1/RouteTableAssociation (vpcPrivateSubnet1RouteTableAssociation67945127)
AppStack | 18/33 | 12:00:44 AM | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E) Resource creation Initiated
AppStack | 19/33 | 12:00:45 AM | CREATE_COMPLETE      | AWS::EC2::VPCGatewayAttachment        | vpc/VPCGW (vpcVPCGW7984C166)
AppStack | 19/33 | 12:00:45 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PublicSubnet2/DefaultRoute (vpcPublicSubnet2DefaultRouteA1EC0F60)
AppStack | 19/33 | 12:00:45 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PublicSubnet1/DefaultRoute (vpcPublicSubnet1DefaultRoute10708846)
AppStack | 19/33 | 12:00:47 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PublicSubnet2/DefaultRoute (vpcPublicSubnet2DefaultRouteA1EC0F60) Resource creation Initiated
AppStack | 19/33 | 12:00:47 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PublicSubnet1/DefaultRoute (vpcPublicSubnet1DefaultRoute10708846) Resource creation Initiated
AppStack | 20/33 | 12:00:47 AM | CREATE_COMPLETE      | AWS::EC2::Route                       | vpc/PublicSubnet2/DefaultRoute (vpcPublicSubnet2DefaultRouteA1EC0F60)
AppStack | 21/33 | 12:00:49 AM | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet2/RouteTableAssociation (vpcPublicSubnet2RouteTableAssociation21F81B59)
AppStack | 22/33 | 12:00:49 AM | CREATE_COMPLETE      | AWS::EC2::SubnetRouteTableAssociation | vpc/PublicSubnet1/RouteTableAssociation (vpcPublicSubnet1RouteTableAssociation5D3F4579)
AppStack | 22/33 | 12:00:50 AM | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | vpc/PublicSubnet2/NATGateway (vpcPublicSubnet2NATGateway9B8AE11A)
AppStack | 23/33 | 12:00:50 AM | CREATE_COMPLETE      | AWS::Lambda::Function                 | Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler (CustomVpcRestrictDefaultSGCustomResourceProviderHandlerDC833E5E)
AppStack | 23/33 | 12:00:51 AM | CREATE_IN_PROGRESS   | Custom::VpcRestrictDefaultSG          | vpc/RestrictDefaultSecurityGroupCustomResource/Default (vpcRestrictDefaultSecurityGroupCustomResourceA6EBC6D0)
AppStack | 23/33 | 12:00:51 AM | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | vpc/PublicSubnet2/NATGateway (vpcPublicSubnet2NATGateway9B8AE11A) Resource creation Initiated
AppStack | 23/33 | 12:01:07 AM | CREATE_IN_PROGRESS   | Custom::VpcRestrictDefaultSG          | vpc/RestrictDefaultSecurityGroupCustomResource/Default (vpcRestrictDefaultSecurityGroupCustomResourceA6EBC6D0) Resource creation Initiated
AppStack | 24/33 | 12:01:07 AM | CREATE_COMPLETE      | Custom::VpcRestrictDefaultSG          | vpc/RestrictDefaultSecurityGroupCustomResource/Default (vpcRestrictDefaultSecurityGroupCustomResourceA6EBC6D0)
AppStack | 25/33 | 12:01:08 AM | CREATE_COMPLETE      | AWS::EC2::Route                       | vpc/PublicSubnet1/DefaultRoute (vpcPublicSubnet1DefaultRoute10708846)
AppStack | 25/33 | 12:01:09 AM | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | vpc/PublicSubnet1/NATGateway (vpcPublicSubnet1NATGateway9C16659E)
AppStack | 25/33 | 12:01:11 AM | CREATE_IN_PROGRESS   | AWS::EC2::NatGateway                  | vpc/PublicSubnet1/NATGateway (vpcPublicSubnet1NATGateway9C16659E) Resource creation Initiated
25/33 Currently in progress: AppStack, instanceInstanceProfile931F14E3, vpcPublicSubnet2NATGateway9B8AE11A, vpcPublicSubnet1NATGateway9C16659E
AppStack | 26/33 | 12:02:27 AM | CREATE_COMPLETE      | AWS::EC2::NatGateway                  | vpc/PublicSubnet2/NATGateway (vpcPublicSubnet2NATGateway9B8AE11A)
AppStack | 26/33 | 12:02:28 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PrivateSubnet2/DefaultRoute (vpcPrivateSubnet2DefaultRouteB0E07F99)
AppStack | 26/33 | 12:02:30 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PrivateSubnet2/DefaultRoute (vpcPrivateSubnet2DefaultRouteB0E07F99) Resource creation Initiated
AppStack | 27/33 | 12:02:30 AM | CREATE_COMPLETE      | AWS::EC2::Route                       | vpc/PrivateSubnet2/DefaultRoute (vpcPrivateSubnet2DefaultRouteB0E07F99)
AppStack | 28/33 | 12:02:40 AM | CREATE_COMPLETE      | AWS::IAM::InstanceProfile             | instance/InstanceProfile (instanceInstanceProfile931F14E3)
AppStack | 28/33 | 12:02:41 AM | CREATE_IN_PROGRESS   | AWS::EC2::Instance                    | instance (instanceB7CCE687)
AppStack | 28/33 | 12:02:42 AM | CREATE_IN_PROGRESS   | AWS::EC2::Instance                    | instance (instanceB7CCE687) Resource creation Initiated
AppStack | 29/33 | 12:02:50 AM | CREATE_COMPLETE      | AWS::EC2::Instance                    | instance (instanceB7CCE687)
AppStack | 30/33 | 12:02:52 AM | CREATE_COMPLETE      | AWS::EC2::NatGateway                  | vpc/PublicSubnet1/NATGateway (vpcPublicSubnet1NATGateway9C16659E)
AppStack | 30/33 | 12:02:52 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PrivateSubnet1/DefaultRoute (vpcPrivateSubnet1DefaultRoute1AA8E2E5)
AppStack | 30/33 | 12:02:54 AM | CREATE_IN_PROGRESS   | AWS::EC2::Route                       | vpc/PrivateSubnet1/DefaultRoute (vpcPrivateSubnet1DefaultRoute1AA8E2E5) Resource creation Initiated
30/33 Currently in progress: AppStack, vpcPrivateSubnet1DefaultRoute1AA8E2E5
AppStack | 31/33 | 12:05:34 AM | CREATE_COMPLETE      | AWS::EC2::Route                       | vpc/PrivateSubnet1/DefaultRoute (vpcPrivateSubnet1DefaultRoute1AA8E2E5)
AppStack | 32/33 | 12:05:36 AM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack            | AppStack
AppStack | 33/33 | 12:05:37 AM | UPDATE_COMPLETE      | AWS::CloudFormation::Stack            | AppStack

 ✅  AppStack

✨  Deployment time: 352.17s

Stack ARN:
arn:aws:cloudformation:us-east-1:123456789012:stack/AppStack/74eaa640-5461-11ee-8321-0a0278c876f9

✨  Total time: 356.43s

讓我們進入 AWS Console EC2 看一下剛剛建立,或是說唯一的執行個體,右上角有 Connect ,我們嘗試連進去。
AWS Console EC2 Instance

哎呀,怎麼每個選項都不能連線呢?
AWS Console EC2 Instance Connect Failed

只好來修一下他了,我們這次用懶人方法,直接在把後面的分號 (;) 拿掉,加上下面的設定。

.role.addManagedPolicy(
  cdk.aws_iam.ManagedPolicy.fromAwsManagedPolicyName(
    'AmazonSSMManagedInstanceCore',
  ),
);

這是請 AWS CDK 將名為 AmazonSSMManagedInstanceCore 的 IAM 政策 (Policy) 附加到 AWS EC2 執行個體的角色 (Role) 上面,現在來部署上去,我們從這之後就擷取部分的輸出就好。
IAM 政策異動:

┌───┬──────────────────────┬───────────────────────┐
│   │ Resource             │ Managed Policy ARN    │
├───┼──────────────────────┼───────────────────────┤
│ + │ ${instance/InstanceR │ arn:${AWS::Partition} │
│   │ ole}                 │ :iam::aws:policy/Amaz │
│   │                      │ onSSMManagedInstanceC │
│   │                      │ ore                   │
└───┴──────────────────────┴───────────────────────┘

資源:

[~] AWS::IAM::Role instance/InstanceRole instanceInstanceRoleF436EE92 
 └─ [+] ManagedPolicyArns
     └─ [{"Fn::Join":["",["arn:",{"Ref":"AWS::Partition"},":iam::aws:policy/AmazonSSMManagedInstanceCore"]]}]

部署:

AppStack: deploying... [1/1]
AppStack: creating CloudFormation changeset...
AppStack | 0/3 | 12:06:04 AM | UPDATE_IN_PROGRESS   | AWS::CloudFormation::Stack            | AppStack User Initiated
AppStack | 0/3 | 12:06:08 AM | UPDATE_IN_PROGRESS   | AWS::IAM::Role                        | instance/InstanceRole (instanceInstanceRoleF436EE92)
AppStack | 1/3 | 12:06:23 AM | UPDATE_COMPLETE      | AWS::IAM::Role                        | instance/InstanceRole (instanceInstanceRoleF436EE92)
AppStack | 2/3 | 12:06:26 AM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack            | AppStack     
AppStack | 3/3 | 12:06:27 AM | UPDATE_COMPLETE      | AWS::CloudFormation::Stack            | AppStack     

 ✅  AppStack

現在回到令人尷尬的連線畫面, Session Manager 下面的連線 (Connect) 應該是變成可以點選的狀態了。
AWS Console EC2 Instance Connect

如果還是不行的話,可以嘗試將 AWS EC2 執行個體重新啟動。
AWS Console EC2 Instance Reboot

恭喜大家成功連線進剛才建立的 AWS EC2 執行個體,這台執行個體的設置,在 AWS 中被稱作是堡壘主機 (Bastion)
AWS Console EC2 Instance Terminal

使用 AWS CDK 定義 AWS Lambda 函數 (Function)

打鐵趁熱,我們也來利用 AWS Lambda 函數,讓他可以在上面執行簡單的程式。

有了方才 AWS EC2 執行個體的前車之鑑,讓我們直接使用下面的程式碼來定義新的資源。

new cdk.aws_lambda.Function(this, 'function', {
  vpc,
  runtime: cdk.aws_lambda.Runtime.NODEJS_18_X,
  code: cdk.aws_lambda.Code.fromInline(`
    exports.greeting = async function () {
      console.log('Hello AWS CDK');
    };
  `),
  handler: 'index.greeting',
});

一樣來詳解一下每個屬性的內容:

  • vpc:跟剛才 AWS EC2 執行個體的位置一樣。
  • runtime:指定使用 Node.js 18 作為執行環境。
  • code:AWS Lambda 函數的程式碼,對,我們成功的在程式碼中寫程式碼,還是在 TypeScript 中寫 CommonJS 。
  • handler:AWS Lambda 函數的處理常式,由於我們將程式碼直接嵌入在 AWS CDK 中,所以必須以 index. 作為開頭,而 greeting 是我們所想要運行的函數。

等部署完成之後,就來看一下AWS Lambda 函數的結果吧。
IAM 陳述式異動:

┌───┬────────┬────────┬────────┬────────┬──────────┐
│   │ Resour │ Effect │ Action │ Princi │ Conditio │ 
│   │ ce     │        │        │ pal    │ n        │ 
├───┼────────┼────────┼────────┼────────┼──────────┤ 
│ + │ ${func │ Allow  │ sts:As │ Servic │          │ 
│   │ tion/S │        │ sumeRo │ e:lamb │          │ 
│   │ ervice │        │ le     │ da.ama │          │ 
│   │ Role.A │        │        │ zonaws │          │ 
│   │ rn}    │        │        │ .com   │          │ 
└───┴────────┴────────┴────────┴────────┴──────────┘ 

IAM 政策異動:

┌───┬──────────────────────┬───────────────────────┐
│   │ Resource             │ Managed Policy ARN    │ 
├───┼──────────────────────┼───────────────────────┤ 
│ + │ ${function/ServiceRo │ arn:${AWS::Partition} │ 
│   │ le}                  │ :iam::aws:policy/serv │ 
│   │                      │ ice-role/AWSLambdaBas │ 
│   │                      │ icExecutionRole       │ 
│ + │ ${function/ServiceRo │ arn:${AWS::Partition} │ 
│   │ le}                  │ :iam::aws:policy/serv │ 
│   │                      │ ice-role/AWSLambdaVPC │ 
│   │                      │ AccessExecutionRole   │ 
└───┴──────────────────────┴───────────────────────┘ 

安全群組異動:

┌───┬────────────┬─────┬────────────┬──────────────┐ 
│   │ Group      │ Dir │ Protocol   │ Peer         │ 
├───┼────────────┼─────┼────────────┼──────────────┤ 
│ + │ ${function │ Out │ Everything │ Everyone (IP │ 
│   │ /SecurityG │     │            │ v4)          │ 
│   │ roup.Group │     │            │              │ 
│   │ Id}        │     │            │              │ 
└───┴────────────┴─────┴────────────┴──────────────┘ 

資源:

[+] AWS::IAM::Role function/ServiceRole functionServiceRoleEF216095
[+] AWS::EC2::SecurityGroup function/SecurityGroup functionSecurityGroup698076D7
[+] AWS::Lambda::Function function functionF19B1A04  

部署:

AppStack: deploying... [1/1]
AppStack: creating CloudFormation changeset...
AppStack | 0/6 | 12:07:06 AM | UPDATE_IN_PROGRESS   | AWS::CloudFormation::Stack            | AppStack User Initiated
AppStack | 0/6 | 12:07:10 AM | CREATE_IN_PROGRESS   | AWS::EC2::SecurityGroup               | function/SecurityGroup (functionSecurityGroup698076D7)
AppStack | 0/6 | 12:07:10 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | function/ServiceRole (functionServiceRoleEF216095)
AppStack | 0/6 | 12:07:10 AM | CREATE_IN_PROGRESS   | AWS::IAM::Role                        | function/ServiceRole (functionServiceRoleEF216095) Resource creation Initiated
AppStack | 0/6 | 12:07:10 AM | UPDATE_IN_PROGRESS   | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
AppStack | 1/6 | 12:07:12 AM | UPDATE_COMPLETE      | AWS::CDK::Metadata                    | CDKMetadata/Default (CDKMetadata)
AppStack | 1/6 | 12:07:15 AM | CREATE_IN_PROGRESS   | AWS::EC2::SecurityGroup               | function/SecurityGroup (functionSecurityGroup698076D7) Resource creation Initiated
AppStack | 2/6 | 12:07:16 AM | CREATE_COMPLETE      | AWS::EC2::SecurityGroup               | function/SecurityGroup (functionSecurityGroup698076D7)
AppStack | 3/6 | 12:07:26 AM | CREATE_COMPLETE      | AWS::IAM::Role                        | function/ServiceRole (functionServiceRoleEF216095)
AppStack | 3/6 | 12:07:27 AM | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | function (functionF19B1A04)
AppStack | 3/6 | 12:07:29 AM | CREATE_IN_PROGRESS   | AWS::Lambda::Function                 | function (functionF19B1A04) Resource creation Initiated
3/6 Currently in progress: AppStack, functionF19B1A04
AppStack | 4/6 | 12:11:13 AM | CREATE_COMPLETE      | AWS::Lambda::Function                 | function (functionF19B1A04)
AppStack | 5/6 | 12:11:14 AM | UPDATE_COMPLETE_CLEA | AWS::CloudFormation::Stack            | AppStack
AppStack | 6/6 | 12:11:15 AM | UPDATE_COMPLETE      | AWS::CloudFormation::Stack            | AppStack

 ✅  AppStack

現在就重新進入 AWS Console Lambda 去執行,並且看一下結果,我們要執行的是有 function 在名字內的,可用上面的搜尋欄做到,雖然也只有兩個函數就是了。
AWS Console Lambda Function filtered

在 Test 裡面,右邊有 Test 的橘色按鈕,不用等他載入完畢,直接大方地點下去。

成功執行結束了,我們展開看詳細資訊,可以發現剛剛的 Hello AWS CDK 有被正確的印出。
AWS Console Lambda Function Test Log


相信大家已經更加熟悉 AWS CDK 的操作了,如果大家對於傳入的參數,或是物件的結構有疑問的話,別急著離開,我們馬上就要把 AWS CDK 送進 X 光機,看一下他的架構。


上一篇
04 - 使用 CDK 定義 AWS 存儲資源
下一篇
06 - CDK 的架構
系列文
CDK 從 0 開始打造靈活自如的 IaC7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言