def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here # vpc network vpc = aws_ec2.CfnVPC(self, 'vpc', cidr_block='10.0.0.0/16', enable_dns_hostnames=True, enable_dns_support=True, instance_tenancy='default', tags=[core.CfnTag(key='Name',value='vpc')]) internetgateway = aws_ec2.CfnInternetGateway(self, 'internetgateway', tags=[core.CfnTag(key='Name',value='internetgateway')]) aws_ec2.CfnVPCGatewayAttachment(self, 'VPCGatewayAttachment', vpc_id=vpc.ref, internet_gateway_id=internetgateway.ref) # public network publicsubnet01 = aws_ec2.CfnSubnet(self, 'publicsubnet01', cidr_block='10.0.0.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='publicsubnet01')]) publicsubnet02 = aws_ec2.CfnSubnet(self, 'publicsubnet02', cidr_block='10.0.1.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='publicsubnet02')]) publicsubnet03 = aws_ec2.CfnSubnet(self, 'publicsubnet03', cidr_block='10.0.2.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='publicsubnet03')]) publicroutetable01 = aws_ec2.CfnRouteTable(self, 'publicroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable01')]) publicroutetable02 = aws_ec2.CfnRouteTable(self, 'publicroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable02')]) publicroutetable03 = aws_ec2.CfnRouteTable(self, 'publicroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable03')]) aws_ec2.CfnRoute(self, 'publicroute01', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable01.ref,) aws_ec2.CfnRoute(self, 'publicroute02', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable02.ref) aws_ec2.CfnRoute(self, 'publicroute03', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable03.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation01', route_table_id=publicroutetable01.ref, subnet_id=publicsubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation02', route_table_id=publicroutetable02.ref, subnet_id=publicsubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation03', route_table_id=publicroutetable03.ref, subnet_id=publicsubnet03.ref) # private network privatesubnet01 = aws_ec2.CfnSubnet(self, 'privatesubnet01', cidr_block='10.0.11.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='privatesubnet01')]) privatesubnet02 = aws_ec2.CfnSubnet(self, 'privatesubnet02', cidr_block='10.0.12.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='privatesubnet02')]) privatesubnet03 = aws_ec2.CfnSubnet(self, 'privatesubnet03', cidr_block='10.0.13.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='privatesubnet03')]) privateroutetable01 = aws_ec2.CfnRouteTable(self, 'privateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable01')]) privateroutetable02 = aws_ec2.CfnRouteTable(self, 'privateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable02')]) privateroutetable03 = aws_ec2.CfnRouteTable(self, 'privateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable03')]) aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation01', route_table_id=privateroutetable01.ref, subnet_id=privatesubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation02', route_table_id=privateroutetable02.ref, subnet_id=privatesubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation03', route_table_id=privateroutetable03.ref, subnet_id=privatesubnet03.ref) eip01 = aws_ec2.CfnEIP(self, 'eip01', tags=[core.CfnTag(key='Name',value='eip01')]) eip02 = aws_ec2.CfnEIP(self, 'eip02', tags=[core.CfnTag(key='Name',value='eip02')]) eip03 = aws_ec2.CfnEIP(self, 'eip03', tags=[core.CfnTag(key='Name',value='eip03')]) natgateway01 = aws_ec2.CfnNatGateway(self, 'natgateway01', allocation_id=eip01.attr_allocation_id, subnet_id=publicsubnet01.ref, tags=[core.CfnTag(key='Name',value='natgateway01')]) natgateway02 = aws_ec2.CfnNatGateway(self, 'natgateway02', allocation_id=eip02.attr_allocation_id, subnet_id=publicsubnet02.ref, tags=[core.CfnTag(key='Name',value='natgateway02')]) natgateway03 = aws_ec2.CfnNatGateway(self, 'natgateway03', allocation_id=eip03.attr_allocation_id, subnet_id=publicsubnet03.ref, tags=[core.CfnTag(key='Name',value='natgateway03')]) aws_ec2.CfnRoute(self, 'privateroute01', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway01.ref, route_table_id=privateroutetable01.ref) aws_ec2.CfnRoute(self, 'privateroute02', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway02.ref, route_table_id=privateroutetable02.ref) aws_ec2.CfnRoute(self, 'privateroute03', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway03.ref, route_table_id=privateroutetable03.ref) # isolate network isolatesubnet01 = aws_ec2.CfnSubnet(self, 'isolatesubnet01', cidr_block='10.0.21.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='isolatesubnet01')]) isolatesubnet02 = aws_ec2.CfnSubnet(self, 'isolatesubnet02', cidr_block='10.0.22.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='isolatesubnet02')]) isolatesubnet03 = aws_ec2.CfnSubnet(self, 'isolatesubnet03', cidr_block='10.0.23.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='isolatesubnet03')]) isolateroutetable01 = aws_ec2.CfnRouteTable(self, 'isolateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable01')]) isolateroutetable02 = aws_ec2.CfnRouteTable(self, 'isolateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable02')]) isolateroutetable03 = aws_ec2.CfnRouteTable(self, 'isolateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable03')]) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation01', route_table_id=isolateroutetable01.ref, subnet_id=isolatesubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation02', route_table_id=isolateroutetable02.ref, subnet_id=isolatesubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation03', route_table_id=isolateroutetable03.ref, subnet_id=isolatesubnet03.ref)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # launchtemplate # https://aws.amazon.com/marketplace/pp/B00O7WM7QW ami-06a46da680048c8ae template01=aws_ec2.CfnLaunchTemplate(self, 'template01', launch_template_data={'imageId':'ami-06a46da680048c8ae', 'blockDeviceMappings':[{'deviceName':'/dev/sda1','ebs':{'deleteOnTermination':True, 'volumeSize':20, 'volumeType':'gp2'}}], 'securityGroupIds':[core.Fn.import_value('publicsecuritygroup01')], 'instanceType':'t3.micro'}, launch_template_name='public01') template02=aws_ec2.CfnLaunchTemplate(self, 'template02', launch_template_data={'imageId':'ami-06a46da680048c8ae', 'blockDeviceMappings':[{'deviceName':'/dev/sda1','ebs':{'deleteOnTermination':True, 'volumeSize':20, 'volumeType':'gp2'}}], 'securityGroupIds':[core.Fn.import_value('privatesecuritygroup01')], 'instanceType':'t3.micro'}, launch_template_name='private01') # public instance instance01=aws_ec2.CfnInstance(self, 'instance01', launch_template={'launchTemplateId': template01.ref, 'version': template01.attr_latest_version_number}, key_name='aws-example-key', subnet_id=core.Fn.import_value('publicsubnet01')) aws_ec2.CfnEIP(self, 'eip', domain='vpc', instance_id=instance01.ref, tags=[core.CfnTag(key='Name', value='eip01')]) # private instance aws_ec2.CfnInstance(self, 'instance02', launch_template={'launchTemplateId': template02.ref, 'version': template01.attr_latest_version_number}, key_name='aws-example-key', subnet_id=core.Fn.import_value('publicsubnet02'))
def create_elastic_ip(self, internet_gateway_attachment): # EIP1 (for NATGW) elastic_ip = _ec2.CfnEIP(self, 'CfnEIP', domain="vpc", tags=[CfnTag( key='Name', value='DEMO-EIP', )]) elastic_ip.add_depends_on(internet_gateway_attachment) return elastic_ip
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Create the VPC vpc = ec2.Vpc(self, "VPC", max_azs=1, cidr='10.0.0.0/16', subnet_configuration=[ { 'cidrMask': 24, 'name': 'Ingress', 'subnetType': ec2.SubnetType.PUBLIC, }, { 'cidrMask': 24, 'name': 'Application', 'subnetType': ec2.SubnetType.PRIVATE, } ] ) publicsubnet = vpc.public_subnets[0].subnet_id privatesubnet = vpc.private_subnets[0].subnet_id publicinstancetags = [ core.CfnTag(key="Name", value="MyPublicLabHost"), core.CfnTag(key="Project", value="lab"), core.CfnTag(key="CostCenter", value="1520") ] privateinstancetags = [ core.CfnTag(key="Name", value="MyPrivateLabHost"), core.CfnTag(key="Project", value="lab"), core.CfnTag(key="CostCenter", value="1520") ] mypublicinstance = ec2.CfnInstance(self, 'MyPublicLabHost', instance_type='t3.nano', subnet_id=publicsubnet, image_id=ec2.AmazonLinuxImage().get_image(self).image_id, tags=publicinstancetags) myprivateinstance = ec2.CfnInstance(self, 'MyPrivateLabHost', instance_type='t3.nano', subnet_id=privatesubnet, image_id=ec2.AmazonLinuxImage().get_image(self).image_id, tags=privateinstancetags) iid = mypublicinstance.ref eip = ec2.CfnEIP(self,'MyLabEip',domain='vpc',instance_id=iid)
def __init__(self, scope: core.Construct, id: str, count: int, timeout: str, **kwargs): super().__init__(scope, id, **kwargs) eip = ec2.CfnEIP(self, "NAT_EIP", domain="vpc") self._h = cfn.CfnWaitConditionHandle( self, "testWaitConditionWithDataHandle") self._w = cfn.CfnWaitCondition(self, "testWaitConditionWithData", count=count, handle=self._h.ref, timeout=timeout) self._w.add_depends_on(eip)
def __init__(self, scope: core.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) # add elastic IP to the stack elastic_ip = ec2.CfnEIP(self, "zach-elastic-ip") # create public subnet to place ec2 instance for public access public_subnet = self._create_public_subnet() # create a role associated with vpc instance role = self._add_role() # create vpc with public subnet vpc = self._add_vpc([public_subnet]) # add security group security_group = self._add_security_groups(vpc) # add autoscaling group Zach_Ec2_Instance = self._add_autoscaling_group( vpc, public_subnet, security_group, role) # add bootstrap script self._add_bootstrap_script_to_ec2(Zach_Ec2_Instance) # publish resource output core.CfnOutput( self, "AllocationId", description= "The ID that AWS assigns to represent the allocation of the address for use with Amazon VPC. " "This is returned only for VPC elastic IP addresses. For example, eipalloc-5723d13e.", value=elastic_ip.get_att('AllocationId').to_string()) core.CfnOutput(self, "InstanceSubnetType", value=public_subnet.subnet_type.value) core.CfnOutput(self, "InstanceOS", value=Zach_Ec2_Instance.os_type.value) core.CfnOutput(self, "InstanceRole", value=role.role_arn) core.CfnOutput(self, "InstanceBindSG", value=str( Zach_Ec2_Instance.connections.security_groups)) core.CfnOutput(self, "AutoScaleName", value=Zach_Ec2_Instance.auto_scaling_group_name) core.CfnOutput(self, "AutoScaleARN", value=Zach_Ec2_Instance.auto_scaling_group_arn)
def create_nat_gateway(scope: core.Construct, vpc: aws_ec2.CfnVPC, subnet: aws_ec2.CfnSubnet) -> aws_ec2.CfnNatGateway: prefix = scope.node.try_get_context("prefix") az_end = subnet.availability_zone[-2:] eip = aws_ec2.CfnEIP(scope, f'{prefix}-eip-{az_end}') nat_gateway = aws_ec2.CfnNatGateway( scope, f'{prefix}-nat-{az_end}', allocation_id=eip.attr_allocation_id, subnet_id=subnet.ref, tags=[core.CfnTag( key='Name', value=f'{prefix}-nat-{az_end}', )], ) return nat_gateway
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id) self._id = id try: kwargs['tags'] except: self._tags_wk = None else: self._tags_wk = [ core.CfnTag(key=kwargs['tags'][i]['key'], value=kwargs['tags'][i]['value']) if kwargs['tags'] else None for i in range(len(kwargs['tags'])) ] self._eip = aws_ec2.CfnEIP(self, self._id, tags=self._tags_wk)
def createServer(self): volume = ec2.Volume(self, 'serverVolume2a', removal_policy=cdk.RemovalPolicy.RETAIN, volume_type=ec2.EbsDeviceVolumeType.GP3, availability_zone='us-west-2a', snapshot_id='snap-0ca71aed81fe73771', size=cdk.Size.gibibytes(16), ) instance = ec2.Instance(self, 'serverVpcInstance', instance_type=ec2.InstanceType('t3a.small'), vpc=self.vpc, machine_image=ec2.MachineImage.generic_linux({ 'us-west-2': 'ami-03d5c68bab01f3496' }), role=self.serverRole, availability_zone='us-west-2a', key_name='tipbotkey', # must be created in advance ) instance.apply_removal_policy(cdk.RemovalPolicy.RETAIN) instance.node.default_child.volumes = [ ec2.CfnInstance.VolumeProperty( device='/dev/sda2', volume_id=volume.volume_id, ) ] ec2.CfnEIPAssociation(self, 'serverVpcEIPAssociation', eip=ec2.CfnEIP(self, 'serverVpcEIP', domain='vpc', instance_id=instance.instance_id, ).ref, instance_id=instance.instance_id ) cfnInstance = typing.cast(typing.Optional[ec2.CfnInstance], instance.node.default_child) cfnInstance.ipv6_addresses = [ ec2.CfnInstance.InstanceIpv6AddressProperty(ipv6_address='2600:1f14:0741:4a00:fedc:ba98:7654:3210') ] # Need to attach this manually since we have a CfnSecurityGroup, not a SecurityGroup cfnInstance.security_group_ids = [ cdk.Fn.get_att(self.securityGroup.logical_id, 'GroupId').to_string() ]
def __init__(self, scope: core.Construct, construct_id: str, imaging_sg: ec2.ISecurityGroup, imaging_ec2_role: iam.IRole, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # elastic ip eip = ec2.CfnEIP(self, "Imaging Server IP") core.Tags.of(eip).add(key="Name", value="Imaging Server EIP") # imaging ec2 instance #ami_id=ssm.StringParameter.value_from_lookup(self,"/linux/production/ami_id") itype = ec2.InstanceType("t3.nano") iami = ec2.MachineImage.from_ssm_parameter( "/linux/production/ami_id", os=ec2.OperatingSystemType.LINUX) default_vpc = ec2.Vpc.from_lookup(self, "DefaultVpc", is_default=True) imaging_ec2 = ec2.Instance(self, "ec2-instance", instance_type=itype, machine_image=iami, vpc=default_vpc, security_group=imaging_sg, role=imaging_ec2_role) # add tags core.Tags.of(imaging_ec2).add(key="Name", value="Linux-Prod-Imaging-Server") core.Tags.of(imaging_ec2).add(key="ami_id_parameter", value="/linux/production/ami_id") core.Tags.of(imaging_ec2).add(key="OS", value="linux") core.Tags.of(imaging_ec2).add(key="ServerGroup", value="production") core.Tags.of(imaging_ec2).add(key="Type", value="imaging_server") # attach eip ec2.CfnEIPAssociation(self, "EIP Attachment", eip=eip.ref, instance_id=imaging_ec2.instance_id)
def __init__(self, scope: core.Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) # add elastic IP to the stack elastic_ip = ec2.CfnEIP(self, "vpn-elastic-ip") # create public subnet to place ec2 instance for public access public_subnet = self._create_public_subnet() # create a role associated with vpc instance role = self._add_role() # add vpn config to ssm parameters self._add_ssm_parameters(role) # create vpc with public subnet vpc = self._add_vpc([public_subnet]) # add security group security_group = self._add_security_groups(vpc) # add autoscaling group autoscaling_group = self._add_autoscaling_group( vpc, public_subnet, security_group, role) # add bootstrap script self._add_bootstrap_script_to_ec2(autoscaling_group) # publish resource output core.CfnOutput( self, "AllocationId", description= "The ID that AWS assigns to represent the allocation of the address for use with Amazon VPC. " "This is returned only for VPC elastic IP addresses. For example, eipalloc-5723d13e.", value=elastic_ip.get_att('AllocationId').to_string())
def provision_bastion(self, name: str, bastion: VPC.Bastion) -> None: if not bastion.enabled: return None if bastion.machine_image: bastion_machine_image = ec2.MachineImage.generic_linux( {self.region: bastion.machine_image.ami_id}, user_data=ec2.UserData.custom(bastion.machine_image.user_data), ) else: if not self.scope.account.isnumeric( ): # TODO: Can we get rid of this requirement? raise ValueError( "Error loooking up AMI: Must provide explicit AWS account ID to do AMI lookup. Either provide AMI ID or AWS account id" ) bastion_machine_image = ec2.LookupMachineImage( name="ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*", owners=["099720109477"]) bastion_sg = ec2.SecurityGroup( self.scope, "bastion_sg", vpc=self.vpc, security_group_name=f"{name}-bastion", ) for rule in bastion.ingress_ports: for ip_cidr in rule.ip_cidrs: bastion_sg.add_ingress_rule( peer=ec2.Peer.ipv4(ip_cidr), connection=ec2.Port( protocol=ec2.Protocol(rule.protocol), string_representation=rule.name, from_port=rule.from_port, to_port=rule.to_port, ), ) bastion = ec2.Instance( self.scope, "bastion", machine_image=bastion_machine_image, vpc=self.vpc, instance_type=ec2.InstanceType(bastion.instance_type), key_name=bastion.key_name, security_group=bastion_sg, vpc_subnets=ec2.SubnetSelection( subnet_group_name=self.public_subnet_name, ), ) ec2.CfnEIP( self.scope, "bastion_eip", instance_id=bastion.instance_id, ) cdk.CfnOutput(self.scope, "bastion_public_ip", value=bastion.instance_public_ip) return bastion_sg
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Create an empty VPC # If you don't specify any other resources EXCEPT the VPC, there's a standard template applied vpc = ec2.Vpc( self, id="MyVPC", nat_gateways=0, cidr="192.168.0.0/20", max_azs=1, subnet_configuration=[], ) # A couple of subnets app_subnet = ec2.CfnSubnet( self, id="Application", vpc_id=vpc.vpc_id, availability_zone="eu-central-1a", cidr_block="192.168.1.0/24", map_public_ip_on_launch=False, tags=[core.CfnTag(key="Name", value="Application")]) web_subnet = ec2.CfnSubnet( self, id="Webhost", vpc_id=vpc.vpc_id, availability_zone="eu-central-1b", cidr_block="192.168.2.0/24", map_public_ip_on_launch=True, tags=[core.CfnTag(key="Name", value="WebHost")]) # A couple of route tables private_rt = ec2.CfnRouteTable( self, id="Private_RT", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="Private_RT")]) public_rt = ec2.CfnRouteTable( self, id="Public_RT", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="Public_RT")]) # How to associate a subnet with a route table ec2.CfnSubnetRouteTableAssociation(self, id="WebHostRTAssoc", subnet_id=web_subnet.ref, route_table_id=public_rt.ref) ec2.CfnSubnetRouteTableAssociation(self, id="ApplicationRTAssoc", subnet_id=app_subnet.ref, route_table_id=private_rt.ref) # A gateway (Internet Gateway in this case) igw = ec2.CfnInternetGateway( self, id="MyIGW", tags=[core.CfnTag(key="Name", value="IGW")]) # How to associate a gateway to a VPC (IGW in this case - for VGW use vpn_gateway_id=blablabla) ec2.CfnVPCGatewayAttachment(self, id="IGW_Assoc", vpc_id=vpc.vpc_id, internet_gateway_id=igw.ref) # Elastic IP eip_01 = ec2.CfnEIP(self, id="EIP01") # NAT gateway ngw = ec2.CfnNatGateway(self, id="NAT_GW", allocation_id=eip_01.attr_allocation_id, subnet_id=web_subnet.ref, tags=[core.CfnTag(key="Name", value="NAT_GW")]) ngw.add_depends_on(eip_01) # Add a route to a route table default_route_public = ec2.CfnRoute(self, id="DefaultRoutePublic", route_table_id=public_rt.ref, destination_cidr_block="0.0.0.0/0", gateway_id=igw.ref) default_route_public.add_depends_on(igw) default_route_private = ec2.CfnRoute( self, id="DefaultRouteprivate", route_table_id=private_rt.ref, destination_cidr_block="0.0.0.0/0", nat_gateway_id=ngw.ref) default_route_private.add_depends_on(ngw) ### Security Groups ### # PUBLIC SUBNET SG sg_public = ec2.CfnSecurityGroup( self, id="SG_PUBLIC", group_description="SG for the Public Subnet", group_name="SG_PUBLIC", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="SG_Public")]) my_home_ip = requests.get("https://api.my-ip.io/ip.json").json()['ip'] ports_pub = {'tcp': [22, 80], 'icmp': [-1]} for protocl, ports_list in ports_pub.items(): for port in ports_list: ec2.CfnSecurityGroupIngress( self, id=f"sg_pub_in_{protocl}_{port}", group_id=sg_public.attr_group_id, ip_protocol=protocl, cidr_ip=f"{my_home_ip}/32", to_port=port, from_port=port, description=f"{protocl.upper()} {port} from home IP") # SG INGRESS ENTRIES - ICMP - EXAMPLE # sg_in_icmp = ec2.CfnSecurityGroupIngress(self, id="SG_PUB_IN_ICMP", # group_id=sg_public.attr_group_id, # ip_protocol = "icmp", # cidr_ip = f"{my_home_ip}/32", # to_port = -1, # from_port = -1, # description = "ICMP FROM HOME") # SG EGRESS ENTRIES - AUTO-IMPLIED IF NOT CONFIGURED # sg_out_all = ec2.CfnSecurityGroupEgress(self, id="SG_PUB_OUT_ALL", # group_id=sg_public.attr_group_id, # ip_protocol="-1", # cidr_ip="0.0.0.0/0") # PRIVATE SUBNET SG sg_private = ec2.CfnSecurityGroup( self, id="SG_PRIVATE", group_description="SG for the Private Subnet", group_name="SG_PRIVATE", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="SG_Private")]) sg_private.add_depends_on(sg_public) ports_priv = {'tcp': [22, 21, 53, 3368, 80], 'icmp': [-1]} for protocl, ports_list in ports_priv.items(): for port in ports_list: ec2.CfnSecurityGroupIngress( self, id=f"sg_priv_in_{protocl}_{port}", group_id=sg_private.attr_group_id, description= f"{protocl.upper()}:{port} from the public subnet only", ip_protocol=protocl, from_port=port, to_port=port, source_security_group_id=sg_public.ref) ### EC2 Instances ### # Generate some user data _ WIP # user_data = ec2.UserData.custom # One in the public subnet webserver01 = ec2.CfnInstance( self, id="WebServer01", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=web_subnet.ref, key_name="proton_mail_kp", security_group_ids=[sg_public.ref], tags=[core.CfnTag(key="Name", value="WebServer01")]) appserver01 = ec2.CfnInstance( self, id="AppServer01", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=app_subnet.ref, key_name="proton_mail_kp", security_group_ids=[sg_private.ref], tags=[core.CfnTag(key="Name", value="AppServer01")])
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # vpc = ec2.Vpc(self, "VPC", # cidr = "10.1.0.0/16", # max_azs = 2, # subnet_configuration =[ # ec2.SubnetConfiguration(name='edx-subnet-Public', subnet_type=ec2.SubnetType.PUBLIC, cidr_mask=24), # ec2.SubnetConfiguration(name='edx-subnet-Private', subnet_type=ec2.SubnetType.PRIVATE, cidr_mask=24), # ] # ) # core.Tag.add(vpc, key = "Name", value = "edx-build-aws-vpc") # core.Tag.add(vpc.public_subnets[0], key = "Name", value = "edx-subnet-public-a") # core.Tag.add(vpc.public_subnets[1], key = "Name", value = "edx-subnet-public-b") # core.Tag.add(vpc.private_subnets[0], key = "Name", value = "edx-subnet-public-a") # core.Tag.add(vpc.private_subnets[1], key = "Name", value = "edx-subnet-public-b") # Exercise 3 # Create VPC vpc = ec2.CfnVPC(self, "VPC", cidr_block="10.1.0.0/16", tags=[{ "key": "Name", "value": "edx-build-aws-vpc" }]) # Create Internet Gateway internet_gateway = ec2.CfnInternetGateway(self, "InternetGateway", tags=[{ "key": "Name", "value": "edx-igw" }]) # Attach Gateway attach_gateway = ec2.CfnVPCGatewayAttachment( self, "AttachGateway", vpc_id=vpc.ref, internet_gateway_id=internet_gateway.ref) # Create EIP1 eip_1 = ec2.CfnEIP(self, "EIP1", domain="vpc") # Create Public Subnet 1 public_subnet_1 = ec2.CfnSubnet(self, "PublicSubnet1", availability_zone=core.Fn.select( 0, core.Fn.get_azs(core.Aws.REGION)), cidr_block="10.1.1.0/24", vpc_id=vpc.ref, map_public_ip_on_launch=True, tags=[{ "key": "Name", "value": "edx-subnet-public-a" }]) # Create Nat Gateway 1 nat_gateway_1 = ec2.CfnNatGateway( self, "NatGateway1", allocation_id=eip_1.attr_allocation_id, subnet_id=public_subnet_1.ref) # Create Private Route Table 1 private_route_table_1 = ec2.CfnRouteTable(self, "PrivateRouteTable1", vpc_id=vpc.ref, tags=[{ "key": "Name", "value": "edx-routetable-private1" }]) # Create Private Route 1 private_route_1 = ec2.CfnRoute( self, "PrivateRoute1", route_table_id=private_route_table_1.ref, destination_cidr_block="0.0.0.0/0", nat_gateway_id=nat_gateway_1.ref) # Create EIP2 eip_2 = ec2.CfnEIP(self, "EIP2", domain="vpc") # Create Public Subnet 2 public_subnet_2 = ec2.CfnSubnet(self, "PublicSubnet2", availability_zone=core.Fn.select( 1, core.Fn.get_azs(core.Aws.REGION)), cidr_block="10.1.2.0/24", vpc_id=vpc.ref, map_public_ip_on_launch=True, tags=[{ "key": "Name", "value": "edx-subnet-public-b" }]) # Create Nat Gateway 2 nat_gateway_2 = ec2.CfnNatGateway( self, "NatGateway2", allocation_id=eip_2.attr_allocation_id, subnet_id=public_subnet_2.ref) # Create Private Route Table 2 private_route_table_2 = ec2.CfnRouteTable(self, "PrivateRouteTable2", vpc_id=vpc.ref, tags=[{ "key": "Name", "value": "edx-routetable-private2" }]) # Create Private Route 2 private_route_2 = ec2.CfnRoute( self, "PrivateRoute2", route_table_id=private_route_table_2.ref, destination_cidr_block="0.0.0.0/0", nat_gateway_id=nat_gateway_2.ref) # Create Public Route Table public_route_table = ec2.CfnRouteTable(self, "PublicRouteTable", vpc_id=vpc.ref, tags=[{ "key": "Name", "value": "edx-routetable-public" }]) # Create Public Default Route public_default_route = ec2.CfnRoute( self, "PublicDefaultRoute", route_table_id=public_route_table.ref, destination_cidr_block="0.0.0.0/0", gateway_id=internet_gateway.ref) # Create Public Route Association 1 public_route_association_1 = ec2.CfnSubnetRouteTableAssociation( self, "PublicRouteAssociation1", route_table_id=public_route_table.ref, subnet_id=public_subnet_1.ref) # Create Public Route Association 12 public_route_association_2 = ec2.CfnSubnetRouteTableAssociation( self, "PublicRouteAssociation2", route_table_id=public_route_table.ref, subnet_id=public_subnet_2.ref) # Create Private Subnet 1 private_subnet_1 = ec2.CfnSubnet(self, "PrivateSubnet1", availability_zone=core.Fn.select( 0, core.Fn.get_azs(core.Aws.REGION)), cidr_block="10.1.3.0/24", vpc_id=vpc.ref, tags=[{ "key": "Name", "value": "edx-subnet-private-a" }]) # Create Private Subnet 2 private_subnet_2 = ec2.CfnSubnet(self, "PrivateSubnet2", availability_zone=core.Fn.select( 1, core.Fn.get_azs(core.Aws.REGION)), cidr_block="10.1.4.0/24", vpc_id=vpc.ref, tags=[{ "key": "Name", "value": "edx-subnet-private-b" }]) # Create Private Route Association 1 private_route_association_1 = ec2.CfnSubnetRouteTableAssociation( self, "PrivateRouteAssociation1", route_table_id=private_route_table_1.ref, subnet_id=private_subnet_1.ref) # Create Private Route Association 2 private_route_association_1 = ec2.CfnSubnetRouteTableAssociation( self, "PrivateRouteAssociation2", route_table_id=private_route_table_2.ref, subnet_id=private_subnet_2.ref) # Output core.CfnOutput(self, "VPCOutput", value=vpc.ref, description="VPC", export_name="VPC") core.CfnOutput(self, "PublicSubnet1Output", value=public_subnet_1.ref, description="PublicSubnet1", export_name="PublicSubnet1") core.CfnOutput(self, "PublicSubnet2Output", value=public_subnet_2.ref, description="PublicSubnet2", export_name="PublicSubnet2") core.CfnOutput(self, "PrivateSubnet1Output", value=private_subnet_1.ref, description="PrivateSubnet1", export_name="PrivateSubnet1") core.CfnOutput(self, "PrivateSubnet2Output", value=private_subnet_2.ref, description="PrivateSubnet2", export_name="PrivateSubnet2")
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) user_data = ec2.UserData.for_linux(shebang='#!/bin/bash -xe') user_data.add_commands(raw_user_data) # The code that defines your stack goes here vpc = ec2.Vpc( self, "DemoVpc", subnet_configuration=[ ec2.SubnetConfiguration(name="public-subnet", subnet_type=ec2.SubnetType.PUBLIC) ], ) role = iam.Role(self, "InstanceSSM", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")) role.add_managed_policy( iam.ManagedPolicy.from_aws_managed_policy_name( "service-role/AmazonEC2RoleforSSM")) role.add_managed_policy( iam.ManagedPolicy.from_aws_managed_policy_name( "AmazonEC2ReadOnlyAccess")) host = ec2.Instance( self, "myEC2", instance_type=ec2.InstanceType(instance_type_identifier=ec2_type), instance_name="littl_htt", machine_image=ec2.MachineImage.latest_amazon_linux( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, edition=ec2.AmazonLinuxEdition.STANDARD, virtualization=ec2.AmazonLinuxVirt.HVM, storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE), vpc=vpc, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), user_data=user_data, role=role, key_name='ec2demo') # ec2.Instance has no property of BlockDeviceMappings, add via lower layer cdk api: host.instance.add_property_override( "BlockDeviceMappings", [{ "DeviceName": "/dev/xvda", "Ebs": { "VolumeSize": "8", "VolumeType": "gp2", "DeleteOnTermination": "true" } }, { "DeviceName": "/dev/sdb", "Ebs": { "VolumeSize": "1" } }]) host.connections.allow_from_any_ipv4(ec2.Port.tcp(22), "Allow ssh from internet") host.connections.allow_from_any_ipv4(ec2.Port.tcp(80), "Allow http from internet") ec2.CfnEIP(self, 'eip', instance_id=host.instance.ref, tags=[core.CfnTag(key='Name', value='eip')]) core.CfnOutput(self, "Public IP", value=host.instance_public_ip) core.CfnOutput(self, "Instance ID", value=host.instance_id)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Contexts PRJ = self.node.try_get_context("prj") CIDR_VPC = self.node.try_get_context("cidr-out-vpc") CIDR_NGW_SUBNET = self.node.try_get_context("cidr-out-ngw-subnet") CIDR_TGW_SUBNET = self.node.try_get_context("cidr-out-tgw-subnet") # Parameters # Functions def nametag(x): return core.CfnTag(key="Name", value="{}/{}".format(PRJ, x)) # ### Resources # VPC self.vpc = ec2.CfnVPC(self, "vpc", cidr_block=CIDR_VPC, tags=[nametag("outVpc")]) # Ngw Subnet self.ngw_subnet = ec2.CfnSubnet(self, "ngwSubnet", cidr_block=CIDR_NGW_SUBNET, vpc_id=self.vpc.ref, map_public_ip_on_launch=False, availability_zone="ap-northeast-1a", tags=[nametag("outNgwSubnet")]) # Tgw Subnet self.tgw_subnet = ec2.CfnSubnet(self, "tgwSubnet", cidr_block=CIDR_TGW_SUBNET, vpc_id=self.vpc.ref, map_public_ip_on_launch=False, availability_zone="ap-northeast-1a", tags=[nametag("outTgwSubnet")]) # IGW self.igw = ec2.CfnInternetGateway(self, "igw", tags=[nametag("outIgw")]) igw_attachment = ec2.CfnVPCGatewayAttachment( self, "igwAttachment", vpc_id=self.vpc.ref, internet_gateway_id=self.igw.ref) # EIP for NATGW eip = ec2.CfnEIP(self, "eip", domain="vpc", tags=[nametag("outNatgwEip")]) eip.add_depends_on(igw_attachment) # NATGW self.natgw = ec2.CfnNatGateway(self, "natgw", allocation_id=eip.attr_allocation_id, subnet_id=self.ngw_subnet.ref, tags=[nametag("outNatgw")]) # RouteTable(NGW Subnet) self.ngw_rtb = ec2.CfnRouteTable(self, "ngwRtb", vpc_id=self.vpc.ref, tags=[nametag("outNgwRtb")]) ec2.CfnSubnetRouteTableAssociation(self, "ngwRtbAssoc", route_table_id=self.ngw_rtb.ref, subnet_id=self.ngw_subnet.ref) # RouteTable(TGW Subnet) self.tgw_rtb = ec2.CfnRouteTable(self, "tgwRtb", vpc_id=self.vpc.ref, tags=[nametag("outTgwRtb")]) ec2.CfnSubnetRouteTableAssociation(self, "tgwRtbAssoc", route_table_id=self.tgw_rtb.ref, subnet_id=self.tgw_subnet.ref)
def __init__(self, scope: core.Construct, id: str, data, iam_vars) -> None: super().__init__(scope, id) # VPC vpc = ec2.CfnVPC(self, "cdk-vpc", cidr_block=data["vpc"]) igw = ec2.CfnInternetGateway(self, id="igw") ec2.CfnVPCGatewayAttachment(self, id="igw-attach", vpc_id=vpc.ref, internet_gateway_id=igw.ref) public_route_table = ec2.CfnRouteTable(self, id="public_route_table", vpc_id=vpc.ref) ec2.CfnRoute(self, id="public_route", route_table_id=public_route_table.ref, destination_cidr_block="0.0.0.0/0", gateway_id=igw.ref) public_subnets = [] for i, s in enumerate(data["subnets"]["public"]): subnet = ec2.CfnSubnet(self, id="public_{}".format(s), cidr_block=s, vpc_id=vpc.ref, availability_zone=core.Fn.select( i, core.Fn.get_azs()), map_public_ip_on_launch=True) public_subnets.append(subnet) ec2.CfnSubnetRouteTableAssociation( self, id="public_{}_association".format(s), route_table_id=public_route_table.ref, subnet_id=subnet.ref) eip = ec2.CfnEIP(self, id="natip") nat = ec2.CfnNatGateway(self, id="nat", allocation_id=eip.attr_allocation_id, subnet_id=public_subnets[0].ref) private_route_table = ec2.CfnRouteTable(self, id="private_route_table", vpc_id=vpc.ref) ec2.CfnRoute(self, id="private_route", route_table_id=private_route_table.ref, destination_cidr_block="0.0.0.0/0", nat_gateway_id=nat.ref) private_subnets = [] for i, s in enumerate(data["subnets"]["private"]): subnet = ec2.CfnSubnet(self, id="private_{}".format(s), cidr_block=s, vpc_id=vpc.ref, availability_zone=core.Fn.select( i, core.Fn.get_azs()), map_public_ip_on_launch=False) private_subnets.append(subnet) ec2.CfnSubnetRouteTableAssociation( self, id="private_{}_association".format(s), route_table_id=private_route_table.ref, subnet_id=subnet.ref) # Security groups lb_sg = ec2.CfnSecurityGroup(self, id="lb", group_description="LB SG", vpc_id=vpc.ref) lambda_sg = ec2.CfnSecurityGroup(self, id="lambda", group_description="Lambda SG", vpc_id=vpc.ref) public_prefix = ec2.CfnPrefixList(self, id="cidr_prefix", address_family="IPv4", max_entries=1, prefix_list_name="public", entries=[{ "cidr": "0.0.0.0/0", "description": "Public" }]) _sg_rules = [{ 'sg': lb_sg.attr_group_id, 'rules': [{ "direction": "ingress", "description": "HTTP from Internet", "from_port": 80, "to_port": 80, "protocol": "tcp", "cidr_blocks": public_prefix.ref }, { "direction": "egress", "description": "LB to Lambda", "from_port": 80, "to_port": 80, "protocol": "tcp", "source_security_group_id": lambda_sg.attr_group_id }] }, { "sg": lambda_sg.attr_group_id, "rules": [{ "direction": "ingress", "description": "HTTP from LB", "from_port": 80, "to_port": 80, "protocol": "tcp", "source_security_group_id": lb_sg.attr_group_id }, { "direction": "egress", "description": "All to Internet", "from_port": 0, "to_port": 65535, "protocol": "tcp", "cidr_blocks": public_prefix.ref }] }] for ruleset in _sg_rules: for rule in ruleset["rules"]: if rule["direction"] == "ingress": ec2.CfnSecurityGroupIngress( self, id=rule["description"].replace(" ", "_"), description=rule["description"], to_port=rule["to_port"], from_port=rule["from_port"], ip_protocol=rule["protocol"], group_id=ruleset["sg"], source_prefix_list_id=rule["cidr_blocks"] if "cidr_blocks" in rule else None, source_security_group_id=rule[ "source_security_group_id"] if "source_security_group_id" in rule else None) else: ec2.CfnSecurityGroupEgress( self, id=rule["description"].replace(" ", "_"), description=rule["description"], to_port=rule["to_port"], from_port=rule["from_port"], ip_protocol=rule["protocol"], group_id=ruleset["sg"], destination_prefix_list_id=rule["cidr_blocks"] if "cidr_blocks" in rule else None, destination_security_group_id=rule[ "source_security_group_id"] if "source_security_group_id" in rule else None) # IAM assume_policy_doc = iam.PolicyDocument() for statement in iam_vars["assume"]["Statement"]: _statement = iam.PolicyStatement(actions=[statement["Action"]], ) _statement.add_service_principal(statement["Principal"]["Service"]) assume_policy_doc.add_statements(_statement) role = iam.CfnRole(self, id="iam_role", path="/", assume_role_policy_document=assume_policy_doc) role_policy_doc = iam.PolicyDocument() for statement in iam_vars["policy"]["Statement"]: _statement = iam.PolicyStatement(actions=statement["Action"], resources=["*"]) role_policy_doc.add_statements(_statement) policy = iam.CfnPolicy(self, id="iam_policy", policy_document=role_policy_doc, policy_name="cdkPolicy", roles=[role.ref]) # Lambda shutil.make_archive("../lambda", 'zip', "../lambda/") s3_client = boto3.client('s3') s3_client.upload_file("../lambda.zip", "cloudevescops-zdays-demo", "cdk.zip") function = lmd.CfnFunction(self, id="lambda_function", handler="lambda.lambda_handler", role=role.attr_arn, runtime="python3.7", code={ "s3Bucket": "cloudevescops-zdays-demo", "s3Key": "cdk.zip" }, vpc_config={ "securityGroupIds": [lambda_sg.ref], "subnetIds": [s.ref for s in private_subnets] }, environment={"variables": { "TOOL": "CDK" }}) # LB lb = alb.CfnLoadBalancer(self, id="alb", name="lb-cdk", scheme="internet-facing", type="application", subnets=[s.ref for s in public_subnets], security_groups=[lb_sg.ref]) lmd.CfnPermission(self, id="lambda_permis", action="lambda:InvokeFunction", function_name=function.ref, principal="elasticloadbalancing.amazonaws.com") tg = alb.CfnTargetGroup(self, id="alb_tg", name="lambda-cdk", target_type="lambda", health_check_enabled=True, health_check_interval_seconds=40, health_check_path="/", health_check_timeout_seconds=30, targets=[{ "id": function.get_att("Arn").to_string() }], matcher={"httpCode": "200"}) alb.CfnListener(self, id="listener", default_actions=[{ "type": "forward", "targetGroupArn": tg.ref }], load_balancer_arn=lb.ref, port=80, protocol="HTTP") core.CfnOutput(self, id="fqdn", value=lb.attr_dns_name)
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) vpc = ec2.Vpc(self, id="MyVPC", nat_gateways=0, cidr="192.168.0.0/20", max_azs=3, subnet_configuration=[]) pub_subnet = ec2.PublicSubnet(self, id="PublicSubnet", availability_zone="eu-central-1c", cidr_block="192.168.0.0/24", vpc_id=vpc.vpc_id, map_public_ip_on_launch=True) igw = ec2.CfnInternetGateway( self, id="MyIGW", tags=[core.CfnTag(key="Name", value="IGW")]) ec2.CfnVPCGatewayAttachment(self, id="IGW_Assoc", vpc_id=vpc.vpc_id, internet_gateway_id=igw.ref) pub_subnet.add_route(id="default_route-sub01", router_id=igw.ref, router_type=ec2.RouterType('GATEWAY'), destination_cidr_block="0.0.0.0/0", enables_internet_connectivity=True) # Elastic IP eip_01 = ec2.CfnEIP(self, id="EIP01") # NAT gateway ngw = ec2.CfnNatGateway(self, id="NAT_GW", allocation_id=eip_01.attr_allocation_id, subnet_id=pub_subnet.subnet_id, tags=[core.CfnTag(key="Name", value="NAT_GW")]) subnet01 = ec2.Subnet(self, id="Subnet01", availability_zone="eu-central-1a", cidr_block="192.168.1.0/24", vpc_id=vpc.vpc_id, map_public_ip_on_launch=False) subnet02 = ec2.Subnet(self, id="Subnet02", availability_zone="eu-central-1b", cidr_block="192.168.2.0/24", vpc_id=vpc.vpc_id, map_public_ip_on_launch=False) subnet01.add_route(id="default_route-sub01", router_id=ngw.ref, router_type=ec2.RouterType('NAT_GATEWAY'), destination_cidr_block="0.0.0.0/0", enables_internet_connectivity=True) subnet02.add_route(id="default_route-sub02", router_id=ngw.ref, router_type=ec2.RouterType('NAT_GATEWAY'), destination_cidr_block="0.0.0.0/0", enables_internet_connectivity=True) sg_lb = ec2.CfnSecurityGroup( self, id="SG_ALB", group_description="SG for the APP LB", group_name="SG_ALB", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="SG_ALB")]) sg_ec2i = ec2.CfnSecurityGroup( self, id="SG_Instances", group_description="SG for the Instances", group_name="SG_Instances", vpc_id=vpc.vpc_id, tags=[core.CfnTag(key="Name", value="SG_Instances")]) # my_home_ip = requests.get("https://api.ipify.org").text my_home_ip = "94.112.113.195" ports_pub = {'tcp': [22, 80], 'icmp': [-1]} for protocol, ports_list in ports_pub.items(): for port in ports_list: ec2.CfnSecurityGroupIngress( self, id=f"sg_alb_in_{protocol}_{port}", group_id=sg_lb.attr_group_id, ip_protocol=protocol, cidr_ip=f"{my_home_ip}/32", to_port=port, from_port=port, description=f"{protocol.upper()} {port} from home IP") ec2.CfnSecurityGroupIngress( self, id=f"sg_ec2i_in_{protocol}_{port}", group_id=sg_ec2i.attr_group_id, ip_protocol=protocol, to_port=port, from_port=port, source_security_group_id=sg_lb.ref, description=f"{protocol.upper()} {port} from the ALB SG") with open( "/home/dragos/Documents/AWS_CDK/app_lb_sample/app_lb_sample/configure.sh", 'r') as config_file: ud = core.Fn.base64(config_file.read()) bastion_host = ec2.CfnInstance( self, id="bastion", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=pub_subnet.subnet_id, key_name="proton_mail_kp", security_group_ids=[sg_lb.ref], tags=[core.CfnTag(key="Name", value="bastion")]) instance01 = ec2.CfnInstance( self, id="WebServer01", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=subnet01.subnet_id, key_name="proton_mail_kp", security_group_ids=[sg_ec2i.ref], user_data=ud, tags=[core.CfnTag(key="Name", value="WebServer01")]) instance02 = ec2.CfnInstance( self, id="WebServer02", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=subnet02.subnet_id, key_name="proton_mail_kp", security_group_ids=[sg_ec2i.ref], user_data=ud, tags=[core.CfnTag(key="Name", value="WebServer02")]) # health_check = elbv2.HealthCheck(enabled=True, # healthy_http_codes="200", # path="/index.html", # protocol=elbv2.Protocol("HTTP")) target01 = elbv2.CfnTargetGroup.TargetDescriptionProperty( id=instance01.ref) target02 = elbv2.CfnTargetGroup.TargetDescriptionProperty( id=instance02.ref) tg = elbv2.CfnTargetGroup( self, id="TG-WEB-HTTP", name="TG-WEB-HTTP", health_check_enabled=True, health_check_path="/index.html", health_check_port="80", matcher=elbv2.CfnTargetGroup.MatcherProperty(http_code="200"), port=80, protocol="HTTP", # CASE SENSITIVE target_type="instance", # CASE SENSITIVE targets=[target01, target02], vpc_id=vpc.vpc_id) alb = elbv2.CfnLoadBalancer( self, id="MyALB-HTTP", ip_address_type="ipv4", name="MyALB-HTTP", scheme="internet-facing", security_groups=[sg_lb.ref], type="application", subnets=[subnet01.subnet_id, subnet02.subnet_id]) def_act = Listener.ActionProperty(type="forward", authenticate_cognito_config=None, authenticate_oidc_config=None, fixed_response_config=None, forward_config=None, order=50000, redirect_config=None, target_group_arn=tg.ref) listener = elbv2.CfnListener(self, id="Listener01", load_balancer_arn=alb.ref, port=80, protocol="HTTP", default_actions=[def_act])
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here # vpc network vpc = aws_ec2.CfnVPC(self, 'VPC', cidr_block='10.0.0.0/16', enable_dns_hostnames=True, enable_dns_support=True, instance_tenancy='default', tags=[core.CfnTag(key='Name', value='vpc')]) internetgateway = aws_ec2.CfnInternetGateway( self, 'internetgateway', tags=[core.CfnTag(key='Name', value='internetgateway')]) aws_ec2.CfnVPCGatewayAttachment( self, 'VPCGatewayAttachment', vpc_id=vpc.ref, internet_gateway_id=internetgateway.ref) networkacl = aws_ec2.CfnNetworkAcl( self, 'NetworkAcl', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='networkacl')]) aws_ec2.CfnNetworkAclEntry(self, 'NetworkAclEntry01', network_acl_id=networkacl.ref, protocol=-1, rule_action='allow', rule_number=100, cidr_block='0.0.0.0/0', egress=True) aws_ec2.CfnNetworkAclEntry(self, 'NetworkAclEntry03', network_acl_id=networkacl.ref, protocol=-1, rule_action='allow', rule_number=100, cidr_block='0.0.0.0/0', egress=False) # public network publicsubnet01 = aws_ec2.CfnSubnet( self, 'publicsubnet01', cidr_block='10.0.0.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name', value='publicsubnet01')]) publicsubnet02 = aws_ec2.CfnSubnet( self, 'publicsubnet02', cidr_block='10.0.1.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name', value='publicsubnet02')]) publicsubnet03 = aws_ec2.CfnSubnet( self, 'publicsubnet03', cidr_block='10.0.2.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name', value='publicsubnet03')]) publicroutetable01 = aws_ec2.CfnRouteTable( self, 'publicroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='publicroutetable01')]) publicroutetable02 = aws_ec2.CfnRouteTable( self, 'publicroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='publicroutetable02')]) publicroutetable03 = aws_ec2.CfnRouteTable( self, 'publicroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='publicroutetable03')]) aws_ec2.CfnRoute( self, 'publicroute01', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable01.ref, ) aws_ec2.CfnRoute(self, 'publicroute02', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable02.ref) aws_ec2.CfnRoute(self, 'publicroute03', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable03.ref) aws_ec2.CfnSubnetRouteTableAssociation( self, 'publicsubnetroutetableassociation01', route_table_id=publicroutetable01.ref, subnet_id=publicsubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation( self, 'publicsubnetroutetableassociation02', route_table_id=publicroutetable02.ref, subnet_id=publicsubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation( self, 'publicsubnetroutetableassociation03', route_table_id=publicroutetable03.ref, subnet_id=publicsubnet03.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'publicSubnetNetworkAclAssociation01', network_acl_id=networkacl.ref, subnet_id=publicsubnet01.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'publicSubnetNetworkAclAssociation02', network_acl_id=networkacl.ref, subnet_id=publicsubnet02.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'publicSubnetNetworkAclAssociation03', network_acl_id=networkacl.ref, subnet_id=publicsubnet03.ref) # private network privatesubnet01 = aws_ec2.CfnSubnet( self, 'privatesubnet01', cidr_block='10.0.11.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name', value='privatesubnet01')]) privatesubnet02 = aws_ec2.CfnSubnet( self, 'privatesubnet02', cidr_block='10.0.12.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name', value='privatesubnet02')]) privatesubnet03 = aws_ec2.CfnSubnet( self, 'privatesubnet03', cidr_block='10.0.13.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name', value='privatesubnet03')]) privateroutetable01 = aws_ec2.CfnRouteTable( self, 'privateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='privateroutetable01')]) privateroutetable02 = aws_ec2.CfnRouteTable( self, 'privateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='privateroutetable02')]) privateroutetable03 = aws_ec2.CfnRouteTable( self, 'privateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='privateroutetable03')]) aws_ec2.CfnSubnetRouteTableAssociation( self, 'privatesubnetroutetableassociation01', route_table_id=privateroutetable01.ref, subnet_id=privatesubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation( self, 'privatesubnetroutetableassociation02', route_table_id=privateroutetable02.ref, subnet_id=privatesubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation( self, 'privatesubnetroutetableassociation03', route_table_id=privateroutetable03.ref, subnet_id=privatesubnet03.ref) eip01 = aws_ec2.CfnEIP(self, 'eip01', tags=[core.CfnTag(key='Name', value='eip01')]) eip02 = aws_ec2.CfnEIP(self, 'eip02', tags=[core.CfnTag(key='Name', value='eip02')]) eip03 = aws_ec2.CfnEIP(self, 'eip03', tags=[core.CfnTag(key='Name', value='eip03')]) natgateway01 = aws_ec2.CfnNatGateway( self, 'natgateway01', allocation_id=eip01.attr_allocation_id, subnet_id=publicsubnet01.ref, tags=[core.CfnTag(key='Name', value='natgateway01')]) natgateway02 = aws_ec2.CfnNatGateway( self, 'natgateway02', allocation_id=eip02.attr_allocation_id, subnet_id=publicsubnet02.ref, tags=[core.CfnTag(key='Name', value='natgateway02')]) natgateway03 = aws_ec2.CfnNatGateway( self, 'natgateway03', allocation_id=eip03.attr_allocation_id, subnet_id=publicsubnet03.ref, tags=[core.CfnTag(key='Name', value='natgateway03')]) aws_ec2.CfnRoute(self, 'privateroute01', destination_cidr_block='0.0.0.0/0', nat_gateway_id=natgateway01.ref, route_table_id=privateroutetable01.ref) aws_ec2.CfnRoute(self, 'privateroute02', destination_cidr_block='0.0.0.0/0', nat_gateway_id=natgateway02.ref, route_table_id=privateroutetable02.ref) aws_ec2.CfnRoute(self, 'privateroute03', destination_cidr_block='0.0.0.0/0', nat_gateway_id=natgateway03.ref, route_table_id=privateroutetable03.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'privateSubnetNetworkAclAssociation01', network_acl_id=networkacl.ref, subnet_id=privatesubnet01.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'privateSubnetNetworkAclAssociation02', network_acl_id=networkacl.ref, subnet_id=privatesubnet02.ref) aws_ec2.CfnSubnetNetworkAclAssociation( self, 'privateSubnetNetworkAclAssociation03', network_acl_id=networkacl.ref, subnet_id=privatesubnet03.ref) # isolate network ''' isolatesubnet01 = aws_ec2.CfnSubnet(self, 'isolatesubnet01', cidr_block='10.0.21.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name', value='isolatesubnet01')]) isolatesubnet02 = aws_ec2.CfnSubnet(self, 'isolatesubnet02', cidr_block='10.0.22.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name', value='isolatesubnet02')]) isolatesubnet03 = aws_ec2.CfnSubnet(self, 'isolatesubnet03', cidr_block='10.0.23.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name', value='isolatesubnet03')]) isolateroutetable01 = aws_ec2.CfnRouteTable(self, 'isolateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable01')]) isolateroutetable02 = aws_ec2.CfnRouteTable(self, 'isolateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable02')]) isolateroutetable03 = aws_ec2.CfnRouteTable(self, 'isolateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable03')]) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation01', route_table_id=isolateroutetable01.ref, subnet_id=isolatesubnet01.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation02', route_table_id=isolateroutetable02.ref, subnet_id=isolatesubnet02.ref) aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation03', route_table_id=isolateroutetable03.ref, subnet_id=isolatesubnet03.ref) aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation01', network_acl_id=networkacl.ref, subnet_id=isolatesubnet01.ref) aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation02', network_acl_id=networkacl.ref, subnet_id=isolatesubnet02.ref) aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation03', network_acl_id=networkacl.ref, subnet_id=isolatesubnet03.ref) ''' # output core.CfnOutput(self, 'output01', value=vpc.ref, description='vpcid', export_name='vpcid01') core.CfnOutput(self, 'output02', value=publicsubnet01.ref, description='publicsubnet01', export_name='publicsubnet01') core.CfnOutput(self, 'output03', value=publicsubnet02.ref, description='publicsubnet02', export_name='publicsubnet02') core.CfnOutput(self, 'output04', value=publicsubnet03.ref, description='publicsubnet03', export_name='publicsubnet03') core.CfnOutput(self, 'output05', value=privatesubnet01.ref, description='privatesubnet01', export_name='privatesubnet01') core.CfnOutput(self, 'output06', value=privatesubnet02.ref, description='privatesubnet02', export_name='privatesubnet02') core.CfnOutput(self, 'output07', value=privatesubnet03.ref, description='privatesubnet03', export_name='privatesubnet03')
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # get vpc used vpc-id vpc = ec2.Vpc.from_lookup(self, "EKSNode", vpc_id=vpc_id) subnets = [] if len(vpc.private_subnets) > 0: subnets.extend(vpc.private_subnets) elif len(vpc.public_subnets) > 0: subnets.extend(vpc.public_subnets) else: print("Not any subnets found,") return # add a worker node role workerRole = iam.Role.from_role_arn(self, 'nodeRole', role_arn=nodes_role_arn) #node_sg=ec2.SecurityGroup.from_security_group_id(self,"nodeSG",security_group_id='sg-0461d7bdfb942d0ef') # add iam instance profile instanceProfile = iam.CfnInstanceProfile( self, 'kopsNodeProfile', roles=[workerRole.role_name], instance_profile_name='eks-cluster-workerNodeProfile') # read and base64 encode userdata file data = open('nodeup.sh', 'rb').read() encodedBytes = base64.encodebytes(data) encodedStr = str(encodedBytes, "utf-8") # add worker instances and associate EIPs for i in range(0, 1): # add a network interface eni0 = ec2.CfnNetworkInterface( self, 'eni-' + str(i), subnet_id='subnet-040455b57b16a4cc9', group_set=['sg-0461d7bdfb942d0ef', 'sg-0b3ae225b27e04679']) # add worker instances instance = ec2.CfnInstance( self, "kops-node-" + str(i), image_id=ami_id, instance_type="t2.medium", block_device_mappings=[ { 'deviceName': '/dev/xvda', 'ebs': { 'deleteOnTermination': True, 'volumeSize': 40, 'volumeType': 'gp2', 'encrypted': False, }, }, { 'deviceName': '/dev/sdb', # for /var/lib/docker 'ebs': { 'deleteOnTermination': True, 'volumeSize': 100, 'volumeType': 'gp2', 'encrypted': False, }, }, { 'deviceName': '/dev/sdc', # for data volume 'ebs': { 'deleteOnTermination': True, 'volumeSize': 200, 'volumeType': 'gp2', 'encrypted': False, }, }, ], key_name=key_name, network_interfaces=[{ 'deviceIndex': '0', 'networkInterfaceId': eni0.ref, }], iam_instance_profile=instanceProfile.ref, #iam_instance_profile=nodes_role_arn, tags=[ core.CfnTag(key="KubernetesCluster", value="eks-asgfleet-01"), core.CfnTag(key="Name", value="test-01"), core.CfnTag(key="k8s.io/role/node", value="1"), core.CfnTag(key="CDK/manual", value="singlenode"), ], user_data=encodedStr) #associate EIP with the instance eip = ec2.CfnEIP(self, "eip-" + str(i)) ec2.CfnEIPAssociation(self, "eip-ass-i" + str(i), allocation_id=eip.attr_allocation_id, network_interface_id=eni0.ref)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here # vpc = ec2.Vpc.from_lookup(self,'vpc',vpc_name="eksctl-Cloudteam-cluster/VPC" ) prj_name = self.node.try_get_context("token") shellCommands = ec2.UserData.for_linux() shellCommands.add_commands("yum update -y") shellCommands.add_commands("yum install docker -y") shellCommands.add_commands("usermod -aG dokcer ec2-user") shellCommands.add_commands("systemctl start docker") shellCommands.add_commands("systemctl enable docker") shellCommands.add_commands( "docker run -d -v /home/ec2-user/.gitlab-runner:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock --name gitlab-runner-register gitlab/gitlab-runner:alpine register --non-interactive --url https://gitlab.com./ --registration-token " + prj_name + " --docker-volumes \"/var/run/docker.sock:/var/run/docker.sock\" --executor docker --docker-image \"alpine:latest\" --description \"Docker Runner\" --tag-list \"demo,runner,cdk\" --docker-privileged") shellCommands.add_commands( "sleep 2 && docker run -d -v /home/ec2-user/.gitlab-runner:/etc/gitlab-runner -v /var/run/docker.sock:/var/run/docker.sock --name gitlab-runner gitlab/gitlab-runner:alpine") vpc = ec2.Vpc.from_lookup(self, 'vpc', is_default=True) newSG = ec2.SecurityGroup(self, 'Webec2SG', vpc=vpc, security_group_name="Webec2SG", description="for aws cdk python lab create webec2 SG") newSG.add_ingress_rule(peer=ec2.Peer.ipv4( your_public_ip), connection=ec2.Port.tcp(22)) newSG.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(80)) newSG.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(443)) # aws linux 2 # newec2 = ec2.Instance(self, 'webec2', instance_type=ec2.InstanceType(instance_type_identifier="t2.micro"), instance_name='webec2', vpc=vpc, security_group=newSG, # key_name=my_key_pair, machine_image=ec2.LookupMachineImage(name="amzn2-ami-hvm-2.0.20200406.0-x86_64-gp2", user_data=ec2.UserData.custom(userdata))) newec2 = ec2.Instance(self, 'webec2', instance_type=ec2.InstanceType(instance_type_identifier="t2.micro"), instance_name='webec2', vpc=vpc, security_group=newSG, key_name=my_key_pair, machine_image=ec2.LookupMachineImage(name="amzn2-ami-hvm-2.0.20200406.0-x86_64-gp2", user_data=shellCommands)) # ubuntu 16.04 # newec2 = ec2.Instance(self, 'webec2', instance_type=ec2.InstanceType(instance_type_identifier="t2.micro"), instance_name='webec2', vpc=vpc, security_group=newSG, # key_name=my_key_pair, machine_image=ec2.LookupMachineImage(name="ubuntu/images/hvm-ssd/ubuntu-xenial-16.04-amd64-server-20200407", user_data=ec2.UserData.custom(userdata))) newec2.role.add_managed_policy( iam.ManagedPolicy.from_aws_managed_policy_name("AmazonSSMManagedInstanceCore")) neweip = ec2.CfnEIP(self, "EIP", domain=vpc.vpc_id, tags=[core.CfnTag( key="Name", value="WEBEC2EIP")], instance_id=newec2.instance_id) # search my route53 HostedZone. zone = r53.HostedZone.from_hosted_zone_attributes( self, 'MYHOSTED_ZONE', hosted_zone_id=my_hosted_zone, zone_name=my_zone_name) # target neweip . newdomain = r53.ARecord(self, "Route53NewArecord", zone=zone, target=r53.RecordTarget.from_ip_addresses(neweip.ref), record_name="cdk-demo", ttl=core.Duration.minutes(5)) core.CfnOutput(self, 'domainname', value=newdomain.domain_name) core.CfnOutput(self, 'hosted_zone', value=zone.zone_name) core.CfnOutput(self, 'ec2-public-ip', value=newec2.instance_public_dns_name) core.CfnOutput(self, 'vpc-id', value=vpc.vpc_id) core.CfnOutput(self, 'sg-id', value=newSG.security_group_id) core.CfnOutput(self, 'instance-id', value=newec2.instance_id) core.CfnOutput(self, 'local-az', value=newec2.instance.availability_zone) core.CfnOutput(self, 'subnet-id', value=newec2.instance.subnet_id) core.CfnOutput(self, 'region', value=self.region)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) self.vpc = ec2.Vpc( self, id="VPC", cidr="10.0.0.0/16", max_azs=2, nat_gateways=1, subnet_configuration=[ ec2.SubnetConfiguration(name="public", cidr_mask=24, reserved=False, subnet_type=ec2.SubnetType.PUBLIC), ec2.SubnetConfiguration(name="private", cidr_mask=24, reserved=False, subnet_type=ec2.SubnetType.PRIVATE), ec2.SubnetConfiguration(name="DB", cidr_mask=24, reserved=False, subnet_type=ec2.SubnetType.ISOLATED), # ec2.SubnetConfiguration( # name="DB2", cidr_mask=24, # reserved=False, subnet_type=ec2.SubnetType.ISOLATED # ) ], enable_dns_hostnames=True, enable_dns_support=True) core.Tag(key="Application", value=self.stack_name) \ .add(self.vpc, key="Application", value=self.stack_name) # core.Tag("Network", "Public").add(vpc) # core.Tag("Name", "VPCName-Environment").add(vpc) # core.Tag("Environment", "Environment").add(vpc) bastion = ec2.BastionHostLinux( self, id="BastionHost", vpc=self.vpc, instance_name="BastionHost", instance_type=ec2.InstanceType(ec2_type), subnet_selection=ec2.SubnetSelection( subnet_type=ec2.SubnetType.PUBLIC)) bastion.allow_ssh_access_from(ec2.Peer.any_ipv4()) # Setup key_name for EC2 instance login if you don't use Session Manager #bastion.instance.instance.add_property_override("KeyName", key_name) ec2.CfnEIP(self, id="BastionHostEIP", domain="vpc", instance_id=bastion.instance_id) core.CfnOutput( self, id="VPCId", value=self.vpc.vpc_id, description="VPC ID", export_name=f"{self.region}:{self.account}:{self.stack_name}:vpc-id" ) core.CfnOutput( self, id="BastionPrivateIP", value=bastion.instance_private_ip, description="BASTION Private IP", export_name= f"{self.region}:{self.account}:{self.stack_name}:bastion-private-ip" ) core.CfnOutput( self, id="BastionPublicIP", value=bastion.instance_public_ip, description="BASTION Public IP", export_name= f"{self.region}:{self.account}:{self.stack_name}:bastion-public-ip" )
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) high_cpu_topic = sns.Topic(self, 'high-cpu-topic', display_name='myHighCpuAlarm') # phone number format must be 12225558888 for US phone_param = ssm.StringParameter.from_string_parameter_name(self, 'phone-param', 'notification-phone') high_cpu_topic_sub = sns.Subscription(self, 'high-cpu-topic-sub', topic=high_cpu_topic, protocol=sns.SubscriptionProtocol.SMS, endpoint=phone_param.string_value) default_vpc = ec2.Vpc.from_lookup(self, 'default-vpc', is_default=True) monitored_instance = ec2.Instance(self, 'monitored-instance', instance_name='devassoc-monitored', instance_type=type.R3_XLARGE, machine_image=ec2.MachineImage.generic_linux( ami_map=ami_map ), vpc=default_vpc) high_cpu_metric = cw.Metric(namespace='AWS/EC2', metric_name='CPUUtilization', dimensions={ 'InstanceId': monitored_instance.instance_id }, statistic='Average', unit=cw.Unit.PERCENT, period=core.Duration.seconds(300)) high_cpu_alarm = high_cpu_metric.create_alarm(self, 'high-cpu-alarm', alarm_name='cpu-mon', alarm_description='Alarm when CPU exceeds 70%', comparison_operator=cw.ComparisonOperator.GREATER_THAN_THRESHOLD, evaluation_periods=2, period=core.Duration.seconds(300), threshold=70, actions_enabled=True) high_cpu_action = cwa.SnsAction(high_cpu_topic) high_cpu_alarm.add_alarm_action(high_cpu_action) ec2.CfnEIP(self, 'devassoc-elastic-ip') # not really a service role, but there are problems with that, per # https://github.com/aws/aws-cdk/issues/3492 config_service_role = iam.Role(self, 'devassoc-config-service-role', assumed_by=iam.ServicePrincipal('config.amazonaws.com'), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name('service-role/AWSConfigRole') ]) config_recorder = config.CfnConfigurationRecorder(self, 'devassoc-recorder', name='ConfigRecorder', role_arn=config_service_role.role_arn, recording_group=config.CfnConfigurationRecorder.RecordingGroupProperty( all_supported=True) ) config_bucket = s3.Bucket(self, 'config-bucket', bucket_name='devassoc-config', removal_policy=core.RemovalPolicy.DESTROY, auto_delete_objects=True) config_bucket.add_to_resource_policy(iam.PolicyStatement(effect=iam.Effect.ALLOW, principals=[iam.ServicePrincipal('config.amazonaws.com')], resources=[config_bucket.bucket_arn], actions=['s3:GetBucketAcl'])) config_bucket.add_to_resource_policy(iam.PolicyStatement(effect=iam.Effect.ALLOW, principals=[iam.ServicePrincipal('config.amazonaws.com')], resources=[config_bucket.arn_for_objects( f"AWSLogs/{core.Stack.of(self).account}/Config/*")], actions=['s3:PutObject'], conditions={'StringEquals': { 's3:x-amz-acl': 'bucket-owner-full-control'}})) eip_rule = config.ManagedRule(self, 'devassoc-managed-rule', identifier=config.ManagedRuleIdentifiers.EIP_ATTACHED, config_rule_name='devassoc-eip-rule') eip_rule.node.add_dependency(config_recorder) eip_compliance_topic = sns.Topic(self, 'eip-compliance-topic', display_name='EIP Compliance Topic') eip_compliance_topic_sub = sns.Subscription(self, 'eip-compliance-topic-sub', topic=eip_compliance_topic, protocol=sns.SubscriptionProtocol.SMS, endpoint=phone_param.string_value) eip_rule.on_compliance_change('eip-compliance-change', target=targets.SnsTopic(eip_compliance_topic)) config.CfnDeliveryChannel(self, 'devassoc-config-delivery', s3_bucket_name=config_bucket.bucket_name, sns_topic_arn=eip_compliance_topic.topic_arn)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) #create S3 access role for ec2 ec2Role = iam.Role( self, "ec2role", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3ReadOnlyAccess") ] ) instanceProfile = iam.CfnInstanceProfile( self, "ec2Profile", roles=[ec2Role.role_name], instance_profile_name="aws-cdk-handson-ec2Profile", ) #create new VPC for lab02 vpc= ec2.Vpc(self,id="aws-cdk-handson-vpc",cidr="172.30.0.0/16",nat_gateways=0, subnet_configuration=[ { "cidrMask": 24,"name": "subnet-1-", "subnetType": ec2.SubnetType.PUBLIC }, { "cidrMask": 24,"name": "subnet-2-", "subnetType": ec2.SubnetType.PUBLIC }, { "cidrMask": 24,"name": "subnet-3-", "subnetType": ec2.SubnetType.PUBLIC }, ]) #create new Security Group sg = ec2.CfnSecurityGroup( self, "ec2securitygroup", group_description="this is aws-cdk-handson workshop", group_name="ec2securitygroup", security_group_ingress=[ { "ipProtocol": "tcp", "fromPort": 80, "toPort": 80, "cidrIp": "0.0.0.0/0", }, { "ipProtocol": "tcp", "fromPort": 22, "toPort": 22, "cidrIp": "0.0.0.0/0", }, ], vpc_id=vpc.vpc_id ) #create Elastic Network Interface eni0 = ec2.CfnNetworkInterface( self, "eni-" + str(1), subnet_id=vpc.public_subnets[0].subnet_id, #group_set=["sg-08cddeaeec7392eb2"] group_set=[sg.attr_group_id] ) #read and base64 encode userdata file data = open("httpd.sh", "rb").read() encodedBytes = base64.encodebytes(data) encodedStr = str(encodedBytes, "utf-8") #create ec2 instances ami=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2) instance = ec2.CfnInstance( self, "ec2-httpd-" + str(1), image_id=ami.get_image(self).image_id, #use Amazon Linux 2 AMI instance_type="t2.micro", key_name="wsu-ap-northeast-1", network_interfaces=[ { "deviceIndex": "0", "networkInterfaceId": eni0.ref } ], tags=[core.CfnTag(key="Name", value="aws-cdk-handson-ec2")], iam_instance_profile=instanceProfile.ref, user_data=encodedStr ) #associate EIP with the instance eip = ec2.CfnEIP(self, "eip-" + str(1)) ec2.CfnEIPAssociation(self, "eip-ass-i" + str(1), allocation_id=eip.attr_allocation_id, network_interface_id=eni0.ref) #Export PublicIP and PublicDNSName core.CfnOutput(self,"PublicIP",export_name="PublicIP",value=instance.attr_public_ip) core.CfnOutput(self,"PublicDNSName",export_name="PublicDNSName",value=instance.attr_public_dns_name)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # get the local ip address to whitelist whitelist_ip = requests.get("https://ipinfo.io/ip").text.strip( '\n') + "/32" # create a VPC in all AZs vpc = aws_ec2.Vpc(self, 'dns_vpc', max_azs=10, nat_gateways=0, subnet_configuration=[ aws_ec2.SubnetConfiguration( name="publicSubnet", subnet_type=aws_ec2.SubnetType.PUBLIC) ]) # add vpc flowlog for easier debugging vpc.add_flow_log("flowlog") # add user data to ec2 instance user_data = aws_ec2.UserData.for_linux() # add ec2 instance user data from file def get_userdata(): with open('ec2/boot.sh', 'r') as userdata: return userdata.read().replace("@PASSWORD@", pihole_passw) # generate a random pihole web ui password pihole_passw = ''.join( random.choice(string.ascii_lowercase) for i in range(10)) # set the password in userdata with the generated one user_data.add_commands(get_userdata()) # create the ec2 instance ec2 = aws_ec2.Instance( self, "pihole-ec2", vpc=vpc, instance_type=aws_ec2.InstanceType('t3a.nano'), machine_image=aws_ec2.AmazonLinuxImage( generation=aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), vpc_subnets={'subnet_type': aws_ec2.SubnetType.PUBLIC}, key_name="workbook", user_data=aws_ec2.UserData.custom(get_userdata())) # tag the ec2 instance core.Tag.add(ec2, "stack", "pihole") # set the password as an ec2 instance tag core.Tag.add(ec2, "PiholePassword", pihole_passw) # add the pihole admin panel password as an ec2 instance tag # this way it can be randomly generated and doesn't require you to ssh into the instance to retrieve # create security group with inbound access from the internet sg = aws_ec2.SecurityGroup(self, "allow_dns_http_world", description='Allow ssh from world', vpc=vpc) # add tcp/22 security group rule sg.add_ingress_rule(aws_ec2.Peer.ipv4(whitelist_ip), aws_ec2.Port.tcp(22)) # add tcp/80 security group rule sg.add_ingress_rule(aws_ec2.Peer.ipv4(whitelist_ip), aws_ec2.Port.tcp(80)) # add udp/53 security group rule sg.add_ingress_rule(aws_ec2.Peer.ipv4(whitelist_ip), aws_ec2.Port.udp(53)) # attach security group to instance ec2.add_security_group(sg) # create elastic ip eip = aws_ec2.CfnEIP(self, 'elastic-ip', domain='vpc', instance_id=ec2.instance_id) ''' # get the elastic ip address of the ec2 instance client = boto3.client('ec2') addr_dict = client.describe_addresses(AllocationIds = [eip.attr_allocation_id]) elastic_ip = addr_dict['Addresses'][0]['PublicIp'] # print the elastic ip allocation id core.CfnOutput( self, "elastic_allocation_id", value = eip.attr_allocation_id ) ''' # print the pihole web ui password core.CfnOutput(self, "pihole_web_ui_password", value=pihole_passw) # print the whitelisted ip in the ec2 security group core.CfnOutput(self, "whitelisted_ip", value=whitelist_ip) '''
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) current_directory = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) allowed_values = yaml.load(open( os.path.join(current_directory, "..", "..", "allowed_values.yaml")), Loader=yaml.SafeLoader) ami_mapping = {"AMI": {"OEJITSI": AMI_NAME}} for region in generated_ami_ids.keys(): ami_mapping[region] = {"OEJITSI": generated_ami_ids[region]} aws_ami_region_map = core.CfnMapping(self, "AWSAMIRegionMap", mapping=ami_mapping) # utility function to parse the unique id from the stack id for # shorter resource names using cloudformation functions def append_stack_uuid(name): return core.Fn.join("-", [ name, core.Fn.select( 0, core.Fn.split( "-", core.Fn.select(2, core.Fn.split( "/", core.Aws.STACK_ID)))) ]) # # PARAMETERS # cidr_block_param = core.CfnParameter( self, "IngressCidrBlock", allowed_pattern="((\d{1,3})\.){3}\d{1,3}/\d{1,2}", default="0.0.0.0/0", description= "Required: A CIDR block to restrict access to the Jitsi application. Leave as 0.0.0.0/0 to allow public access from internet." ) ec2_instance_type_param = core.CfnParameter( self, "InstanceType", allowed_values=allowed_values["allowed_instance_types"], default="t3.xlarge", description= "Required: The EC2 instance type for the application Auto Scaling Group." ) jitsi_hostname_param = core.CfnParameter( self, "JitsiHostname", description= "Required: The hostname to access Jitsi. E.G. 'jitsi.internal.mycompany.com'" ) jitsi_interface_app_name_param = core.CfnParameter( self, "JitsiInterfaceAppName", default="Jitsi Meet", description= "Optional: Customize the app name on the Jitsi interface.") jitsi_interface_default_remote_display_name_param = core.CfnParameter( self, "JitsiInterfaceDefaultRemoteDisplayName", default="Fellow Jitster", description= "Optional: Customize the default display name for Jitsi users.") jitsi_interface_native_app_name_param = core.CfnParameter( self, "JitsiInterfaceNativeAppName", default="Jitsi Meet", description= "Optional: Customize the native app name on the Jitsi interface.") jitsi_interface_show_brand_watermark_param = core.CfnParameter( self, "JitsiInterfaceShowBrandWatermark", allowed_values=["true", "false"], default="true", description= "Optional: Display the watermark logo image in the upper left corner." ) jitsi_interface_show_watermark_for_guests_param = core.CfnParameter( self, "JitsiInterfaceShowWatermarkForGuests", allowed_values=["true", "false"], default="true", description= "Optional: Display the watermark logo image in the upper left corner for guest users. This can be set to override the general setting behavior for guest users." ) jitsi_interface_brand_watermark_param = core.CfnParameter( self, "JitsiInterfaceBrandWatermark", default="", description= "Optional: Provide a URL to a PNG image to be used as the brand watermark logo image in the upper right corner. File should be publically available for download." ) jitsi_interface_brand_watermark_link_param = core.CfnParameter( self, "JitsiInterfaceBrandWatermarkLink", default="http://jitsi.org", description= "Optional: Provide a link destination for the brand watermark logo image in the upper right corner." ) jitsi_interface_watermark_param = core.CfnParameter( self, "JitsiInterfaceWatermark", default="", description= "Optional: Provide a URL to a PNG image to be used as the watermark logo image in the upper left corner. File should be publically available for download." ) jitsi_interface_watermark_link_param = core.CfnParameter( self, "JitsiInterfaceWatermarkLink", default="http://jitsi.org", description= "Optional: Provide a link destination for the Jitsi watermark logo image in the upper left corner." ) route_53_hosted_zone_name_param = core.CfnParameter( self, "Route53HostedZoneName", description= "Required: Route 53 Hosted Zone name in which a DNS record will be created by this template. Must already exist and be the domain part of the Jitsi Hostname parameter, without trailing dot. E.G. 'internal.mycompany.com'" ) notification_email_param = core.CfnParameter( self, "NotificationEmail", default="", description= "Optional: Specify an email address to get emails about deploys, Let's Encrypt, and other system events." ) # # CONDITIONS # notification_email_exists_condition = core.CfnCondition( self, "NotificationEmailExistsCondition", expression=core.Fn.condition_not( core.Fn.condition_equals(notification_email_param.value, ""))) # # RESOURCES # # vpc vpc = Vpc(self, "Vpc") # sns sns_notification_topic = aws_sns.CfnTopic( self, "NotificationTopic", topic_name="{}-notifications".format(core.Aws.STACK_NAME)) sns_notification_subscription = aws_sns.CfnSubscription( self, "NotificationSubscription", protocol="email", topic_arn=sns_notification_topic.ref, endpoint=notification_email_param.value_as_string) sns_notification_subscription.cfn_options.condition = notification_email_exists_condition iam_notification_publish_policy = aws_iam.PolicyDocument(statements=[ aws_iam.PolicyStatement(effect=aws_iam.Effect.ALLOW, actions=["sns:Publish"], resources=[sns_notification_topic.ref]) ]) # cloudwatch app_log_group = aws_logs.CfnLogGroup( self, "JitsiAppLogGroup", retention_in_days=TWO_YEARS_IN_DAYS) app_log_group.cfn_options.update_replace_policy = core.CfnDeletionPolicy.RETAIN app_log_group.cfn_options.deletion_policy = core.CfnDeletionPolicy.RETAIN system_log_group = aws_logs.CfnLogGroup( self, "JitsiSystemLogGroup", retention_in_days=TWO_YEARS_IN_DAYS) system_log_group.cfn_options.update_replace_policy = core.CfnDeletionPolicy.RETAIN system_log_group.cfn_options.deletion_policy = core.CfnDeletionPolicy.RETAIN # iam iam_jitsi_instance_role = aws_iam.CfnRole( self, "JitsiInstanceRole", assume_role_policy_document=aws_iam.PolicyDocument(statements=[ aws_iam.PolicyStatement( effect=aws_iam.Effect.ALLOW, actions=["sts:AssumeRole"], principals=[aws_iam.ServicePrincipal("ec2.amazonaws.com")]) ]), policies=[ aws_iam.CfnRole.PolicyProperty( policy_document=aws_iam.PolicyDocument(statements=[ aws_iam.PolicyStatement( effect=aws_iam.Effect.ALLOW, actions=[ "logs:CreateLogStream", "logs:DescribeLogStreams", "logs:PutLogEvents" ], resources=[ app_log_group.attr_arn, system_log_group.attr_arn ]) ]), policy_name="AllowStreamLogsToCloudWatch"), aws_iam.CfnRole.PolicyProperty( policy_document=aws_iam.PolicyDocument(statements=[ aws_iam.PolicyStatement( effect=aws_iam.Effect.ALLOW, actions=[ "ec2:AssociateAddress", "ec2:DescribeVolumes", "ec2:DescribeTags", "cloudwatch:GetMetricStatistics", "cloudwatch:ListMetrics", "cloudwatch:PutMetricData" ], resources=["*"]) ]), policy_name="AllowStreamMetricsToCloudWatch"), aws_iam.CfnRole.PolicyProperty( policy_document=aws_iam.PolicyDocument(statements=[ aws_iam.PolicyStatement( effect=aws_iam.Effect.ALLOW, actions=["autoscaling:Describe*"], resources=["*"]) ]), policy_name="AllowDescribeAutoScaling"), ], managed_policy_arns=[ "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" ]) # ec2 jitsi_sg = aws_ec2.CfnSecurityGroup( self, "JitsiSg", group_description="Jitsi security group", vpc_id=vpc.id()) eip = aws_ec2.CfnEIP(self, "Eip", domain="vpc") core.Tags.of(eip).add("Name", "{}/Eip".format(core.Aws.STACK_NAME)) ec2_instance_profile = aws_iam.CfnInstanceProfile( self, "JitsiInstanceProfile", roles=[iam_jitsi_instance_role.ref]) with open("jitsi/jitsi_launch_config_user_data.sh") as f: jitsi_launch_config_user_data = f.read() ec2_launch_config = aws_autoscaling.CfnLaunchConfiguration( self, "JitsiLaunchConfig", image_id=core.Fn.find_in_map("AWSAMIRegionMap", core.Aws.REGION, "OEJITSI"), instance_type=ec2_instance_type_param.value_as_string, iam_instance_profile=ec2_instance_profile.ref, security_groups=[jitsi_sg.ref], user_data=(core.Fn.base64( core.Fn.sub( jitsi_launch_config_user_data, { "JitsiHostname": jitsi_hostname_param.value_as_string, "JitsiPublicIP": eip.ref, "LetsEncryptCertificateEmail": notification_email_param.value_as_string })))) # autoscaling asg = aws_autoscaling.CfnAutoScalingGroup( self, "JitsiAsg", launch_configuration_name=ec2_launch_config.ref, desired_capacity="1", max_size="1", min_size="1", vpc_zone_identifier=vpc.public_subnet_ids()) asg.cfn_options.creation_policy = core.CfnCreationPolicy( resource_signal=core.CfnResourceSignal(count=1, timeout="PT15M")) asg.cfn_options.update_policy = core.CfnUpdatePolicy( auto_scaling_rolling_update=core.CfnAutoScalingRollingUpdate( max_batch_size=1, min_instances_in_service=0, pause_time="PT15M", wait_on_resource_signals=True)) core.Tags.of(asg).add("Name", "{}/JitsiAsg".format(core.Aws.STACK_NAME)) jitsi_http_ingress = aws_ec2.CfnSecurityGroupIngress( self, "JitsiHttpSgIngress", cidr_ip=cidr_block_param.value_as_string, from_port=80, group_id=jitsi_sg.ref, ip_protocol="tcp", to_port=80) jitsi_https_ingress = aws_ec2.CfnSecurityGroupIngress( self, "JitsiHttpsSgIngress", cidr_ip=cidr_block_param.value_as_string, from_port=443, group_id=jitsi_sg.ref, ip_protocol="tcp", to_port=443) jitsi_fallback_network_audio_video_ingress = aws_ec2.CfnSecurityGroupIngress( self, "JitsiFallbackNetworkAudioVideoSgIngress", cidr_ip=cidr_block_param.value_as_string, from_port=4443, group_id=jitsi_sg.ref, ip_protocol="tcp", to_port=4443) jitsi_general_network_audio_video_ingress = aws_ec2.CfnSecurityGroupIngress( self, "JitsiGeneralNetworkAudioVideoSgIngress", cidr_ip=cidr_block_param.value_as_string, from_port=10000, group_id=jitsi_sg.ref, ip_protocol="udp", to_port=10000) # route 53 record_set = aws_route53.CfnRecordSet( self, "RecordSet", hosted_zone_name= f"{route_53_hosted_zone_name_param.value_as_string}.", name=jitsi_hostname_param.value_as_string, resource_records=[eip.ref], type="A") # https://github.com/aws/aws-cdk/issues/8431 record_set.add_property_override("TTL", 60) # AWS::CloudFormation::Interface self.template_options.metadata = { "OE::Patterns::TemplateVersion": template_version, "AWS::CloudFormation::Interface": { "ParameterGroups": [{ "Label": { "default": "Infrastructure Config" }, "Parameters": [ jitsi_hostname_param.logical_id, route_53_hosted_zone_name_param.logical_id, cidr_block_param.logical_id, ec2_instance_type_param.logical_id, notification_email_param.logical_id ] }, { "Label": { "default": "Jitsi Config" }, "Parameters": [ jitsi_interface_app_name_param.logical_id, jitsi_interface_default_remote_display_name_param. logical_id, jitsi_interface_native_app_name_param.logical_id, jitsi_interface_show_brand_watermark_param.logical_id, jitsi_interface_show_watermark_for_guests_param. logical_id, jitsi_interface_brand_watermark_param.logical_id, jitsi_interface_brand_watermark_link_param.logical_id, jitsi_interface_watermark_param.logical_id, jitsi_interface_watermark_link_param.logical_id, ] }, *vpc.metadata_parameter_group()], "ParameterLabels": { cidr_block_param.logical_id: { "default": "Ingress CIDR Block" }, ec2_instance_type_param.logical_id: { "default": "EC2 instance type" }, jitsi_hostname_param.logical_id: { "default": "Jitsi Hostname" }, jitsi_interface_app_name_param.logical_id: { "default": "Jitsi Interface App Name" }, jitsi_interface_default_remote_display_name_param.logical_id: { "default": "Jitsi Interface Default Remote Display Name" }, jitsi_interface_native_app_name_param.logical_id: { "default": "Jitsi Interface Native App Name" }, jitsi_interface_show_brand_watermark_param.logical_id: { "default": "Jitsi Interface Show Watermark" }, jitsi_interface_show_watermark_for_guests_param.logical_id: { "default": "Jitsi Interface Show Watermark For Guests" }, jitsi_interface_brand_watermark_param.logical_id: { "default": "Jitsi Interface Watermark" }, jitsi_interface_brand_watermark_link_param.logical_id: { "default": "Jitsi Interface Watermark Link" }, jitsi_interface_watermark_param.logical_id: { "default": "Jitsi Interface Watermark" }, jitsi_interface_watermark_link_param.logical_id: { "default": "Jitsi Interface Watermark Link" }, notification_email_param.logical_id: { "default": "Notification Email" }, route_53_hosted_zone_name_param.logical_id: { "default": "AWS Route 53 Hosted Zone Name" }, **vpc.metadata_parameter_labels() } } } # # OUTPUTS # eip_output = core.CfnOutput( self, "EipOutput", description= "The Elastic IP address dynamically mapped to the autoscaling group instance.", value=eip.ref) endpoint_output = core.CfnOutput( self, "JitsiUrl", description="The URL for the Jitsi instance.", value=core.Fn.join( "", ["https://", jitsi_hostname_param.value_as_string]))