|
| 1 | +from aws_cdk import core |
| 2 | +import aws_cdk.aws_ec2 as ec2 |
| 3 | + |
| 4 | +vpc_id = "MY-VPC-ID" # Import an Exist VPC |
| 5 | +ec2_type = "t2.micro" |
| 6 | +key_name = "id_rsa" |
| 7 | +linux_ami = ec2.GenericLinuxImage({ |
| 8 | + "cn-northwest-1": "AMI-ID-IN-cn-northwest-1-REGION", # Refer to an Exist AMI |
| 9 | + "eu-west-1": "AMI-ID-IN-eu-west-1-REGION" |
| 10 | +}) |
| 11 | +with open("./user_data/user_data.sh") as f: |
| 12 | + user_data = f.read() |
| 13 | + |
| 14 | + |
| 15 | +class CdkVpcEc2Stack(core.Stack): |
| 16 | + |
| 17 | + def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: |
| 18 | + super().__init__(scope, id, **kwargs) |
| 19 | + |
| 20 | + # The code that defines your stack goes here |
| 21 | + vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpc_id) |
| 22 | + |
| 23 | + host = ec2.Instance(self, "myEC2", |
| 24 | + instance_type=ec2.InstanceType( |
| 25 | + instance_type_identifier=ec2_type), |
| 26 | + instance_name="mySingleHost", |
| 27 | + machine_image=linux_ami, |
| 28 | + vpc=vpc, |
| 29 | + key_name=key_name, |
| 30 | + vpc_subnets=ec2.SubnetSelection( |
| 31 | + subnet_type=ec2.SubnetType.PUBLIC), |
| 32 | + user_data=ec2.UserData.custom(user_data) |
| 33 | + ) |
| 34 | + # ec2.Instance has no property of BlockDeviceMappings, add via lower layer cdk api: |
| 35 | + host.instance.add_property_override("BlockDeviceMappings", [{ |
| 36 | + "DeviceName": "/dev/xvda", |
| 37 | + "Ebs": { |
| 38 | + "VolumeSize": "10", |
| 39 | + "VolumeType": "io1", |
| 40 | + "Iops": "150", |
| 41 | + "DeleteOnTermination": "true" |
| 42 | + } |
| 43 | + }, { |
| 44 | + "DeviceName": "/dev/sdb", |
| 45 | + "Ebs": {"VolumeSize": "30"} |
| 46 | + } |
| 47 | + ]) # by default VolumeType is gp2, VolumeSize 8GB |
| 48 | + host.connections.allow_from_any_ipv4( |
| 49 | + ec2.Port.tcp(22), "Allow ssh from internet") |
| 50 | + host.connections.allow_from_any_ipv4( |
| 51 | + ec2.Port.tcp(80), "Allow ssh from internet") |
| 52 | + |
| 53 | + core.CfnOutput(self, "Output", |
| 54 | + value=host.instance_public_ip) |
0 commit comments