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 __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, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Lets create couple of instances to test vpc = ec2.Vpc(self, "abacVPC", cidr="10.13.0.0/21", max_azs=2, nat_gateways=0, subnet_configuration=[ ec2.SubnetConfiguration( name="pubSubnet", cidr_mask=24, subnet_type=ec2.SubnetType.PUBLIC) ]) # Tag all VPC Resources core.Tag.add(vpc, key="Owner", value="KonStone", include_resource_types=[]) core.Tag.add(vpc, key="teamName", value="teamUnicorn", include_resource_types=[]) # We are using the latest AMAZON LINUX AMI ami_id = ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration. AMAZON_LINUX_2).get_image(self).image_id red_web_inst = ec2.CfnInstance( self, "redWebInstance01", image_id=ami_id, instance_type="t2.micro", monitoring=False, tags=[{ "key": "teamName", "value": "teamUnicorn" }, { "key": "projectName", "value": "projectRed" }, { "key": "Name", "value": "projectRed-Web" }], network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, # "groupSet": [web_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 )
def createInstance(self, id, image_id, instance_type, subnet_id, security_group_ids=[]): instance = ec2.CfnInstance(scope=self, id=id, image_id=image_id, instance_type=instance_type, subnet_id=subnet_id, security_group_ids=security_group_ids) return instance
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) cidr = '10.0.0.0/16' vpc = ec2.Vpc( self, "TheVPC", cidr=cidr, max_azs=3, subnet_configuration=[ ec2.SubnetConfiguration(subnet_type=ec2.SubnetType.PUBLIC, name="Ingress", cidr_mask=24), ec2.SubnetConfiguration(cidr_mask=24, name="Application", subnet_type=ec2.SubnetType.PRIVATE), ec2.SubnetConfiguration(cidr_mask=28, name="Database", subnet_type=ec2.SubnetType.ISOLATED, reserved=True) ]) security_group = ec2.SecurityGroup( self, id='test-security-group', vpc=vpc, security_group_name='test-security-group') security_group.add_ingress_rule( peer=ec2.Peer.ipv4(cidr), connection=ec2.Port.tcp(22), ) image_id = ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image( self).image_id ec2.CfnInstance(self, id='test-instance', availability_zone="ap-northeast-1a", image_id=image_id, instance_type="t2.micro", key_name='test-ssh-key', security_group_ids=[security_group.security_group_id], subnet_id=vpc.private_subnets[0].subnet_id, tags=[{ "key": "Name", "value": "test-instance" }])
def __init__(self, scope: core.Construct, id: str, app_nw_stack: appNwStack, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Contexts PRJ = self.node.try_get_context("prj") AMI_ID = self.node.try_get_context("ami-id") # Amazon Linux 2 # Functions def nametag(x): return core.CfnTag( key="Name", value="{}/{}".format(PRJ, x)) # ### Resources # IAM Role ec2_statement = iam.PolicyStatement() ec2_statement.add_actions("sts:AssumeRole") ec2_statement.add_service_principal(service="ec2.amazonaws.com") ec2_document = iam.PolicyDocument( statements=[ec2_statement] ) iam_role = iam.CfnRole( self, "iamRoleForEc2", role_name="{}-ec2-role".format(PRJ), description="{}-ec2-role".format(PRJ), assume_role_policy_document=ec2_document.to_json(), managed_policy_arns=[ "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM" ] ) ec2_instance_profile = iam.CfnInstanceProfile( self, "ec2InstanceProfile", roles=[iam_role.ref], instance_profile_name="{}-ec2-instance-profile".format(PRJ) ) # Security Group sg = ec2.CfnSecurityGroup( self, "sg", group_description="sg for ec2 instance({})".format(PRJ), vpc_id=app_nw_stack.vpc.ref, security_group_ingress=[] ) # Instance ec2.CfnInstance( self, "instance", iam_instance_profile=ec2_instance_profile.ref, image_id=AMI_ID, instance_type="t3.micro", security_group_ids=[sg.ref], subnet_id=app_nw_stack.ec2_subnet.ref, tags=[nametag("instance")] )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) ec2b = boto3.client('ec2', region_name=kwargs['env']['region']) vpc_response = ec2b.describe_vpcs( Filters=[{ 'Name': 'tag:Name', 'Values': [kwargs['env']['vpc']] }]) azs_response = ec2b.describe_availability_zones( Filters=[{ 'Name': 'region-name', 'Values': [kwargs['env']['region']] }]) vpc_id = vpc_response['Vpcs'][0]['VpcId'] vpc = ec2.Vpc.from_vpc_attributes( self, f'{id}-vpc', availability_zones=[ x['ZoneName'] for x in azs_response['AvailabilityZones'] ], vpc_id=vpc_id) subnets = [] subnets_response = ec2b.describe_subnets(Filters=[{ 'Name': 'tag:Tier', 'Values': ['public'] }, { 'Name': 'vpc-id', 'Values': [vpc_id] }]) for s in subnets_response['Subnets']: subnets.append(s['SubnetId']) self.subnet_id = subnets[random.randint(0, len(subnets) - 1)] sg = ec2.SecurityGroup(self, f'{id}-sg', vpc=vpc) sg.add_ingress_rule(ec2.Peer.ipv4(kwargs['env']['cidr']), ec2.Port.tcp(kwargs['env']['port'])) inst = ec2.CfnInstance(self, f'{id}-inst', image_id=kwargs['env']['ami'], instance_type=kwargs['env']['inst_type'], security_group_ids=[sg.security_group_id], subnet_id=self.subnet_id)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__( scope, id, **kwargs, description= "A test on sending data to a WaitCondition. Once created to use: Send data output: cfn-signal -d <data> <wait_handle>" ) c = con.WaitConditionWithDataConstruct(self, "Blah", count=2, timeout="300") instance = ec2.CfnInstance( self, "MainInstance", image_id="ami-f173cc91", key_name="testing", instance_type="t2.micro", subnet_id=core.CfnParameter( self, "SubnetId", type="AWS::EC2::Subnet::Id").to_string(), user_data=core.Fn.base64( core.Fn.sub('''#!/bin/bash /opt/aws/bin/cfn-init -s ${{AWS::StackName}} -r MyEC2Instance --region ${{AWS::Region}} /opt/aws/bin/cfn-signal -d "tempdata" {handle}'''.format( handle=c.getWaitHandle().logical_id)))) core.CfnOutput( self, "Outputs", value=c.getWaitCondition().get_att("Data").to_string(), description= "Data for Cloudformation Handle using cfn-signal with data that is outputted into the Outputs" ) c.getWaitCondition().add_depends_on(instance)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) cidr = '10.0.0.0/16' vpc = ec2.Vpc(self, id='cdk-test-vpc', cidr=cidr, max_azs=1) security_group = ec2.SecurityGroup( self, id='cdk-sg', vpc=vpc, security_group_name='cdk-sg', ) # what is peer security_group.add_ingress_rule( peer=ec2.Peer.ipv4(cidr), connection=ec2.Port.tcp(22), ) security_group.add_ingress_rule( peer=ec2.Peer.ipv4('0.0.0.0/0'), connection=ec2.Port.tcp(80), ) image_id = ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image( self).image_id ec2.CfnInstance(self, id='cdk-instancd', availability_zone="ap-northeast-1a", image_id=image_id, instance_type="t2.small", security_group_ids=[security_group.security_group_id], subnet_id=vpc.private_subnets[0].subnet_id, tags=[{ "key": "Name", "value": "cdk-instance" }])
def __init__(self, scope: core.Construct, id: str, props: dict, **kwargs): super().__init__(scope, id, **kwargs) print(kwargs) print(props) ec2b = boto3.client('ec2', region_name=kwargs['env']['region']) vpc = ec2.Vpc.from_lookup(self, f'{id}-vpc', vpc_name=props['vpc']) if vpc is None: print("VPC lookup error!!!!!!!!!!!!!!!!!!!!!!") subnets = [] subnets_response = ec2b.describe_subnets( Filters=[{ 'Name': 'tag:Tier', 'Values': ['public'] }, { 'Name': 'vpc-id', 'Values': [vpc.vpc_id] }]) for s in subnets_response['Subnets']: subnets.append(s['SubnetId']) self.subnet_id = subnets[random.randint(0, len(subnets) - 1)] sg = ec2.SecurityGroup(self, f'{id}-sg', vpc=vpc) sg.add_ingress_rule(ec2.Peer.ipv4(props['cidr']), ec2.Port.tcp(props['port'])) inst = ec2.CfnInstance(self, f'{id}-inst', image_id=props['ami'], instance_type=props['inst_type'], security_group_ids=[sg.security_group_id], subnet_id=self.subnet_id)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) prefix = "test"" cidr = "10.100.0.0/16" # def name(s): return "{0}/{1}".format(prefix, s) def name(s): return "{0} {1}".format(prefix, s) # VPC self.vpc = ec2.CfnVPC( self, "vpc", cidr_block=cidr, enable_dns_hostnames=True, enable_dns_support=True, tags=[ core.CfnTag(key="Name", value=prefix+" VPC") ] ) # InternetGateway igw = ec2.CfnInternetGateway( self, "igw", tags=[ core.CfnTag(key="Name", value=prefix+" IGW") ] ) igw_attachment = ec2.CfnVPCGatewayAttachment( self, "igw_attachment", vpc_id=self.vpc.ref, internet_gateway_id=igw.ref ) dhcpoptions = ec2.CfnDHCPOptions( self, "dhcpoptions", domain_name="ec2.internal "+prefix, domain_name_servers=["AmazonProvidedDNS"], tags=[ core.CfnTag(key="Name", value=prefix) ] ) dhcpoptionsassociation = ec2.CfnVPCDHCPOptionsAssociation( self, "dhcpoptionsassociation", dhcp_options_id=dhcpoptions.ref, vpc_id=self.vpc.ref ) # PrivateSubnetA # private_subnet_a = ec2.CfnSubnet( # self, "private_a", # vpc_id=vpc.ref, # cidr_block="192.168.0.0/24", # availability_zone="ap-northeast-1a", # tags=[ # core.CfnTag(key="Name", value=name("private_a")) # ] # ) # PrivateSubnetC # private_subnet_c = ec2.CfnSubnet( # self, "private_c", # vpc_id=vpc.ref, # cidr_block="192.168.1.0/24", # availability_zone="ap-northeast-1c", # tags=[ # core.CfnTag(key="Name", value=name("private_c")) # ] # ) # PublicSubnetA self.public_subnet_a = ec2.CfnSubnet( self, "public_a", vpc_id=self.vpc.ref, cidr_block="192.168.0.0/20", # availability_zone="ap-northeast-1a", availability_zone="us-east-1a", tags=[ core.CfnTag(key="Name", value=prefix+" public_a") ] ) # PublicSubnetC self.public_subnet_c = ec2.CfnSubnet( self, "public_c", vpc_id=self.vpc.ref, cidr_block="192.168.16.0/20", availability_zone="us-east-1c", tags=[ core.CfnTag(key="Name", value=prefix+" public_c") ] ) self.public_subnet_d = ec2.CfnSubnet( self, "public_d", vpc_id=self.vpc.ref, cidr_block="192.168.32.0/20", availability_zone="us-east-1d", tags=[ core.CfnTag(key="Name", value=prefix+" public_d") ] ) # EIP1 (for NATGW) # eip1 = ec2.CfnEIP( # self, "eip1", # domain="vpc", # ) # eip1.add_depends_on(igw_attachment) # EIP2 (for NATGW) # eip2 = ec2.CfnEIP( # self, "eip2", # domain="vpc", # ) # eip2.add_depends_on(igw_attachment) # NatGatewayA # natgw_a = ec2.CfnNatGateway( # self, "natgw_a", # allocation_id=eip1.attr_allocation_id, # subnet_id=self.public_subnet_a.ref, # tags=[ # core.CfnTag(key="Name", value=name("natgw_a")) # ] # ) # NatGatewayC # natgw_c = ec2.CfnNatGateway( # self, "natgw_c", # allocation_id=eip2.attr_allocation_id, # subnet_id=public_subnet_c.ref, # tags=[ # core.CfnTag(key="Name", value=name("natgw_c")) # ] # ) # RouteTable of PrivateSubnetA # rtb_private_a = ec2.CfnRouteTable( # self, "rtb_private_a", # vpc_id=vpc.ref, # tags=[ # core.CfnTag(key="Name", value=name("rtb_private_a")) # ] # ) # ec2.CfnSubnetRouteTableAssociation( # self, "rtb_private_a_association", # route_table_id=rtb_private_a.ref, # subnet_id=private_subnet_a.ref # ) # ec2.CfnRoute( # self, "route_private_a", # route_table_id=rtb_private_a.ref, # destination_cidr_block="0.0.0.0/0", # nat_gateway_id=natgw_a.ref # ) # RouteTable of PrivateSubnetC # rtb_private_c = ec2.CfnRouteTable( # self, "rtb_private_c", # vpc_id=vpc.ref, # tags=[ # core.CfnTag(key="Name", value=name("rtb_private_c")) # ] # ) # ec2.CfnSubnetRouteTableAssociation( # self, "rtb_private_c_association", # route_table_id=rtb_private_c.ref, # subnet_id=private_subnet_c.ref # ) # ec2.CfnRoute( # self, "route_private_c", # route_table_id=rtb_private_c.ref, # destination_cidr_block="0.0.0.0/0", # nat_gateway_id=natgw_c.ref # ) # RouteTable of PublicSubnetA self.rtb_public_a = ec2.CfnRouteTable( self, "rtb_public_a", vpc_id=self.vpc.ref, tags=[ core.CfnTag(key="Name", value=prefix+"rtb_public_a") ] ) ec2.CfnSubnetRouteTableAssociation( self, "rtb_public_a_association", route_table_id=self.rtb_public_a.ref, subnet_id=self.public_subnet_a.ref ) ec2.CfnSubnetRouteTableAssociation( self, "rtb_public_c_association", route_table_id=self.rtb_public_a.ref, subnet_id=self.public_subnet_c.ref ) ec2.CfnSubnetRouteTableAssociation( self, "rtb_public_d_association", route_table_id=self.rtb_public_a.ref, subnet_id=self.public_subnet_d.ref ) ec2.CfnRoute( self, "route_public_a", route_table_id=self.rtb_public_a.ref, destination_cidr_block="0.0.0.0/0", gateway_id=igw.ref ) # RouteTable of PublicSubnetC # rtb_public_c = ec2.CfnRouteTable( # self, "rtb_public_c", # vpc_id=vpc.ref, # tags=[ # core.CfnTag(key="Name", value=name("rtb_public_c")) # ] # ) # ec2.CfnSubnetRouteTableAssociation( # self, "rtb_public_c_association", # route_table_id=rtb_public_c.ref, # subnet_id=public_subnet_c.ref # ) # ec2.CfnRoute( # self, "route_public_c", # route_table_id=rtb_public_c.ref, # destination_cidr_block="0.0.0.0/0", # gateway_id=igw.ref # ) ami_id = ec2.AmazonLinuxImage(generation = ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image(self).image_id security_group = ec2.SecurityGroup( self, id='InstanceSecurityGroupwww', vpc=self.vpc, security_group_name='stg-'+prefix+'www' ) security_group.add_ingress_rule( peer=ec2.Peer.ipv4('0.0.0.0/0'), connection=ec2.Port.tcp(22), ) security_group.add_ingress_rule( peer=ec2.Peer.ipv4('0.0.0.0/0'), connection=ec2.Port.tcp(80), ) EC2InstanceStgWeb = ec2.CfnInstance(self, "EC2InstanceStgWeb", image_id = ami_id, instance_type = "t3a.micro", monitoring = False, key_name = "stg-intrinio-www01", security_group_ids=[security_group.security_group_id], block_device_mappings = [{ "deviceName": "/dev/xvda", "ebs": { "volumeSize": 10, # "volumeType": "io1", # "iops": 150, # "deleteOnTermination": True } } ], tags = [ { "key": "Name", "value": 'stg'+prefix+'www01' } ], network_interfaces = [{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": self.public_subnet_a.ref, # "groupSet": [web_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 ) # RdsSecurityGroup RdsStgSecurityGroup = ec2.CfnSecurityGroup(self, "RdsStgSecurityGroup", group_name = 'stg-'+prefix+'db01', group_description = 'stg-'+prefix+'db01', vpc_id = self.vpc.ref, security_group_ingress = [ { "ipProtocol" : "tcp", "fromPort" : 3306, "toPort" : 3306, "cidrIp" : "0.0.0.0/0" } ], security_group_egress = [ { "ipProtocol" : "tcp", "fromPort" : 0, "toPort" : 65535, "cidrIp" : "0.0.0.0/0" } ], ) # MyDBSubnetGroup rds_subnet_group = rds.CfnDBSubnetGroup(self, "DBSubnetGroup", db_subnet_group_description = "DBSubnetGroup", subnet_ids = [ self.public_subnet_a.ref, self.public_subnet_c.ref, self.public_subnet_d.ref ] ) DBParameterGroupStg = rds.CfnDBParameterGroup(self, "DBParameterGroupStg", description = "", family = "", parameters = [{'character_set_client': utf8,}] ) rds_params = { 'db_instance_identifier': "stg-test-db01", 'engine': "mysql", 'engine_version': '5.6.39', 'db_instance_class': 'db.t3.micro', 'allocated_storage': '5', 'storage_type': 'gp2', 'db_name': "test", 'master_username': "******", 'master_user_password': "******", 'db_subnet_group_name' : rds_subnet_group.ref, 'publicly_accessible': False, 'multi_az': False, 'preferred_backup_window': "18:00-18:30", 'PreferredMaintenanceWindow': "sat:19:00-sat:19:30", 'auto_minor_version_upgrade': False, 'db_parameter_group_name': DBParameterGroupStg, 'vpc_security_groups': [RdsStgSecurityGroup.ref], 'copy_tags_to_snapshot': True, 'backup_retention_period': 7, 'enable_performance_insights': True, 'delete_automated_backups': True, 'deletion_protection': False, 'availability_zone': self.public_subnet_a.ref, # 'storage_encrypted': False, } self.rds = rds.CfnDBInstance(self, 'staff-rds', **rds_params) core.CfnOutput(self, "Output", value=self.vpc.ref)
def __init__(self, app: cdk.App, id: str, vpc: ec2.Vpc, servicedomain: str, **kwargs) -> None: super().__init__(app, id) cluster = ecs.Cluster(self, id, vpc=vpc) cluster.add_default_cloud_map_namespace( name=servicedomain, type=ecs.NamespaceType.PrivateDns) self._cluster = cluster ecssg = ec2.SecurityGroup(self, 'ECSServiceSecurityGroup', vpc=vpc) ecssg.add_ingress_rule(peer=ec2.CidrIPv4(vpc.vpc_cidr_block), connection=ec2.TcpAllPorts()) self._clustersg = ecssg # Bastion host stuff ------------------------------------------------------------------------------------- # BastionInstanceRole pd = pu.PolicyUtils.createpolicyfromfile( './appmeshdemo/policydocs/appmesh.json') bir = iam.Role( self, 'BastionInstanceRole', assumed_by=iam.ServicePrincipal('ec2'), inline_policies={'appmesh': pd}, managed_policy_arns=[ 'arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM' ]) bip = iam.CfnInstanceProfile(self, 'BastionInstanceProfile', roles=[bir.role_name]) # Bastion EC2 instance bsg = ec2.SecurityGroup(self, 'BastionSG', vpc=vpc) bsg.add_ingress_rule(peer=ec2.AnyIPv4(), connection=ec2.TcpAllPorts()) ni = ec2.CfnNetworkInterfaceProps() ni['associatePublicIpAddress'] = True ni['deviceIndex'] = '0' ni['groupSet'] = [bsg.security_group_name] ni['subnetId'] = vpc.public_subnets[0].subnet_id bhi = ec2.CfnInstance( self, 'BastionInstance', instance_type='t2.micro', iam_instance_profile=bip.instance_profile_name, image_id=ec2.AmazonLinuxImage().get_image(self).image_id, network_interfaces=[ni]) # Load-Balancer stuff ------------------------------------------------------------------------------------ plbsg = ec2.SecurityGroup(self, 'PublicLoadBalancerSG', vpc=vpc) plbsg.add_ingress_rule(peer=ec2.AnyIPv4(), connection=ec2.TcpPortRange(0, 65535)) plb = elbv2.ApplicationLoadBalancer(self, 'PublicLoadBalancer', internet_facing=True, load_balancer_name='appmeshdemo', security_group=plbsg, vpc=vpc, idle_timeout_secs=30) self._publoadbal = plb healthchk = elbv2.HealthCheck() healthchk['intervalSecs'] = 6 healthchk['healthyThresholdCount'] = 2 healthchk['unhealthyThresholdCount'] = 2 dtg = elbv2.ApplicationTargetGroup( self, 'DummyTargetGroupPublic', vpc=vpc, port=80, protocol=elbv2.ApplicationProtocol.Http, health_check=healthchk, target_group_name='appmeshdemo-drop-1') plbl = elbv2.ApplicationListener( self, 'PublicLoadBalancerListener', load_balancer=plb, port=80, protocol=elbv2.ApplicationProtocol.Http, default_target_groups=[dtg]) cdk.CfnOutput(self, id='External URL', value='http://' + plb.load_balancer_dns_name)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) az1 = core.Fn.select(0, core.Fn.get_azs(region=core.Aws.REGION)) az2 = core.Fn.select(1, core.Fn.get_azs(region=core.Aws.REGION)) ########## # VPC ########## # VPC vpc = ec2.Vpc(self, "vpc", cidr="10.0.0.0/16", subnet_configuration=[]) # Internet gateway internet_gateway = ec2.CfnInternetGateway(self, "internet-gateway") ec2.CfnVPCGatewayAttachment(self, "internet_gateway_attatchment", vpc_id=vpc.vpc_id, internet_gateway_id=internet_gateway.ref) # Public Subnet az1 public_subnet_az1 = ec2.PublicSubnet(self, "subnet-public-1a", availability_zone=az1, cidr_block="10.0.0.0/24", vpc_id=vpc.vpc_id, map_public_ip_on_launch=True) public_subnet_az1.add_route("internet-gateway-route", router_id=internet_gateway.ref, router_type=ec2.RouterType.GATEWAY) # Public Subnet az2 public_subnet_az2 = ec2.PublicSubnet(self, "subnet-public-1c", availability_zone=az2, cidr_block="10.0.1.0/24", vpc_id=vpc.vpc_id, map_public_ip_on_launch=True) public_subnet_az2.add_route("internet-gateway-route", router_id=internet_gateway.ref, router_type=ec2.RouterType.GATEWAY) # Private Subnet az1 private_subnet_az1 = ec2.PrivateSubnet(self, "subnet-private-1a", availability_zone=az1, cidr_block="10.0.2.0/24", vpc_id=vpc.vpc_id) # Private Subnet az2 private_subnet_az2 = ec2.PrivateSubnet(self, "subnet-private-1c", availability_zone=az2, cidr_block="10.0.3.0/24", vpc_id=vpc.vpc_id) ########## # EC2 ########## # # EC2 Security Group ec2_security_group = ec2.SecurityGroup(self, "ec2-security-group", vpc=vpc) # ec2_security_group.add_ingress_rule(peer=ec2.Peer.any_ipv4(),connection=ec2.Port.tcp(80)) # User Data user_data = ec2.UserData.for_linux() user_data.add_commands( "yum -y update", "amazon-linux-extras install php7.2 -y", "yum -y install mysql httpd php-mbstring php-xml", "wget http://ja.wordpress.org/latest-ja.tar.gz -P /tmp/", "tar zxvf /tmp/latest-ja.tar.gz -C /tmp", "cp -r /tmp/wordpress/* /var/www/html/", "chown apache:apache -R /var/www/html", "systemctl enable httpd.service", "systemctl start httpd.service") # EC2 Instance instance_az1 = ec2.CfnInstance( self, "wordpress-instance-az1", subnet_id=public_subnet_az1.subnet_id, image_id=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image( self).image_id, instance_type=ec2.InstanceType.of( instance_class=ec2.InstanceClass.BURSTABLE3, instance_size=ec2.InstanceSize.MICRO).to_string(), security_group_ids=[ec2_security_group.security_group_id], user_data=core.Fn.base64(user_data.render())) core.CfnOutput(self, "EC2 PublicDnsName", value=instance_az1.attr_public_dns_name) ########## # RDS ########## # RDS Security Group rds_security_group = ec2.SecurityGroup(self, "rds-security-group", vpc=vpc) ec2.CfnSecurityGroupIngress( self, "rds-security-group-ingress", group_id=rds_security_group.security_group_id, ip_protocol="tcp", from_port=3306, to_port=3306, source_security_group_id=ec2_security_group.security_group_id) # RDS Subnet Group rds_subnet_group = rds.CfnDBSubnetGroup( self, "rds-subnet-group", db_subnet_group_description="rds-subnet-group", subnet_ids=[ private_subnet_az1.subnet_id, private_subnet_az2.subnet_id ]) # RDS Instance rds_instance = rds.CfnDBInstance( self, "rds-instance", db_instance_identifier="wordpress-rds", engine=rds.DatabaseInstanceEngine.mysql( version=rds.MysqlEngineVersion.VER_8_0_20).engine_type, db_instance_class="db.t3.micro", master_username="******", master_user_password="******", db_name="wordpress", multi_az=False, vpc_security_groups=[rds_security_group.security_group_id], db_subnet_group_name=rds_subnet_group.ref, allocated_storage="20") core.CfnOutput(self, "RDS EndpointAddress", value=rds_instance.attr_endpoint_address) core.CfnOutput(self, "RDS EndpointPort", value=rds_instance.attr_endpoint_port) ########## # ALB ########## # ALB Security Group alb_security_group = ec2.SecurityGroup(self, "alb-security-group", vpc=vpc) alb_security_group.add_ingress_rule(peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(80)) # ALB Instance alb_instance = elb.ApplicationLoadBalancer( self, "alb", vpc=vpc, vpc_subnets=ec2.SubnetSelection( subnets=[public_subnet_az1, public_subnet_az2]), internet_facing=True, security_group=alb_security_group) # ALB Target Group alb_target_group = elb.ApplicationTargetGroup( self, "alb-target-group", vpc=vpc, target_type=elb.TargetType.INSTANCE, targets=[elb.InstanceTarget(instance_az1.ref)], protocol=elb.ApplicationProtocol.HTTP, port=80, health_check=elb.HealthCheck(protocol=elb.ApplicationProtocol.HTTP, path="/wp-includes/images/blank.gif")) # ALB Listener alb_listener = elb.ApplicationListener( self, "alb-listener", load_balancer=alb_instance, default_target_groups=[alb_target_group], protocol=elb.ApplicationProtocol.HTTP, port=80) core.CfnOutput(self, "ALB DNS Name", value=alb_instance.load_balancer_dns_name) # EC2 Security Group Ingress ec2.CfnSecurityGroupIngress( self, "ec2-security-group-ingress", group_id=ec2_security_group.security_group_id, ip_protocol="tcp", from_port=80, to_port=80, source_security_group_id=alb_security_group.security_group_id)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Lets generate a password for our user shiny_new_pass = random_string_generator(self, "shinyNewPasswordGenerator", Length=20) # Lets create a user projectRedUser1redRosy = iam.User(self, "projectRedUser1redRosy", user_name="redRosy", password=core.SecretValue.plain_text( shiny_new_pass.response)) teamUnicornGrp = iam.Group(self, "teamUnicornGrp", group_name="teamUnicorn") # Add Users To Group teamUnicornGrp.add_user(projectRedUser1redRosy) # blueGrp1.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("AmazonS3ReadOnlyAccess")) ############################################## # We need a custom resource to TAG IAM Users # ############################################## iamUserTaggerResp = iam_user_tagger( self, "iamTagger", message=[{ "user": projectRedUser1redRosy.user_name, "tags": [{ 'Key': 'teamName', 'Value': 'teamUnicorn' }, { 'Key': 'projectName', 'Value': 'projectRed' }] }]) # Lets Create the IAM Role # Uses belonging to this group, will be able to asume this role based on tag validation accountId = core.Aws.ACCOUNT_ID teamUnicornProjectRedRole = iam.Role( self, 'unicornTeamProjectRedRoleId', assumed_by=iam.AccountPrincipal(f"{accountId}"), role_name="teamUnicornProjectRedRole") core.Tag.add(teamUnicornProjectRedRole, key="teamName", value="teamUnicorn") core.Tag.add(teamUnicornProjectRedRole, key="projectName", value="projectRed") """ # Allow Group to Assume Role # The role will have naming convention like, <TEAM-NAME><PROJECT-NAME>ROLE For Ex: unicornTeamProjectRedRole """ grpStmt1 = iam.PolicyStatement( effect=iam.Effect.ALLOW, resources=[f"arn:aws:iam::{accountId}:role/teamUnicornProject*"], actions=["sts:AssumeRole"], conditions={ "StringEquals": { "iam:ResourceTag/teamName": "${aws:PrincipalTag/teamName}", "iam:ResourceTag/projectName": "${aws:PrincipalTag/projectName}" } }) grpStmt1.sid = "AllowGroupMembersToAssumeRoleMatchingTeamName" # Attach the policy to the group teamUnicornGrp.add_to_policy(grpStmt1) # Add Permissions to the Role roleStmt0 = iam.PolicyStatement(effect=iam.Effect.ALLOW, resources=["*"], actions=[ "ec2:Describe*", "cloudwatch:Describe*", "cloudwatch:Get*", ]) roleStmt0.sid = "AllowUserToDescribeInstances" teamUnicornProjectRedRole.add_to_policy(roleStmt0) roleStmt1a = iam.PolicyStatement( effect=iam.Effect.ALLOW, resources=[ "arn:aws:ec2:*::image/*", "arn:aws:ec2:*::snapshot/*", "arn:aws:ec2:*:*:subnet/*", "arn:aws:ec2:*:*:network-interface/*", "arn:aws:ec2:*:*:security-group/*", "arn:aws:ec2:*:*:key-pair/*" ], actions=["ec2:RunInstances"]) roleStmt1a.sid = "AllowRunInstances" teamUnicornProjectRedRole.add_to_policy(roleStmt1a) roleStmt1b = iam.PolicyStatement( effect=iam.Effect.ALLOW, resources=[ "arn:aws:ec2:*:*:instance/*", "arn:aws:ec2:*:*:volume/*", ], actions=["ec2:CreateVolume", "ec2:RunInstances"], conditions={ "StringEquals": { "aws:RequestTag/teamName": "${aws:PrincipalTag/teamName}", "aws:RequestTag/projectName": "${aws:PrincipalTag/projectName}" }, "ForAllValues:StringEquals": { "aws:TagKeys": ["teamName", "projectName"] } }) roleStmt1b.sid = "AllowRunInstancesWithRestrictionsRequiredTags" teamUnicornProjectRedRole.add_to_policy(roleStmt1b) roleStmt2 = iam.PolicyStatement( effect=iam.Effect.ALLOW, resources=[ "arn:aws:ec2:*:*:instance/*", "arn:aws:ec2:*:*:volume/*" ], actions=["ec2:CreateTags"], conditions={ "StringEquals": { "aws:RequestTag/teamName": "${aws:PrincipalTag/teamName}", "aws:RequestTag/projectName": "${aws:PrincipalTag/projectName}" }, "ForAllValues:StringEquals": { "aws:TagKeys": ["projectName", "teamName"] }, "StringEquals": { "ec2:CreateAction": "RunInstances" } }) roleStmt2.sid = "AllowCreateTagsIfRequestingValidTags" teamUnicornProjectRedRole.add_to_policy(roleStmt2) roleStmt3 = iam.PolicyStatement( effect=iam.Effect.ALLOW, resources=[ "arn:aws:ec2:*:*:instance/*", "arn:aws:ec2:*:*:volume/*" ], actions=[ "ec2:RebootInstances", "ec2:TerminateInstances", "ec2:StartInstances", "ec2:StopInstances" ], conditions={ "StringEquals": { "ec2:ResourceTag/teamName": "${aws:PrincipalTag/teamName}", "ec2:ResourceTag/projectName": "${aws:PrincipalTag/projectName}" } }) roleStmt3.sid = "AllowInstanceManagementIfTagsMatch" teamUnicornProjectRedRole.add_to_policy(roleStmt3) # Lets create couple of instances to test vpc = ec2.Vpc(self, "abacVPC", cidr="10.13.0.0/21", max_azs=2, nat_gateways=0, subnet_configuration=[ ec2.SubnetConfiguration( name="pubSubnet", cidr_mask=24, subnet_type=ec2.SubnetType.PUBLIC) ]) # Tag all VPC Resources core.Tag.add(vpc, key="Owner", value="KonStone", include_resource_types=[]) core.Tag.add(vpc, key="teamName", value="teamUnicorn", include_resource_types=[]) # We are using the latest AMAZON LINUX AMI ami_id = ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration. AMAZON_LINUX_2).get_image(self).image_id red_web_inst = ec2.CfnInstance( self, "redWebInstance01", image_id=ami_id, instance_type="t2.micro", monitoring=False, tags=[{ "key": "teamName", "value": "teamUnicorn" }, { "key": "projectName", "value": "projectRed" }, { "key": "Name", "value": "projectRed-Web" }], network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, # "groupSet": [web_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 ) # core.Tag.add(red_web_inst,key="Owner",value="KonStone",include_resource_types=[]) blue_web_inst = ec2.CfnInstance( self, "blueWebInstance01", image_id=ami_id, instance_type="t2.micro", monitoring=False, tags=[{ "key": "teamName", "value": "teamUnicorn" }, { "key": "projectName", "value": "projectBlue" }, { "key": "Name", "value": "projectBlue-Web" }], network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, # "groupSet": [web_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 ) # core.Tag.add(blue_web_inst,key="Owner",value="KonStone",include_resource_types=[]) # https://signin.aws.amazon.com/switchrole?roleName=teamUnicornProjectRedRole&account=lint3r role_login_url = ( f"https://signin.aws.amazon.com/switchrole?&account={accountId}" f"&roleName={teamUnicornProjectRedRole.role_name}") output1 = core.CfnOutput(self, "Red-Rosy-AssumeRoleUrl", value=role_login_url, description="Url to login & assume role") output2 = core.CfnOutput(self, "redRosy_user_password", value=shiny_new_pass.response, description="redRosy user password") # Publish the custom resource output output3 = core.CfnOutput( self, "IAMUserTaggerResponseMessage", description="IAM User Tagging Successful", value=iamUserTaggerResp.response, ) # Publish WebInstances ID and Tags output4 = core.CfnOutput( self, "ProjectRed-Web-Instance", description="Project Red Web Instance Publice IP", value=core.Fn.get_att(logical_name_of_resource="redWebInstance01", attribute_name="PublicIp").to_string(), ) output5 = core.CfnOutput( self, "ProjectBlue-Web-Instance", description="Project Blue Web Instance Publice IP", value=core.Fn.get_att(logical_name_of_resource="blueWebInstance01", attribute_name="PublicIp").to_string(), ) output10 = core.CfnOutput( self, "Red-Rosy-User-Login-Url", value=( f"https://{core.Aws.ACCOUNT_ID}.signin.aws.amazon.com/console" ), description=f"The URL for Rosy to Login")
def __init__(self, scope: core.Construct, id: str, custom: dict, **kwargs) -> None: super().__init__(scope, id, **kwargs) region = self.region #create S3 access role for ec2 ec2Role = iam.Role( self, "aws-cdk-handson-lab02-ec2role", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( "AmazonS3ReadOnlyAccess") ]) instanceProfile = iam.CfnInstanceProfile( self, "aws-cdk-handson-lab02-ec2Profile", roles=[ec2Role.role_name], instance_profile_name="aws-cdk-handson-lab02-ec2Profile", ) #create new VPC for lab02 #vpc = ec2.Vpc.from_lookup(self, "aws-cdk-handson-lab02-vpc",vpc_name="default") #使用默认的vpc #创建新的vpc vpc = ec2.Vpc(self, id="aws-cdk-handson-lab02-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 }, ]) #使用已有的安全组 #sg=ec2.SecurityGroup.from_security_group_id(self,"nodeSG",security_group_id='sg-0dd53aaa5c9eb8324') #创建新的安全组 sg = ec2.CfnSecurityGroup( self, "aws-cdk-handson-lab02-ec2securitygroup", group_description="this is aws-cdk-handson workshop", group_name="aws-cdk-handson-lab02-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", }, { "ipProtocol": "tcp", "fromPort": 8080, "toPort": 8080, "cidrIp": "0.0.0.0/0", }, ], vpc_id=vpc.vpc_id) #read and base64 encode userdata file data = open("../resource/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) #创建2台EC2 ec2Count = 2 for i in range(ec2Count): eni0 = ec2.CfnNetworkInterface( self, "eni-" + str(i), subnet_id=vpc.public_subnets[0].subnet_id, group_set=[sg.attr_group_id]) #group_set=[sg.security_group_id] instance = ec2.CfnInstance( self, "ec2-httpd-" + str(i), image_id=ami.get_image( self).image_id, #use Amazon Linux 2 AMI instance_type="t3.micro", key_name="wsu-cn-northwest-1", #这个是keypair的名字非常重要 tags=[ core.CfnTag(key="Name", value="aws-cdk-lab02-ec2-" + str(i)) ], #加上标签 iam_instance_profile=instanceProfile.ref, user_data=encodedStr, network_interfaces=[{ 'deviceIndex': '0', 'networkInterfaceId': eni0.ref, }]) core.CfnOutput(self, "PublicIP-" + str(i), export_name="PublicIP-" + str(i), value=instance.attr_public_ip) core.CfnOutput(self, "PublicDNSName-" + str(i), export_name="PublicDNSName-" + str(i), value=instance.attr_public_dns_name)
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) ############################################# ### Setup a basic vpc and security groups ### ############################################# # Create a simple vpc vpc = ec2.Vpc(self, "MyVPC", max_azs=3) # My existing ssh key pair name keypair = 'tom' # Dynamically pull ubuntu ami id - needs environment var set CDK_DEFAULT_REGION dynamic_ubuntu_ami = ec2.MachineImage.lookup( name="*ubuntu-bionic-18.04-amd64-server*", owners=["099720109477"]) # Security group for our test instance my_sg = ec2.SecurityGroup(self, "my_sg", vpc=vpc, description="My sg for testing", allow_all_outbound=True) # Add ssh from anywhere my_sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22), "Allow ssh access from anywhere") ################################################################# # Single Ubuntu EC2 instance in Private Subnet in an ASG of 1:1 # ################################################################# asg = autoscaling.AutoScalingGroup( self, "Ubuntu-ASG-Instance", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=dynamic_ubuntu_ami, key_name=keypair, ) asg.add_security_group(my_sg) # add our security group, expects object ######################################################## # Single Ubuntu EC2 instance in Private Subnet, no ASG # ######################################################## ubuntu_ami = dynamic_ubuntu_ami.get_image( self ).image_id # CfnInstances requires image_id to be the ami string instance = ec2.CfnInstance( self, "Ubuntu-Instance", image_id=ubuntu_ami, instance_type='m4.large', monitoring=True, key_name=keypair, network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": False, "subnetId": vpc.private_subnets[0].subnet_id, "groupSet": [my_sg.security_group_id] }], ) ################################################### # Bastion host to access Ubuntu hosts for testing # ################################################### host = ec2.BastionHostLinux( self, "BastionHost", vpc=vpc, subnet_selection=ec2.SubnetSelection( subnet_type=ec2.SubnetType.PUBLIC), ) host.allow_ssh_access_from( ec2.Peer.ipv4("0.0.0.0/0")) # Restrict this to your IP host.instance.instance.add_property_override( "KeyName", keypair) # Add keypair for access unless you use SSM
def __init__(self, scope: cdk.Construct, construct_id: str, gitlab: cdk.Stack, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) tags = cdk.Tags.of(self) tags.add(key='Stage', value='DevOps') tags.add(key='Module', value='Runner') tags.add(key='Owner', value='Vunk.Lai') tags.add(key='Name', value='GitLab/Runner', apply_to_launched_instances=True) subnets = gitlab.vpc.select_subnets(subnet_group_name='Runner').subnets security_group = ec2.SecurityGroup( self, 'sg', vpc=gitlab.vpc, security_group_name='GitLab/Runner:SecurityGroup', description='Default Runner Security Group', allow_all_outbound=True) policy = iam.ManagedPolicy( self, 'policy', # Use alphanumeric and '+=,.@-_' characters managed_policy_name='GitLab-Runner_Policy', description='SSM Login', statements=[ iam.PolicyStatement( actions=['ssmmessages:*', 'ssm:UpdateInstanceInformation'], resources=['*']), ]) role = iam.Role( self, 'role', # Use alphanumeric and '+=,.@-_' characters role_name='GitLab-Runner_Role', assumed_by=iam.ServicePrincipal('ec2.amazonaws.com'), managed_policies=[policy]) folder = Path(__file__).parent.parent / 'user_data' user_data = ec2.UserData.for_linux() user_data.add_commands( 'apt install unzip', 'curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "aws_cli_v2.zip"', 'unzip aws_cli_v2.zip', 'sudo ./aws/install', 'aws --version') asset = Asset(self, 'asset:userdata', path=str(folder / 'runner.sh')) asset.grant_read(role) path = user_data.add_s3_download_command( bucket=asset.bucket, bucket_key=asset.s3_object_key) user_data.add_execute_file_command( file_path=path, arguments='--verbose -y') template = ec2.LaunchTemplate( self, 'template', launch_template_name='GitLab/Runner_LaunchTemplate', cpu_credits=ec2.CpuCredits.STANDARD, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO), machine_image=ec2.MachineImage.lookup( name='ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*', owners=['099720109477']), role=role, security_group=security_group, user_data=user_data, block_devices=[ ec2.BlockDevice( device_name='/dev/sda1', volume=ec2.BlockDeviceVolume.ebs( volume_size=20, volume_type=ec2.EbsDeviceVolumeType.GP3, delete_on_termination=True, )), ] ) ec2.CfnInstance( self, 'instance', launch_template=ec2.CfnInstance.LaunchTemplateSpecificationProperty( version=template.latest_version_number, launch_template_id=template.launch_template_id, ), subnet_id=subnets[0].subnet_id )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) vpc = ec2.Vpc( self, "MyVpc", cidr="10.13.0.0/21", max_azs=2, nat_gateways=0, subnet_configuration=[ ec2.SubnetConfiguration(name="pubSubnet", cidr_mask=24, subnet_type=ec2.SubnetType.PUBLIC), # ec2.SubnetConfiguration(name="private", cidr_mask=24, subnet_type=ec2.SubnetType.PRIVATE) # ec2.SubnetConfiguration(name="private", cidr_mask=24, subnet_type=ec2.SubnetType.ISOLATED) ]) # Tag all VPC Resources core.Tag.add(vpc, key="Owner", value="KonStone", include_resource_types=[]) # We are using the latest AMAZON LINUX AMI ami_id = ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration. AMAZON_LINUX_2).get_image(self).image_id # Lets add a security group for port 80 web_sg = ec2.SecurityGroup( self, "web_sec_grp", vpc=vpc, description="Allow internet access from the world", allow_all_outbound=True) web_sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(80), "Allow internet access from the world.") broken_nacl = ec2.NetworkAcl(self, "web_broken_nacl", vpc=vpc) # Enable below section to break web server """ broken_nacl.associate_with_subnet("web_broken_nacl", subnets = [vpc.public_subnets[0]] # subnet_type = ec2.SubnetType.PUBLIC ) """ broken_nacl.add_entry("broken_nacl_in_rule_120", cidr=ec2.AclCidr.any_ipv4(), rule_number=120, traffic=ec2.AclTraffic.tcp_port(80), direction=ec2.TrafficDirection.INGRESS, rule_action=ec2.Action.ALLOW) broken_nacl.add_entry( "broken_nacl_out_rule_120", cidr=ec2.AclCidr.any_ipv4(), rule_number=120, # traffic = ec2.AclTraffic.all_traffic(), traffic=ec2.AclTraffic.tcp_port(80), # traffic = ec2.AclTraffic.tcp_port_range(0, 65535), direction=ec2.TrafficDirection.EGRESS, rule_action=ec2.Action.ALLOW) with open("./bootstrap_scripts/httpd.sh", mode='rb') as file: data = file.read() httpd = ec2.UserData.for_linux() httpd.add_commands(str(data, 'utf-8')) # We define instance details here web_inst = ec2.CfnInstance( self, "web-instance", image_id=ami_id, instance_type="t2.micro", monitoring=False, tags=[{ "key": "Name", "value": "KonStone-Web-instance" }], network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, "groupSet": [web_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 user_data=core.Fn.base64(httpd.render())) core.Tag.add(web_inst, key="Owner", value="KonStone", include_resource_types=[])
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( self, "MyVpc", cidr="10.13.0.0/21", max_azs=2, nat_gateways=0, subnet_configuration=[ ec2.SubnetConfiguration(name="pubSubnet", cidr_mask=24, subnet_type=ec2.SubnetType.PUBLIC), ] ) # Tag all VPC Resources core.Tag.add(vpc,key="Owner",value="KonStone",include_resource_types=[]) # We are using the latest AMAZON LINUX AMI ami_id = ec2.AmazonLinuxImage(generation = ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image(self).image_id # Lets add a security group for port 80 high_perf_sg = ec2.SecurityGroup(self, "web_sec_grp", vpc = vpc, description="Allow internet access from the world", allow_all_outbound = True ) high_perf_sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22), "Allow internet access from the world." ) high_perf_sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.icmp_ping(), "Allow ping in security group." ) # Update your key-name ssh_key_name = "virk" # We define instance details here web_inst_01 = ec2.CfnInstance(self, "webinstance01", image_id = ami_id, instance_type = "t2.micro", monitoring = False, key_name = ssh_key_name, # tags = [{"key": "Name","value": "KonStone-Web-instance"}], block_device_mappings=[{ "ebs" : { "volumeSize" : 25 }, "deviceName" : "/dev/xvda", }], network_interfaces = [{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, "groupSet": [high_perf_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 tags=[core.CfnTag(key="Name", value=f"KonStone-Stack")] ) web_inst_02 = ec2.CfnInstance(self, "webinstance02", image_id = ami_id, instance_type = "t2.micro", monitoring = False, key_name = ssh_key_name, # tags = [{"key": "Name","value": "KonStone-Web-instance"}], # block_device_mappings=[{"deviceName":"/dev/xvda"}] block_device_mappings=[{ "ebs" : { "volumeSize" : 25 }, "deviceName" : "/dev/xvda", }], network_interfaces = [{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, "groupSet": [high_perf_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 tags=[core.CfnTag(key="Name", value=f"KonStone-Stack")] ) # https://docs.aws.amazon.com/cdk/api/latest/python/modules.html a1 = core.Fn.get_att(logical_name_of_resource="webinstance01",attribute_name="PublicIp") core.CfnOutput(self, "web_inst_01", value=a1.to_string(), description="Web Server Public IP")
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # IAMロールを作成 my_role_ec2 = iam.CfnRole( self, id="my-role-ec2", assume_role_policy_document={ "Version": "2012-10-17", "Statement": [{ "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" } }] }, description="the ec2 role", managed_policy_arns=[ # "arn:aws:iam::aws:policy/AmazonS3FullAccess" # 付与したいアクセス権をリストする ], role_name="my-role-ec2", tags=[{ "key": "Name", "value": "my-role-ec2" }]) # Instance Profileを作成 my_instance_profile = iam.CfnInstanceProfile(self, id="my-instance-profile", roles=[my_role_ec2.ref]) # VPCを作成 my_vpc = ec2.CfnVPC(self, id="my-vpc", cidr_block="192.168.0.0/16", enable_dns_hostnames=True, tags=[{ "key": "Name", "value": "my-vpc" }]) # Subnetを作成 my_subnet_1 = ec2.CfnSubnet(self, id="my-subnet", cidr_block="192.168.0.0/24", vpc_id=my_vpc.ref, availability_zone=core.Fn.select( 0, core.Fn.get_azs("")), tags=[{ "key": "Name", "value": "my-subnet-1" }]) # Internet Gatewayを作成 my_igw = ec2.CfnInternetGateway(self, id="my-igw", tags=[{ "key": "Name", "value": "my-igw" }]) # Internet Gatewayをアタッチ ec2.CfnVPCGatewayAttachment(self, id="my-igw-attachment", vpc_id=my_vpc.ref, internet_gateway_id=my_igw.ref) # Routetableを作成 my_rtb = ec2.CfnRouteTable(self, id="my-rtb", vpc_id=my_vpc.ref, tags=[{ "key": "Name", "value": "my-rtb" }]) # Routetableとサブネットの関連付け ec2.CfnSubnetRouteTableAssociation(self, id="my-rtb-association", route_table_id=my_rtb.ref, subnet_id=my_subnet_1.ref) # Routeの設定 my_rt = ec2.CfnRoute(self, id="my-rt", route_table_id=my_rtb.ref, destination_cidr_block="0.0.0.0/0", gateway_id=my_igw.ref) # Security Groupの作成 my_sg_ec2 = ec2.CfnSecurityGroup( self, id="my-sg-ec2", vpc_id=my_vpc.ref, group_description="my-sg-ec2", group_name="my-sg-ec2", security_group_ingress=[ ec2.CfnSecurityGroup.IngressProperty(ip_protocol="tcp", cidr_ip="0.0.0.0/0", from_port=22, to_port=22) ], tags=[{ "key": "Name", "value": "my-sg-ec2" }]) # AMIを指定してimage_idを取得 amzn_linux = ec2.MachineImage.latest_amazon_linux( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX, edition=ec2.AmazonLinuxEdition.STANDARD, virtualization=ec2.AmazonLinuxVirt.HVM, storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE, cpu_type=ec2.AmazonLinuxCpuType.X86_64).get_image(self).image_id # EC2を作成 my_ec2 = ec2.CfnInstance( self, id="my-ec2", availability_zone=core.Fn.select(0, core.Fn.get_azs("")), block_device_mappings=[ ec2.CfnInstance.BlockDeviceMappingProperty( device_name="/dev/sda1", ebs=ec2.CfnInstance.EbsProperty(delete_on_termination=True, encrypted=False, volume_size=10, volume_type="gp2")) ], credit_specification=ec2.CfnInstance.CreditSpecificationProperty( cpu_credits="standard"), iam_instance_profile=my_instance_profile.ref, image_id=amzn_linux, instance_type="t2.micro", security_group_ids=[my_sg_ec2.ref], subnet_id=my_subnet_1.ref, tags=[{ "key": "Name", "value": "my-ec2" }])
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Parameter LatestAmiId = core.CfnParameter( self, "LatestAmiId", type="AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>", default= "/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2") # S3 Bucket source_bucket = "sourcebucketname%s" % (core.Aws.ACCOUNT_ID) # Resources CloudFormationLogs = logs.LogGroup( self, 'CloudFormationLogs', retention=logs.RetentionDays('ONE_WEEK')) WebInstance1 = ec2.CfnInstance( self, 'WebInstance1', additional_info=None, affinity=None, iam_instance_profile=core.Fn.import_value( "WebServerInstanceProfileOutput"), image_id=LatestAmiId.value_as_string, instance_type='t3.micro', network_interfaces=[{ "deviceIndex": "0", "groupSet": [core.Fn.import_value("WebSecurityGroupOutput")], "subnetId": core.Fn.import_value("PrivateSubnet1") }], tags=[core.CfnTag(key="Name", value="WebServer1")], user_data=core.Fn.base64("""#!/bin/bash -ex yum update -y /opt/aws/bin/cfn-init -v --stack {StackName} --resource WebInstance1 --configsets InstallAndDeploy --region {Region} # Signal the status from cfn-init (via $?) /opt/aws/bin/cfn-signal -e $? --stack {StackName} --resource WebInstance1 --region {Region} """.format(StackName=core.Aws.STACK_NAME, Region=core.Aws.REGION))) WebInstance1.cfn_options.metadata = { "AWS::CloudFormation::Authentication": { "rolebased": { "type": "S3", "buckets": [source_bucket], "roleName": core.Fn.import_value("WebServerRoleOutput") } }, "AWS::CloudFormation::Init": { "configSets": { "InstallAndDeploy": ["Install", "InstallLogs", "Deploy"] }, "Install": { "packages": { "yum": { "python36": [], "python36-devel": [], "nginx": [], "gcc": [] } }, "files": { "/etc/cfn/cfn-hup.conf": { "content": """ [main] stack={} region={} interval=1 verbose=true""".format(core.Aws.STACK_ID, core.Aws.REGION), "mode": "000400", "owner": "root", "group": "root" }, "/etc/cfn/hooks.d/cfn-auto-reloader.conf": { "content": """ [cfn-auto-reloader-hook] triggers=post.update path=Resources.WebInstance1.Metadata.AWS::CloudFormation::Init action=/opt/aws/bin/cfn-init -v --stack {} --resource WebInstance1 --configsets InstallAndDeploy --region {} runas=root""".format(core.Aws.STACK_NAME, core.Aws.REGION), "mode": "000400", "owner": "root", "group": "root" } }, "services": { "sysvinit": { "nginx": { "enabled": "true", "ensureRunning": "true" }, "cfn-hup": { "enabled": "true", "ensureRunning": "true", "files": [ "/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-auto-reloader.conf" ] } } }, "commands": { "01_unblock_nginx": { "command": "chkconfig nginx on" }, "02_install_xray": { "command": "curl https://s3.dualstack.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-3.x.rpm -o /tmp/xray.rpm && yum install -y /tmp/xray.rpm\n", "cwd": "/tmp", "ignoreErrors": "true" } } }, "InstallLogs": { "packages": { "yum": { "awslogs": [] } }, "files": { "/etc/awslogs/awslogs.conf": { "content": """ [general] state_file= /var/awslogs/state/agent-state [yum] file = /var/log/yum.log log_group_name = %s log_stream_name = {{hostname}} - {{instance_id}} yum.log [messages] file = /var/log/messages log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} messages.log [cfn-hup] file = /var/log/cfn-hup.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-hup.log [cfn-init] file = /var/log/cfn-init.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-init.log [cfn-init-cmd] file = /var/log/cfn-init-cmd.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-init-cmd.log [cloud-init] file = /var/log/cloud-init.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cloud-init.log [cloud-init-output] file = /var/log/cloud-init-output.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cloud-init.log [handler] file = /var/log/handler.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} handler.log [uwsgi] file = /var/log/uwsgi.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} uwsgi.log [nginx_access] file = /var/log/nginx/access.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} nginx_access.log [nginx_error] file = /var/log/nginx/error.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} nginx_error.log """.format(CloudFormationLogs=CloudFormationLogs. log_group_name), "group": "root", "owner": "root", "mode": "000400" }, "/etc/awslogs/awscli.conf": { "content": """ [plugins] cwlogs = cwlogs [default] region = {} """.format(core.Aws.REGION), "mode": "000444", "owner": "root", "group": "root" } }, "commands": { "01_create_state_directory": { "command": "mkdir -p /var/awslogs/state" } }, "services": { "sysvinit": { "awslogs": { "enabled": "true", "ensureRunning": "true", "files": ["/etc/awslogs/awslogs.conf"] } } } }, "Deploy": { "sources": { "/photos": "https://s3.amazonaws.com/{}/deploy-app.zip".format( source_bucket) }, "commands": { "01_pip_uwsgi": { "command": "pip-3.6 install uwsgi", "cwd": "/photos", "ignoreErrors": "false" }, "02_pip_flask_app_requirements": { "command": "pip-3.6 install -r requirements.txt", "cwd": "/photos/FlaskApp", "ignoreErrors": "false" }, "03_stop_uwsgi": { "command": "stop uwsgi", "ignoreErrors": "true" }, "04_stop_nginx": { "command": "service nginx stop" }, "05_copy_config": { "command": "mv -f nginx.conf /etc/nginx/nginx.conf && mv -f uwsgi.conf /etc/init/uwsgi.conf", "cwd": "/photos/Deploy", "ignoreErrors": "false" }, "06_create_database": { "command": "python3 database_create_tables.py", "cwd": "/photos/Deploy", "ignoreErrors": "false" }, "07_start_uwsgi": { "command": "start uwsgi" }, "08_restart_nginx": { "command": "service nginx start" } } } } } WebInstance1.cfn_options.creation_policy = core.CfnCreationPolicy( resource_signal=core.CfnResourceSignal(timeout='PT10M')) WebInstance2 = ec2.CfnInstance( self, 'WebInstance2', additional_info=None, affinity=None, iam_instance_profile=core.Fn.import_value( "WebServerInstanceProfileOutput"), image_id=LatestAmiId.value_as_string, instance_type='t3.micro', network_interfaces=[{ "deviceIndex": "0", "groupSet": [core.Fn.import_value("WebSecurityGroupOutput")], "subnetId": core.Fn.import_value("PrivateSubnet2") }], tags=[core.CfnTag(key="Name", value="WebServer2")], user_data=core.Fn.base64("""#!/bin/bash -ex yum update -y /opt/aws/bin/cfn-init -v --stack {StackName} --resource WebInstance2 --configsets InstallAndDeploy --region {Region} # Signal the status from cfn-init (via $?) /opt/aws/bin/cfn-signal -e $? --stack {StackName} --resource WebInstance2 --region {Region} """.format(StackName=core.Aws.STACK_NAME, Region=core.Aws.REGION))) WebInstance2.cfn_options.metadata = { "AWS::CloudFormation::Authentication": { "rolebased": { "type": "S3", "buckets": [source_bucket], "roleName": core.Fn.import_value("WebServerRoleOutput") } }, "AWS::CloudFormation::Init": { "configSets": { "InstallAndDeploy": ["Install", "InstallLogs", "Deploy"] }, "Install": { "packages": { "yum": { "python36": [], "python36-devel": [], "nginx": [], "gcc": [] } }, "files": { "/etc/cfn/cfn-hup.conf": { "content": """ [main] stack={} region={} interval=1 verbose=true""".format(core.Aws.STACK_ID, core.Aws.REGION), "mode": "000400", "owner": "root", "group": "root" }, "/etc/cfn/hooks.d/cfn-auto-reloader.conf": { "content": """ [cfn-auto-reloader-hook] triggers=post.update path=Resources.WebInstance1.Metadata.AWS::CloudFormation::Init action=/opt/aws/bin/cfn-init -v --stack {} --resource WebInstance2 --configsets InstallAndDeploy --region {} runas=root""".format(core.Aws.STACK_NAME, core.Aws.REGION), "mode": "000400", "owner": "root", "group": "root" } }, "services": { "sysvinit": { "nginx": { "enabled": "true", "ensureRunning": "true" }, "cfn-hup": { "enabled": "true", "ensureRunning": "true", "files": [ "/etc/cfn/cfn-hup.conf", "/etc/cfn/hooks.d/cfn-auto-reloader.conf" ] } } }, "commands": { "01_unblock_nginx": { "command": "chkconfig nginx on" }, "02_install_xray": { "command": "curl https://s3.dualstack.us-east-2.amazonaws.com/aws-xray-assets.us-east-2/xray-daemon/aws-xray-daemon-3.x.rpm -o /tmp/xray.rpm && yum install -y /tmp/xray.rpm\n", "cwd": "/tmp", "ignoreErrors": "true" } } }, "InstallLogs": { "packages": { "yum": { "awslogs": [] } }, "files": { "/etc/awslogs/awslogs.conf": { "content": """ [general] state_file= /var/awslogs/state/agent-state [yum] file = /var/log/yum.log log_group_name = %s log_stream_name = {{hostname}} - {{instance_id}} yum.log [messages] file = /var/log/messages log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} messages.log [cfn-hup] file = /var/log/cfn-hup.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-hup.log [cfn-init] file = /var/log/cfn-init.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-init.log [cfn-init-cmd] file = /var/log/cfn-init-cmd.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cfn-init-cmd.log [cloud-init] file = /var/log/cloud-init.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cloud-init.log [cloud-init-output] file = /var/log/cloud-init-output.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} cloud-init.log [handler] file = /var/log/handler.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} handler.log [uwsgi] file = /var/log/uwsgi.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} uwsgi.log [nginx_access] file = /var/log/nginx/access.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} nginx_access.log [nginx_error] file = /var/log/nginx/error.log log_group_name = {CloudFormationLogs} log_stream_name = {{hostname}} - {{instance_id}} nginx_error.log """.format(CloudFormationLogs=CloudFormationLogs. log_group_name), "group": "root", "owner": "root", "mode": "000400" }, "/etc/awslogs/awscli.conf": { "content": """ [plugins] cwlogs = cwlogs [default] region = {} """.format(core.Aws.REGION), "mode": "000444", "owner": "root", "group": "root" } }, "commands": { "01_create_state_directory": { "command": "mkdir -p /var/awslogs/state" } }, "services": { "sysvinit": { "awslogs": { "enabled": "true", "ensureRunning": "true", "files": ["/etc/awslogs/awslogs.conf"] } } } }, "Deploy": { "sources": { "/photos": "https://s3.amazonaws.com/{}/deploy-app.zip".format( source_bucket) }, "commands": { "01_pip_uwsgi": { "command": "pip-3.6 install uwsgi", "cwd": "/photos", "ignoreErrors": "false" }, "02_pip_flask_app_requirements": { "command": "pip-3.6 install -r requirements.txt", "cwd": "/photos/FlaskApp", "ignoreErrors": "false" }, "03_stop_uwsgi": { "command": "stop uwsgi", "ignoreErrors": "true" }, "04_stop_nginx": { "command": "service nginx stop" }, "05_copy_config": { "command": "mv -f nginx.conf /etc/nginx/nginx.conf && mv -f uwsgi.conf /etc/init/uwsgi.conf", "cwd": "/photos/Deploy", "ignoreErrors": "false" }, "06_create_database": { "command": "python3 database_create_tables.py", "cwd": "/photos/Deploy", "ignoreErrors": "false" }, "07_start_uwsgi": { "command": "start uwsgi" }, "08_restart_nginx": { "command": "service nginx start" } } } } } WebInstance2.cfn_options.creation_policy = core.CfnCreationPolicy( resource_signal=core.CfnResourceSignal(timeout='PT10M')) DefaultTargetGroup = elasticloadbalancingv2.CfnTargetGroup( self, 'DefaultTargetGroup', health_check_interval_seconds=15, health_check_path="/", health_check_protocol="HTTP", health_check_timeout_seconds=10, healthy_threshold_count=2, unhealthy_threshold_count=2, matcher={'httpCode': '200-299'}, port=80, protocol="HTTP", vpc_id=core.Fn.import_value("VPC"), target_group_attributes=[{ "key": "deregistration_delay.timeout_seconds", "value": "30" }], targets=[{ "id": WebInstance1.ref, "port": 80 }, { "id": WebInstance2.ref, "port": 80 }]) HttpListener = elasticloadbalancingv2.CfnListener( self, 'HttpListener', default_actions=[{ "type": "forward", "targetGroupArn": DefaultTargetGroup.ref }], load_balancer_arn=core.Fn.import_value("LoadBalancerArn"), port=80, protocol="HTTP")
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, vpc, subnet_id, **kwargs) -> None: super().__init__(scope, id, **kwargs) prefix = self.node.try_get_context("project_name") env_name = self.node.try_get_context("env") volumne_size = self.node.try_get_context("volumne_size") ec2_type = self.node.try_get_context("ec2_type") self.security_group = ec2.CfnSecurityGroup( self, id="web_server_sg", vpc_id=vpc.ref, group_name=env_name + '-' + prefix + '-www01', group_description="Web server security group", # security_group_ingress=[ingress_ssh], # security_group_egress=[egress_all], tags=[ core.CfnTag(key="Name", value=env_name + '-' + prefix + '-www01') ]) # public Ingress ec2.CfnSecurityGroupIngress(self, 'publicsecuritygroupingress01', group_id=self.security_group.ref, ip_protocol='tcp', cidr_ip='0.0.0.0/0', description='http', from_port=80, to_port=80) ec2.CfnSecurityGroupIngress(self, 'publicsecuritygroupingress02', group_id=self.security_group.ref, ip_protocol='tcp', cidr_ip='0.0.0.0/0', description='ssh', from_port=22, to_port=22) # public Egress ec2.CfnSecurityGroupEgress( self, 'publicsecuritygroupegress01', group_id=self.security_group.ref, ip_protocol='-1', cidr_ip='0.0.0.0/0' # destination_security_group_id=privatesecuritygroup01.ref, # description='for private', # from_port=22, to_port=22 ) # private Ingress image_id = ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image( self).image_id self.host = ec2.CfnInstance( self, env_name + '-' + prefix, # availability_zone="ap-northeast-1a", image_id=image_id, instance_type=ec2_type, key_name=key_name, # credit_specification= { "cpu_credits" : "standard" }, credit_specification=ec2.CfnInstance.CreditSpecificationProperty( cpu_credits="standard"), disable_api_termination=False, security_group_ids=[self.security_group.ref], subnet_id=subnet_id.ref, block_device_mappings=[{ "deviceName": "/dev/xvda", "ebs": { "volumeSize": volumne_size, } }], tags=[{ "key": "Name", "value": env_name + '-' + prefix + '-www01' }])
def __init__(self, scope: core.Construct, id: str, vpc_ip: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) if vpc_ip: print("VPC_IP " + vpc_ip) cidr = vpc_ip else: cidr = "10.0.0.0/16" # 01. VPC 생성 cfVpc = ec2.CfnVPC(self, "VPC", cidr_block=cidr, tags=[core.Tag(key="Name", value="CDKVPC")]) # 02. Subnet 생성 subnet_2a = ec2.CfnSubnet( self, id="subnet_2a", availability_zone="ap-northeast-2a", cidr_block="100.0.1.0/24", map_public_ip_on_launch=True, vpc_id=cfVpc.ref, tags=[core.Tag(key="Name", value="subnet-2a")]) subnet_2c = ec2.CfnSubnet( self, id="subnet_2c", availability_zone="ap-northeast-2c", cidr_block="100.0.2.0/24", map_public_ip_on_launch=True, vpc_id=cfVpc.ref, tags=[core.Tag(key="Name", value="subnet-2c")]) # 03. Internet Gateway 생성 internet_gateway = ec2.CfnInternetGateway( self, id="Internet_Gateway_DNS_Example", tags=[core.Tag(key="Name", value="Internet_Gateway_for_DNS")]) # 04. Internat Gateway Attach ec2.CfnVPCGatewayAttachment(self, id="vpcgw", vpc_id=cfVpc.ref, internet_gateway_id=internet_gateway.ref) #05. Route Table 생성 route_table = ec2.CfnRouteTable( self, id="dns_example_routetable", vpc_id=cfVpc.ref, tags=[core.Tag(key="Name", value="Route_for_DNS")]) #Route ec2.CfnRoute(self, id="IGW_Route", route_table_id=route_table.ref, destination_cidr_block="0.0.0.0/0", gateway_id=internet_gateway.ref) ec2.CfnSubnetRouteTableAssociation(self, id="DnsSubnet_Associate_2a", route_table_id=route_table.ref, subnet_id=subnet_2a.ref) ec2.CfnSubnetRouteTableAssociation(self, id="DnsSubnet_Associate_2c", route_table_id=route_table.ref, subnet_id=subnet_2c.ref) # 03. SG 생성 sg = ec2.CfnSecurityGroup(self, id="sg-ssh", vpc_id=cfVpc.ref, group_description="Default Group", tags=[core.Tag(key="Name", value="DNS_SG")]) #security_group_ingress=[ingress_ssh]) #security_group_egress=[egress_all]) ingress_ssh = ec2.CfnSecurityGroupIngress(self, "SSH", ip_protocol="tcp", group_id=sg.ref, from_port=22, to_port=22, cidr_ip="0.0.0.0/0") egress_all = ec2.CfnSecurityGroupEgress( self, id="OUTBOUND", group_id=sg.ref, ip_protocol="-1", #from_port=0, #to_port=65535, cidr_ip="0.0.0.0/0") # 04. DNS Server EC2 생성 dns_server = ec2.MachineImage.generic_linux( {"ap-northeast-2": "ami-00d293396a942208d"}) ec2.CfnInstance(self, id="dns_master", image_id=dns_server.get_image(self).image_id, instance_type="t2.small", key_name="SeoulRegion", security_group_ids=[sg.ref], subnet_id=subnet_2a.ref, tags=[{ "key": "Name", "value": "dns_master" }]) ec2.CfnInstance(self, id="dns_slave", image_id=dns_server.get_image(self).image_id, instance_type="t2.small", key_name="SeoulRegion", security_group_ids=[sg.ref], subnet_id=subnet_2c.ref, tags=[{ "key": "Name", "value": "dns_slave" }])
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=1, subnet_configuration=[]) subnet = ec2.Subnet(self, id="MySubnet", availability_zone="eu-central-1a", cidr_block="192.168.1.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) subnet.add_route(id="default_route", router_id=igw.ref, router_type=ec2.RouterType('GATEWAY'), destination_cidr_block="0.0.0.0/0", enables_internet_connectivity=True) 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.ipify.org").text 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_pub_in_{protocol}_{port}", group_id=sg_public.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") with open("/home/dragos/Documents/AWS_CDK/instance_creation/instance_creation/configure.sh", 'r') as config_file: ud = core.Fn.base64(config_file.read()) instance = ec2.CfnInstance(self, id="MyInstance", image_id="ami-0de9f803fcac87f46", instance_type="t2.micro", subnet_id=subnet.subnet_id, key_name="proton_mail_kp", security_group_ids=[sg_public.ref], tags=[core.CfnTag(key="Name", value="MyInstance")]) # COMMENT instance.user_data = ud
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, 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) # Lets create couple of instances to test): vpc = _ec2.Vpc(self, "abacVPC", cidr="10.13.0.0/21", max_azs=2, nat_gateways=0, subnet_configuration=[ _ec2.SubnetConfiguration( name="pubSubnet", cidr_mask=24, subnet_type=_ec2.SubnetType.PUBLIC) ]) core.Tag.add(vpc, key="ServiceProvider", value="KonStone", include_resource_types=[]) weak_sg = _ec2.SecurityGroup( self, "web_sec_grp", vpc=vpc, description="Allow internet access from the world", allow_all_outbound=True) # vpc_cidr_block # weak_sg.add_ingress_rule(_ec2.Peer.any_ipv4(), weak_sg.add_ingress_rule(_ec2.Peer.ipv4(vpc.vpc_cidr_block), _ec2.Port.tcp(22), "Allow SSH access from the VPC Only.") # We are using the latest AMAZON LINUX AMI # Benefit of having SSM Agent pre-installed ami_id = _ec2.AmazonLinuxImage(generation=_ec2.AmazonLinuxGeneration. AMAZON_LINUX_2).get_image(self).image_id # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_iam/Role.html instace_profile_role = _iam.Role( self, 'ec2ssmroleid', assumed_by=_iam.ServicePrincipal('ec2.amazonaws.com'), role_name="instace_profile_role") instace_profile_role.add_managed_policy( _iam.ManagedPolicy.from_aws_managed_policy_name( 'AmazonSSMManagedInstanceCore')) instance_profile_role_additional_perms = _iam.PolicyStatement( effect=_iam.Effect.ALLOW, resources=[ "arn:aws:logs:*:*:*", ], actions=["logs:Create*", "logs:PutLogEvents"]) instance_profile_role_additional_perms.sid = "PutBucketPolicy" instace_profile_role.add_to_policy( instance_profile_role_additional_perms) inst_profile_01 = _iam.CfnInstanceProfile( self, "instProfile01Id", roles=[instace_profile_role.role_name], ) # Let us bootstrap the server with the required agents try: with open("./bootstrap_scripts/install_agents.sh", mode='rb') as file: bootstrap_data = file.read() except OSError: print('Failed to get UserData script') install_agents = _ec2.UserData.for_linux() install_agents.add_commands(str(bootstrap_data, 'utf-8')) # The EC2 Instance to monitor for failed SSH Logins ssh_monitored_inst_01 = _ec2.CfnInstance( self, "sshMonitoredInstance01", image_id=ami_id, instance_type="t2.micro", monitoring=False, tags=[{ "key": "ServiceProvider", "value": "KonStone" }], iam_instance_profile=inst_profile_01.ref, network_interfaces=[{ "deviceIndex": "0", "associatePublicIpAddress": True, "subnetId": vpc.public_subnets[0].subnet_id, "groupSet": [weak_sg.security_group_id] }], #https: //github.com/aws/aws-cdk/issues/3419 user_data=core.Fn.base64(install_agents.render()), ) """ linux_ami = _ec2.GenericLinuxImage({ "cn-northwest-1": "ami-0f62e91915e16cfc2","eu-west-1": "ami-12345678"}) ssh_monitored_inst_01_02 = _ec2.Instance(self, "monitoredInstance02", instance_type=_ec2.InstanceType(instance_type_identifier="t2.micro"), instance_name="monitoredInstance02", machine_image=linux_ami, vpc=vpc, security_group=[weak_sg.security_group_id], # vpc_subnets=_ec2.SubnetSelection(subnet_type=_ec2.SubnetType.PUBLIC) vpc_subnets=vpc.public_subnets[0].subnet_id, # user_data=_ec2.UserData.custom(t_user_data) ) """ # The log group name to store logs info_sec_ops_log_group = _logs.LogGroup( self, "infoSecOpsLogGroupId", log_group_name=(f"/Mystique/InfoSec/Automation/" f"{ssh_monitored_inst_01.ref}"), retention=_logs.RetentionDays.ONE_WEEK) # Defines an AWS Lambda resource with open("lambda_src/quarantine_ec2_instance.py", encoding="utf8") as fp: quarantine_ec2_instance_fn_handler_code = fp.read() quarantine_ec2_instance_fn = _lambda.Function( self, id='quarantineEc2InstanceFnId', function_name="quarantine_ec2_instance", runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.InlineCode(quarantine_ec2_instance_fn_handler_code), handler='index.lambda_handler', timeout=core.Duration.seconds(5)) quarantine_ec2_instance_fn_perms = _iam.PolicyStatement( effect=_iam.Effect.ALLOW, resources=[ "*", ], actions=[ "ec2:RevokeSecurityGroupIngress", "ec2:DescribeSecurityGroupReferences", "ec2:RevokeSecurityGroupEgress", "ec2:ApplySecurityGroupsToClientVpnTargetNetwork", "ec2:DescribeSecurityGroups", "ec2:CreateSecurityGroup", "ec2:DescribeInstances", "ec2:CreateTags", "ec2:StopInstances", "ec2:CreateVolume", "ec2:CreateSnapshots", "ec2:CreateSnapshot", "ec2:DescribeSnapshots", "ec2:ModifyInstanceAttribute" ]) quarantine_ec2_instance_fn_perms.sid = "AllowLambdaToQuarantineEC2" quarantine_ec2_instance_fn.add_to_role_policy( quarantine_ec2_instance_fn_perms) info_sec_ops_topic = _sns.Topic(self, "infoSecOpsTopicId", display_name="InfoSecTopic", topic_name="InfoSecOpsTopic") # Ref: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-stepfunctions-readme.html ############################################################################### ################# STEP FUNCTIONS EXPERIMENTAL CODE - UNSTABLE ################# ############################################################################### quarantine_ec2_instance_task = _sfn.Task( self, "Quarantine EC2 Instance", task=_tasks.InvokeFunction(quarantine_ec2_instance_fn), result_path="$") notify_secops_task = _sfn.Task( self, "Notify InfoSecOps", task=_tasks.PublishToTopic( info_sec_ops_topic, integration_pattern=_sfn.ServiceIntegrationPattern. FIRE_AND_FORGET, message=_sfn.TaskInput.from_data_at("$.message"), subject="SSH Error Response Notification")) ssh_error_response_failure = _sfn.Fail( self, "SSH Error Response Actions Failed", cause="All Response Actions were NOT completed", error="Check Logs") ssh_error_response_success = _sfn.Succeed( self, "SSH Error Response Actions Succeeded", comment="All Response Action Completed Successfully", ) ssh_error_response_sfn_definition = quarantine_ec2_instance_task\ .next(notify_secops_task\ .next(_sfn.Choice(self, "SSH Errors Response Complete?")\ .when(_sfn.Condition.number_equals("$.SdkHttpMetadata.HttpStatusCode", 200),ssh_error_response_success)\ .when(_sfn.Condition.not_( _sfn.Condition.number_equals("$.SdkHttpMetadata.HttpStatusCode", 200)), ssh_error_response_failure)\ .otherwise(ssh_error_response_failure) ) ) ssh_error_response_statemachine = _sfn.StateMachine( self, "stateMachineId", definition=ssh_error_response_sfn_definition, timeout=core.Duration.minutes(5)) ############################################################################### ################# STEP FUNCTIONS EXPERIMENTAL CODE - UNSTABLE ################# ############################################################################### # LAMBDA TO TRIGGER STATE MACHINE - since state cannot be invoked by SNS with open("lambda_src/trigger_state_machine.py", encoding="utf8") as fp: trigger_state_machine_fn_handler_code = fp.read() trigger_state_machine_fn = _lambda.Function( self, id='sshErrorResponseFnId', function_name="trigger_ssh_error_response_state_machine_fn", runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.InlineCode(trigger_state_machine_fn_handler_code), # code=_lambda.Code.asset("lambda_src/is_policy_permissive.py"), # code=_lambda.Code.asset('lambda_src'), # code=_lambda.InlineCode(code_body), handler='index.lambda_handler', timeout=core.Duration.seconds(5), environment={ "STATE_MACHINE_ARN": f"{ssh_error_response_statemachine.state_machine_arn}", }) trigger_state_machine_fn_perms = _iam.PolicyStatement( effect=_iam.Effect.ALLOW, resources=[ f"{ssh_error_response_statemachine.state_machine_arn}", ], actions=["states:StartExecution"]) trigger_state_machine_fn_perms.sid = "PutBucketPolicy" trigger_state_machine_fn.add_to_role_policy( trigger_state_machine_fn_perms) """ version = trigger_state_machine_fn.add_version(name=datetime.now().isoformat()) trigger_state_machine_fn_alias = _lambda.Alias(self, 'lmdaAliasId', alias_name='MystiqueTestAlias', version=version ) """ # Lets add permission to SNS to trigger our lambda function trigger_lambda_perms = _iam.PolicyStatement( effect=_iam.Effect.ALLOW, resources=[ trigger_state_machine_fn.function_arn, ], actions=[ "lambda:InvokeFunction", ]) trigger_lambda_perms.sid = "TriggerLambaFunction" # info_sec_ops_topic.add_to_resource_policy( trigger_lambda_perms ) # Subscribe InfoSecOps Email to topic info_sec_ops_topic.add_subscription( _subs.EmailSubscription(global_args.INFO_SEC_OPS_EMAIL)) # info_sec_ops_topic.add_subscription(_subs.LambdaSubscription(trigger_state_machine_fn)) trigger_state_machine_fn_alarm = trigger_state_machine_fn.metric_all_errors( ).create_alarm( self, "fn-error-alarm", threshold=5, alarm_name="trigger_state_machine_fn_error_alarm", evaluation_periods=5, period=core.Duration.minutes(1), ) subscribe_trigger_state_machine_fn_to_logs = _logs.SubscriptionFilter( self, "sshErrorLogSubscriptionId", log_group=info_sec_ops_log_group, destination=_logs_destination.LambdaDestination( trigger_state_machine_fn), filter_pattern=_logs.FilterPattern.space_delimited( "Mon", "day", "timestamp", "ip", "id", "status", "...").where_string("status", "=", "Invalid"), ) # https://pypi.org/project/aws-cdk.aws-logs/ # We are creating three filter # tooManySshDisconnects, invalidSshUser and invalidSshKey: # When a user tries to SSH with invalid username the next line is logged in the SSH log file: # Apr 20 02:39:35 ip-172-31-63-56 sshd[17136]: Received disconnect from xxx.xxx.xxx.xxx: 11: [preauth] too_many_ssh_disconnects_metric = _cloudwatch.Metric( namespace=f"{global_args.OWNER}", metric_name="tooManySshDisconnects") too_many_ssh_disconnects_filter = _logs.MetricFilter( self, "tooManySshDisconnectsFilterId", log_group=info_sec_ops_log_group, metric_namespace=too_many_ssh_disconnects_metric.namespace, metric_name=too_many_ssh_disconnects_metric.metric_name, filter_pattern=_logs.FilterPattern.space_delimited( "Mon", "day", "timestamp", "ip", "id", "msg1", "msg2", "...").where_string("msg2", "=", "disconnect"), metric_value="1") invalid_ssh_user_metric = _cloudwatch.Metric( namespace=f"{global_args.OWNER}", metric_name="invalidSshUser", ) invalid_ssh_user_filter = _logs.MetricFilter( self, "invalidSshUserFilterId", log_group=info_sec_ops_log_group, metric_namespace=invalid_ssh_user_metric.namespace, metric_name=invalid_ssh_user_metric.metric_name, filter_pattern=_logs.FilterPattern.space_delimited( "Mon", "day", "timestamp", "ip", "id", "status", "...").where_string("status", "=", "Invalid"), metric_value="1") invalid_ssh_key_metric = _cloudwatch.Metric( namespace=f"{global_args.OWNER}", metric_name="invalidSshKey") invalid_ssh_key_filter = _logs.MetricFilter( self, "invalidSshKeyFilterId", log_group=info_sec_ops_log_group, metric_namespace=invalid_ssh_key_metric.namespace, metric_name=invalid_ssh_key_metric.metric_name, filter_pattern=_logs.FilterPattern.space_delimited( "Mon", "day", "timestamp", "ip", "id", "msg1", "msg2", "...").where_string("msg1", "=", "Connection").where_string( "msg2", "=", "closed"), metric_value="1") # Now let us create alarms # alarm is raised there are more than 5(threshold) of the measured metrics in two(datapoint) of the last three seconds(evaluation): # Period=60Seconds, Eval=3, Threshold=5 too_many_ssh_disconnects_alarm = _cloudwatch.Alarm( self, "tooManySshDisconnectsAlarmId", alarm_name="too_many_ssh_disconnects_alarm", alarm_description= "The number disconnect requests is greater then 5, even 1 time in 3 minutes", metric=too_many_ssh_disconnects_metric, actions_enabled=True, period=core.Duration.minutes(1), threshold=5, evaluation_periods=3, datapoints_to_alarm=1, statistic="sum", comparison_operator=_cloudwatch.ComparisonOperator. GREATER_THAN_OR_EQUAL_TO_THRESHOLD) invalid_ssh_user_alarm = _cloudwatch.Alarm( self, "invalidSshUserAlarmId", alarm_name="too_many_invalid_ssh_users_alarm", alarm_description= "The number of invalid ssh users connecting is greater then 5, even 1 time in 3 minutes", metric=invalid_ssh_user_metric, actions_enabled=True, period=core.Duration.minutes(1), threshold=5, evaluation_periods=3, datapoints_to_alarm=1, statistic="sum", comparison_operator=_cloudwatch.ComparisonOperator. GREATER_THAN_THRESHOLD) invalid_ssh_user_alarm.add_alarm_action( _cloudwatch_actions.SnsAction(info_sec_ops_topic)) invalid_ssh_key_alarm = _cloudwatch.Alarm( self, "invalidSshKeyAlarmId", alarm_name="too_many_invalid_ssh_key_alarm", alarm_description= "The number of invalid ssh keys connecting is greater then 5, even 1 time in 3 minutes", metric=invalid_ssh_key_metric, actions_enabled=True, period=core.Duration.minutes(1), threshold=5, evaluation_periods=3, datapoints_to_alarm=1, statistic="sum", comparison_operator=_cloudwatch.ComparisonOperator. GREATER_THAN_OR_EQUAL_TO_THRESHOLD) invalid_ssh_key_alarm.add_alarm_action( _cloudwatch_actions.SnsAction(info_sec_ops_topic)) ########################################### ################# OUTPUTS ################# ########################################### output0 = core.CfnOutput( self, "SecuirtyAutomationFrom", value=f"{global_args.SOURCE_INFO}", description= "To know more about this automation stack, check out our github page." ) output1_1 = core.Fn.get_att( logical_name_of_resource="sshMonitoredInstance01", attribute_name="PublicIp") output1 = core.CfnOutput(self, "MonitoredInstance", value=output1_1.to_string(), description="Web Server Public IP to attack") output2 = core.CfnOutput( self, "SSHAlarms", value= (f"https://console.aws.amazon.com/cloudwatch/home?region=" f"{core.Aws.REGION}" f"#/configuration/" f"#alarmsV2:?search=ssh&alarmStateFilter=ALL&alarmTypeFilter=ALL" ), description="Check out the cloudwatch Alarms") output3 = core.CfnOutput( self, "SubscribeToNotificationTopic", value=(f"https://console.aws.amazon.com/sns/v3/home?" f"{core.Aws.REGION}" f"#/topic/" f"{info_sec_ops_topic.topic_arn}"), description= "Add your email to subscription and confirm subscription") output_test_1 = core.CfnOutput( self, "ToGenInvalidKeyErrors", value= (f"for i in {{1..30}}; do ssh -i $RANDOM ec2-user@{output1_1.to_string()}; sleep 2; done &" ), description= "Generates random key names and connects to server 30 times over 60 seconds" ) output_test_2 = core.CfnOutput( self, "ToGenInvalidUserErrors", value= (f"for i in {{1..30}}; do ssh ec2-user$RANDOM@{output1_1.to_string()}; sleep 2; done &" ), description= "Generates random user names and connects to server 30 times over 60 seconds" ) """
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) tags = cdk.Tags.of(self) tags.add(key='Stage', value='DevOps') tags.add(key='Module', value='GitLab') tags.add(key='Owner', value='Vunk.Lai') tags.add(key='Name', value='GitLab/GitLab', apply_to_launched_instances=True) vpc = ec2.Vpc( self, 'vpc', max_azs=1, cidr=ec2.Vpc.DEFAULT_CIDR_RANGE, nat_gateways=0, subnet_configuration=[ ec2.SubnetConfiguration(name='Generic', subnet_type=ec2.SubnetType.PUBLIC, cidr_mask=24, reserved=True), ec2.SubnetConfiguration(name='GitLab', subnet_type=ec2.SubnetType.PUBLIC, cidr_mask=24), ec2.SubnetConfiguration(name='Runner', subnet_type=ec2.SubnetType.PUBLIC, cidr_mask=24), ]) cdk.Tags.of(vpc).add(key='Name', value='GitLab/VPC') subnets = vpc.select_subnets(subnet_group_name='GitLab').subnets security_group = ec2.SecurityGroup( self, 'sg', vpc=vpc, security_group_name='GitLab/GitLab:SecurityGroup', description='Default GitLab Security Group', allow_all_outbound=True) security_group.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(80), 'LetsEncrypt HTTP-01') security_group.add_ingress_rule(ec2.Peer.ipv4(self.home_ip), ec2.Port.tcp(443), 'Home') security_group.add_ingress_rule( ec2.Peer.ipv4(ec2.Vpc.DEFAULT_CIDR_RANGE), ec2.Port.tcp(443), 'LAN') policy = iam.ManagedPolicy( self, 'policy', # Use alphanumeric and '+=,.@-_' characters managed_policy_name='GitLab-GitLab_Policy', description='SSM Login', statements=[ iam.PolicyStatement( actions=['ssmmessages:*', 'ssm:UpdateInstanceInformation'], resources=['*']), ]) role = iam.Role( self, 'role', # Use alphanumeric and '+=,.@-_' characters role_name='GitLab-GitLab_Role', assumed_by=iam.ServicePrincipal('ec2.amazonaws.com'), managed_policies=[policy]) folder = Path(__file__).parent.parent / 'user_data' user_data = ec2.UserData.for_linux() user_data.add_commands( 'apt install unzip', 'curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "aws_cli_v2.zip"', 'unzip aws_cli_v2.zip', 'sudo ./aws/install', 'aws --version') asset = Asset(self, 'asset:gitlab.rb', path=str(folder / 'gitlab.rb')) asset.grant_read(role) user_data.add_s3_download_command(bucket=asset.bucket, bucket_key=asset.s3_object_key, local_file='/etc/gitlab/gitlab.rb') asset = Asset(self, 'asset:userdata', path=str(folder / 'gitlab.sh')) asset.grant_read(role) path = user_data.add_s3_download_command( bucket=asset.bucket, bucket_key=asset.s3_object_key) user_data.add_execute_file_command(file_path=path, arguments='--verbose -y') # asset = Asset( # self, 'asset:prometheus:rules', path=str(folder / 'gitlab.rules.json')) template = ec2.LaunchTemplate( self, 'template', # Use alphanumeric and '-()./_' characters launch_template_name='GitLab/GitLab_LaunchTemplate', cpu_credits=ec2.CpuCredits.STANDARD, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM), machine_image=ec2.MachineImage.lookup( name='ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*', owners=['099720109477']), role=role, security_group=security_group, user_data=user_data, block_devices=[ ec2.BlockDevice(device_name='/dev/sda1', volume=ec2.BlockDeviceVolume.ebs( volume_size=8, volume_type=ec2.EbsDeviceVolumeType.GP3, delete_on_termination=True, )), ec2.BlockDevice(device_name='/dev/sdf', volume=ec2.BlockDeviceVolume.ebs( volume_size=20, volume_type=ec2.EbsDeviceVolumeType.GP3, delete_on_termination=False, )) ]) instance = ec2.CfnInstance( self, 'instance', launch_template=ec2.CfnInstance. LaunchTemplateSpecificationProperty( version=template.latest_version_number, launch_template_id=template.launch_template_id, ), subnet_id=subnets[0].subnet_id) zone = route53.HostedZone.from_lookup(self, 'zone', domain_name=DOMAIN) route53.CnameRecord(self, 'cname', record_name='gitlab', domain_name=instance.attr_public_dns_name, zone=zone, ttl=cdk.Duration.minutes(5)) self.vpc = vpc self.security_group = security_group