1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
| from aws_cdk import (
Stack,
aws_iam as iam,
aws_ec2 as ec2
)
from constructs import Construct
# 从user_data.txt 文件读出 user_data
with open('user_data.txt') as f:
user_data = f.read()
class CdkStack(Stack):
def __init__(self, scope: Construct, id: str, subnet_id: str, sg_id: str, vpc_id: str, availability_zone: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# Found the latest debian 11 arm64 AMI which could be launched as t4g.small
image = ec2.LookupMachineImage(
owners = ['amazon'],
name = 'debian-11-arm64*',
filters={
'virtualization-type': ['hvm'],
'architecture': ['arm64']
},
)
# Found the latest ubuntu 24 arm64 AMI
# image = ec2.LookupMachineImage(
# owners=['099720109477'], # Canonical 的 AWS 账户 ID
# name='ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-arm64-server-*', # Ubuntu 24 ARM64 的 AMI 名称模式
# filters={
# 'virtualization-type': ['hvm'],
# 'architecture': ['arm64']
# },
# )
# Create an IAM role for SSM
ssm_role = iam.Role(self, "SSMInstanceRole",
assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"),
managed_policies=[iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore")]
)
# Import the subnet with availability zone
subnet = ec2.Subnet.from_subnet_attributes(self, "Subnet",
subnet_id=subnet_id,
availability_zone=availability_zone
)
# Import the VPC by its ID (use VPC ID)
vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpc_id)
# 创建一个EC2实例, 给公共IP吧
instance = ec2.Instance(
self, "testing-ec2",
instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE4_GRAVITON, ec2.InstanceSize.SMALL),
machine_image=image,
vpc=vpc,
vpc_subnets=ec2.SubnetSelection(subnets=[subnet]),
security_group=ec2.SecurityGroup.from_security_group_id(self, "SecurityGroup", sg_id),
user_data=ec2.UserData.custom(user_data),
role=ssm_role
)
|