def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # create VPC w/ public and private subnets in 2 AZs # this also creates NAT Gateways in our public subnets vpc = ec2.Vpc(self, "NAT_Vpc", max_azs=2) # define the IAM role that will allow the EC2 instance to communicate with SSM role = iam.Role(self, "Role", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")) # arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore role.add_managed_policy( iam.ManagedPolicy( self, id='mp', managed_policy_name='AmazonSSMManagedInstanceCore', statements=[ iam.PolicyStatement(actions=['*'], resources=['*']) ])) # define user data script to update server software ssma_user_data = ec2.UserData.for_linux() ssma_user_data.add_commands('sudo yum update -y') # define user data script to create metadata.sh script ssma_user_data.add_commands('sudo touch metadata.sh') ssma_user_data.add_commands('sudo chmod 777 metadata.sh') ssma_user_data.add_commands( "sudo echo 'curl http://169.254.169.254/latest/meta-data/$1' > metadata.sh" ) ssma_user_data.add_commands("sudo echo 'VAR=' >> metadata.sh") ssma_user_data.add_commands("sudo echo 'echo $VAR' >> metadata.sh") # launch an EC2 instance in one of the private subnets instance = ec2.Instance( self, "PrivateInstance", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(), vpc_subnets={'subnet_type': ec2.SubnetType.PRIVATE}, role=role, user_data=ssma_user_data) # launch an EC2 instance in one of the public subnets instance = ec2.Instance( self, "PublicInstance", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(), vpc_subnets={'subnet_type': ec2.SubnetType.PUBLIC}, role=role, user_data=ssma_user_data)
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", max_azs=2 ) sg = ec2.SecurityGroup( self, "SG", description='Allow ssh access to ec2 instances', vpc=vpc ) sg.add_ingress_rule( peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22) ) asg = autoscaling.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO ), machine_image=ec2.AmazonLinuxImage(), desired_capacity=3, ) lb = elb.LoadBalancer( self, "LB", vpc=vpc, internet_facing=True, health_check={"port": 80} ) lb.add_target(asg) ec2instance = ec2.Instance( self, "EC2INSTANCE", vpc=vpc, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO ), machine_image=ec2.AmazonLinuxImage(), vpc_subnets={ 'subnet_type': ec2.SubnetType.PUBLIC }, security_group=sg, key_name="MyNVKeyPair" ) listener = lb.add_listener(external_port=80) listener.connections.allow_default_port_from_any_ipv4("Open to the world")
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, app: core.App, id: str) -> None: super().__init__(app, id) vpc = ec2.Vpc(self, "DemoVPC") data_blue = open("./httpd-blue.sh", "rb").read() httpd_blue = ec2.UserData.for_linux() httpd_blue.add_commands(str(data_blue, 'utf-8')) asg_blue = autoscaling.AutoScalingGroup( self, "ASG-Blue", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), user_data=httpd_blue, ) data_green = open("./httpd-green.sh", "rb").read() httpd_green = ec2.UserData.for_linux() httpd_green.add_commands(str(data_green, 'utf-8')) asg_green = autoscaling.AutoScalingGroup( self, "ASG-Green", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), user_data=httpd_green, ) lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc, internet_facing=True) listener = lb.add_listener("Listener", port=80) listener.add_targets("Target", port=80, targets=[asg_blue]) listener.connections.allow_default_port_from_any_ipv4( "Open to the world") asg_blue.scale_on_request_count("AModestLoad", target_requests_per_second=1) core.CfnOutput(self, "LoadBalancer", export_name="LoadBalancer", value=lb.load_balancer_dns_name)
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", max_azs=1 ) sg = ec2.SecurityGroup( self, "SG", description='Allow ssh access to ec2 instances', vpc=vpc ) sg.add_ingress_rule( peer=ec2.Peer.any_ipv4(), connection=ec2.Port.tcp(22) ) ec2instance = ec2.Instance( self, "EC2INSTANCE", vpc=vpc, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO ), machine_image=ec2.AmazonLinuxImage(), vpc_subnets={'subnet_type': ec2.SubnetType.PUBLIC}, security_group=sg, key_name="MyNVKeyPair" )
def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None: super().__init__(scope, id, **kwargs) 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) linux = ec2.MachineImage.generic_linux( {"ap-south-1": "ami-0b9d66ddb2a9f47d1"}) data = open("./scripts/userdata/userdata.sh", "rb").read() user_data = ec2.UserData.for_linux() user_data.add_commands(str(data, 'utf-8')) self.auto_scaling_group = autoscaling.AutoScalingGroup( self, "FirstASG", instance_type=ec2.InstanceType('t2.micro'), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), vpc=vpc, user_data=user_data, desired_capacity=6, key_name="ap-south-1", min_capacity=1, vpc_subnets=ec2.SubnetSelection( availability_zones=["ap-south-1a", "ap-south-1b"]))
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) with open("../iac-test-key.pub") as f: public_key = f.read() vpc = ec2.Vpc.from_lookup(self, "default_vpc", is_default=True) security_group = ec2.SecurityGroup( self, "test_sg", vpc=vpc, allow_all_outbound=True, ) security_group.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22)) image = ec2.AmazonLinuxImage() instance = ec2.Instance( self, "test_instance", machine_image=image, instance_type=ec2.InstanceType("t2.micro"), key_name="app_key-d2f12cf", vpc=vpc, security_group=security_group, ) public_ip = cdk.CfnOutput(self, "public_ip", value=instance.instance_public_ip)
def __init__(self, app: core.App, id: str) -> None: super().__init__(app, id) vpc = ec2.Vpc(self, "VPC") asg = autoscaling.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(), ) lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc, internet_facing=True) listener = lb.add_listener("Listener", port=80) listener.add_targets("Target", port=80, targets=[asg]) listener.connections.allow_default_port_from_any_ipv4( "Open to the world") asg.scale_on_request_count("AModestLoad", target_requests_per_second=1)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here self.vpc = ec2.Vpc(self, "VPC", cidr='10.10.0.0/16', max_azs=6, subnet_configuration=[ ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PRIVATE, name='Private', cidr_mask=19 ), ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PUBLIC, name='Public', cidr_mask=20 ), ec2.SubnetConfiguration( subnet_type=ec2.SubnetType.PRIVATE, name='Spare', cidr_mask=20, reserved=True ) ]) core.CfnOutput(self, "Output", value=self.vpc.vpc_id) self.bastion = ec2.BastionHostLinux(self, id, vpc = self.vpc, instance_name = 'bastione', instance_type = ec2.InstanceType('t3.micro'), machine_image = ec2.AmazonLinuxImage(), subnet_selection = ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), ) core.CfnOutput(self, 'bastion-id', value=self.bastion.instance_id)
def __init__(self, app: core.App, id: str, **kwargs) -> None: super().__init__(app, id, **kwargs) vpc = ec2.Vpc(self, "VPC") # 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") asg = autoscaling.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(), ) asg.add_security_group(my_sg) # add our security group, expects object ## Classic Elastic Load Balancer #lb = elb.LoadBalancer( # self, "ELB", # vpc=vpc, # internet_facing=True, # health_check={"port": 22} #) #lb.add_target(asg) # #listener = lb.add_listener( # external_port=8000, # external_protocol=elb.LoadBalancingProtocol.TCP, # internal_port=22, # internal_protocol=elb.LoadBalancingProtocol.TCP #) #listener.connections.allow_default_port_from_any_ipv4("Open to the world") # Network Load Balancer nlb = elbv2.NetworkLoadBalancer( self, "NLB", vpc=vpc, internet_facing=True, cross_zone_enabled=True, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)) my_target = elbv2.NetworkTargetGroup(self, "MyTargetGroup", port=22, vpc=vpc) listener = nlb.add_listener("Listener", port=8000, default_target_groups=[my_target]) my_target.add_target(asg)
def create_asg_by_service(self, name, userdata_path, key_name, port): role = self.output_props["default_role"] sg = self.output_props["sg"] nlb = self.output_props["nlb"] userdata = ec2.UserData.for_linux() with open(userdata_path, "rb") as f: userdata.add_commands(str(f.read(), 'utf-8')) asg = autoscaling.AutoScalingGroup( self, name, vpc=self.output_props['vpc'], instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), key_name=key_name, vpc_subnets=ec2.SubnetSelection( subnet_type=ec2.SubnetType.PRIVATE), user_data=userdata, security_group=sg, spot_price="0.005", min_capacity=1, max_capacity=3, desired_capacity=1, role=role, ) nlb.add_listener(name, port=port, protocol=lb.Protocol.TCP) \ .add_targets(name, port=port, targets=[asg])
def __init__(self, scope: core.Construct, id: str, vpc: ec2.Vpc, sg: ec2.ISecurityGroup, stage={}, **kwargs) -> None: super().__init__(scope, id, **kwargs) prefix_name = f'{stage["vpc_prefix"]}-{stage["stage_name"]}-{self.node.try_get_context("customer")}' bastion_host = ec2.Instance( self, f'{prefix_name}-public-bastion', instance_type=ec2.InstanceType('t3.micro'), machine_image=ec2.AmazonLinuxImage( edition=ec2.AmazonLinuxEdition.STANDARD, generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, virtualization=ec2.AmazonLinuxVirt.HVM, storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE), vpc=vpc, key_name=stage["key_name"], vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), security_group=sg) core.Tags.of(bastion_host).add("Name", f'{prefix_name}-public-bastion') core.CfnOutput(self, 'my-bastion-id', value=bastion_host.instance_id)
def __init__(self, scope: core.Construct, id: str, nw_stack: core.Stack, **kwargs) -> None: super().__init__(scope, id, **kwargs) ec2_sg = _ec2.SecurityGroup(self, id='test-ec2-instance-sg', vpc=nw_stack.app_vpc) bastion_sg = _ec2.SecurityGroup(self, id='bastion-sg', vpc=nw_stack.app_vpc) prv = _ec2.Instance(self, id='tgw_poc_instance', instance_type=_ec2.InstanceType('t3a.nano'), machine_image=_ec2.AmazonLinuxImage(), key_name=EC2Stack.KEY_PAIR, security_group=ec2_sg, instance_name='tgw_nat_test_instance', vpc=nw_stack.app_vpc, vpc_subnets=_ec2.SubnetSelection( subnet_type=_ec2.SubnetType.ISOLATED)) bastion = _ec2.Instance(self, id='tgw_poc_bastion', instance_type=_ec2.InstanceType('t3a.nano'), machine_image=_ec2.AmazonLinuxImage(), key_name=EC2Stack.KEY_PAIR, security_group=bastion_sg, instance_name='tgw_test_bastion', vpc=nw_stack.app_vpc, vpc_subnets=_ec2.SubnetSelection( subnet_type=_ec2.SubnetType.PUBLIC)) ssh_port = _ec2.Port(protocol=_ec2.Protocol.TCP, string_representation="tcp_22", from_port=EC2Stack.SSH_PORT, to_port=EC2Stack.SSH_PORT) bastion_sg.add_ingress_rule(peer=_ec2.Peer.ipv4(EC2Stack.SSH_IP), connection=ssh_port, description='Allow SSH access from SSH_IP') ec2_sg.add_ingress_rule( peer=bastion_sg, connection=ssh_port, description='Allow SSH access from bastion host')
def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None: super().__init__(scope, id, **kwargs) instance_type = ec2.InstanceType('m5.large') machine_image = ec2.AmazonLinuxImage( edition=ec2.AmazonLinuxEdition.STANDARD, generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2) key_name = 'kyn-key' allow_all_outbound = True user_data = ec2.UserData.for_linux() user_data.add_commands('sudo yum -y update', 'sudo yum install -y httpd', 'sudo systemctl start httpd') ## create security group # class aws_cdk.aws_ec2.SecurityGroup(scope, id, *, vpc, allow_all_outbound=None, description=None, security_group_name=None) cidr = vpc.vpc_cidr_block self.http_server_sg = ec2.SecurityGroup( self, 'http-server-sg', vpc=vpc, allow_all_outbound=True, security_group_name='http-server-sg') self.http_server_sg.add_ingress_rule( peer=ec2.Peer.ipv4('0.0.0.0/0'), connection=ec2.Port.tcp(80), description='Allow Inbound http Connection') self.http_server_sg.add_ingress_rule( peer=ec2.Peer.ipv4(cidr), connection=ec2.Port.all_traffic(), description='Allow Inbound Connection from VPC') security_group = self.http_server_sg ## create iam role for ec2 # class aws_cdk.aws_iam.Role(scope, id, *, assumed_by, external_id=None, external_ids=None, inline_policies=None, managed_policies=None, max_session_duration=None, path=None, permissions_boundary=None, role_name=None) managed_policies = [] policy = iam.ManagedPolicy.from_aws_managed_policy_name( 'AmazonSSMManagedInstanceCore') managed_policies.append(policy) role = iam.Role(self, 'http-server-role', assumed_by=iam.ServicePrincipal('ec2'), managed_policies=managed_policies, role_name=None) ## create http server instance # class aws_cdk.aws_ec2.Instance(scope, id, *, instance_type, machine_image, vpc, allow_all_outbound=None, availability_zone=None, instance_name=None, key_name=None, resource_signal_timeout=None, role=None, security_group=None, user_data=None, vpc_subnets=None) self.http_server = ec2.Instance( self, 'ec2', instance_type=instance_type, machine_image=machine_image, vpc=vpc, allow_all_outbound=allow_all_outbound, key_name=key_name, security_group=security_group, user_data=user_data, role=role, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC))
def __init__(self, scope: core.Construct, id: str, *, cidr_range: str, transit_gateway: ec2.CfnTransitGateway, role: iam.IRole, **kwargs): super().__init__(scope, id, **kwargs) vpc = ec2.Vpc( self, 'Vpc', cidr=cidr_range, max_azs=2, nat_gateways=1, ) sg = ec2.SecurityGroup( self, 'InstanceSecurityGroup', vpc=vpc, ) sg.add_ingress_rule(ec2.Peer.ipv4('10.0.0.0/8'), ec2.Port.tcp(80)) user_data = ec2.UserData.for_linux() user_data.add_commands(raw_user_data) ec2.Instance( self, 'Instance', role=role, vpc=vpc, security_group=sg, user_data=user_data, instance_type=ec2.InstanceType.of( instance_class=ec2.InstanceClass.BURSTABLE3_AMD, instance_size=ec2.InstanceSize.NANO, ), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, ), ) # TODO: replace by CDK construct when available attachment = ec2.CfnTransitGatewayAttachment( self, 'TransitGatewayAttachment', transit_gateway_id=transit_gateway.ref, vpc_id=vpc.vpc_id, subnet_ids=[subnet.subnet_id for subnet in vpc.private_subnets], ) for i, subnet in enumerate(vpc.private_subnets): # TODO: replace by CDK construct when available route = ec2.CfnRoute( self, 'TransitGatewayRoute{}'.format(i), route_table_id=subnet.route_table.route_table_id, transit_gateway_id=transit_gateway.ref, destination_cidr_block='10.0.0.0/8') route.node.add_dependency(attachment)
def __init__(self, scope: core.Construct, id: str, **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") # read parameters from SSM vpcid = ssm.StringParameter.value_from_lookup(self, "/cdk/ec2/vpc_id") # Get the existing VPC my_vpc = ec2.Vpc.from_lookup(self, "VPC", vpc_id=vpcid) # 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 # Create an EC2 instance with the above configuration ec2_instance = ec2.Instance( self, "my_ec2_instance", # instance_type=_ec2.InstanceType( # instance_type_identifier=instance_type), # machine_image=_ec2.MachineImage.latest_amazon_linux(), vpc=my_vpc, instance_name="MyInstance", # key_name=key_name, security_group=my_security_group, # role=my_session_mgmt_role, # user_data=_ec2.UserData.custom(user_data) )
def __init__(self, app: core.App, id: str, **kwargs) -> None: super().__init__(app, id, **kwargs) env_name = self.node.try_get_context('env') vpc = ec2.Vpc(self, id=f"{env_name}VPC") data = open("./pr_stacks/httpd.sh", "rb").read() httpd=ec2.UserData.for_linux() httpd.add_commands(str(data,'utf-8')) asg = autoscaling.AutoScalingGroup( self, id=f"{env_name}-ASG", vpc=vpc, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO ), machine_image=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), user_data=httpd, min_capacity=2, max_capacity=5 ) lb = elbv2.ApplicationLoadBalancer( self, "LB", vpc=vpc, internet_facing=True) """ Listeners: For every load balancer, regardless of the type used, you must configure at least one listener. The listener defines how your inbound connections are routed to your target groups based on ports and protocols set as conditions. The configurations of the listener itself differ slightly depending on which ELB you have selected. """ listener = lb.add_listener(id=f"{env_name}-Listener", port=80) """ Target Groups: A target group is simply a group of your resources that you want your ELB to route requests to, such as a fleet of EC2 instances. You can configure the ELB with a number of different target groups, each associated with a different listener configuration and associated rules. This enables you to route traffic to different resources based upon the type of request. """ listener.add_targets(id=f"{env_name}-Target", port=80, targets=[asg]) listener.connections.allow_default_port_from_any_ipv4(description="Open to the world") asg.scale_on_request_count(id=f"{env_name}-AModestLoad", target_requests_per_second=1) core.CfnOutput(self,"LoadBalancer",export_name="LoadBalancer",value=f"http://{lb.load_balancer_dns_name}")
def __init__(self, scope: core.Construct, id: str, ssh_key_name: str, **kw) -> None: super().__init__(scope, id, **kw) # start the web server (EC2 instance) in the default VPC vpc = ec2.Vpc.from_lookup(self, 'default_vpc', is_default=True) # create a security group for the web server that allows HTTP and SSH traffic sg = ec2.SecurityGroup(self, 'we_server_security_group', vpc=vpc, description='Allow HTTP ans SSH access', allow_all_outbound=True) sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22), 'SSH') sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(80), 'HTTP') sg.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(443), 'HTTPS') # create a bucket with all the web app components so they can be laoded into the # EC2 server later app_contents_bucket = s3.Bucket( self, 'cdk_lamp_server', public_read_access=True, removal_policy=core.RemovalPolicy.DESTROY) s3_deploy.BucketDeployment( self, 'deploy_webapp', sources=[s3_deploy.Source.asset('./web_app_contents')], destination_bucket=app_contents_bucket) # create an EC2 instance to work as a web server init_script = EC2_INIT_SCRIPT % dict( SOURCE_BUCKET_NAME=app_contents_bucket.bucket_name) web_server = ec2.Instance( self, 'web_server', instance_name='cdk_web_app', instance_type=ec2.InstanceType('t2.micro'), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), vpc=vpc, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), security_group=sg, user_data=ec2.UserData.custom(init_script), key_name=ssh_key_name) # grant access to the EC2 instance app_contents_bucket.grant_read(web_server) # show the web_server public address as an output core.CfnOutput(self, 'web-server-address', description='Web server public address', value=web_server.instance_public_dns_name)
def asg_app(self, vpc, asg_name): asg_app= asg.AutoScalingGroup(self, f"asg-app{asg_name}", vpc=vpc['vpc'], instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(), key_name="adl-keypair-dev-us-east-1", max_capacity=2 update_type=asg.UpdateType.ROLLING_UPDATE ) asg_app.add_to_role_policy(statement=iam.PolicyStatement( resources=["*"] actions=[s3:*]))
def __create_asg__(self): asg = autoscaling.AutoScalingGroup( self, "frontend-autoscaling-group", instance_type=ec2.InstanceType(INSTANCE_TYPE), machine_image=ec2.AmazonLinuxImage(), vpc=self.network_stack.vpc, vpc_subnets=ec2.SubnetSelection(one_per_az=True, subnet_type=ec2.SubnetType.PUBLIC), desired_capacity=2) asg.add_security_group(self.frontend_security_group) return asg
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 __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, vpc: ec2.Vpc, **kwargs) -> None: super().__init__(scope, id, **kwargs) # security group self.webapp_ec2_security_grp = ec2.SecurityGroup( self, "healthlake_webapp_ec2_security_grp", vpc=vpc, description="security group ec2 hosting ec2", allow_all_outbound=True, ) code_server_role = iam.Role( self, "CodeServerRole", assumed_by=iam.CompositePrincipal( iam.ServicePrincipal("ec2.amazonaws.com")), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( "AdministratorAccess") ]) # Open port 22, 80, and 443 self.webapp_ec2_security_grp.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22), "ssh") self.webapp_ec2_security_grp.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(80), "http") self.webapp_ec2_security_grp.add_ingress_rule( ec2.Peer.any_ipv4(), ec2.Port.tcp(443), "https", ) core.Tags.of(self.webapp_ec2_security_grp).add( "Name", "webapp_ec2_security_grp") ## EC2 instance to host the webapp self.webAppInstance = ec2.Instance( self, "healthlake-knowledge-webapp-ec2", instance_type=ec2.InstanceType(EC2_INSTANCE_TYPE), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), role=code_server_role, vpc=vpc, vpc_subnets={"subnet_type": ec2.SubnetType.PUBLIC}, key_name=KEY_PAIR_NAME, security_group=self.webapp_ec2_security_grp)
def __init__(self, app: core.App, id: str) -> None: super().__init__(app, id) vpc = ec2.Vpc(self, "VPC") data = open("./httpd.sh", "rb").read() httpd = ec2.UserData.for_linux() httpd.add_commands(str(data, 'utf-8')) asg = autoscaling.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of( ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO ), machine_image=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), user_data=httpd, ) lb = elbv2.ApplicationLoadBalancer( self, "LB", vpc=vpc, internet_facing=True) listener = lb.add_listener("Listener", port=80) listener.add_targets("Target", port=80, targets=[asg]) listener.connections.allow_default_port_from_any_ipv4("Open to the world") asg.scale_on_request_count("AModestLoad", target_requests_per_second=1) core.CfnOutput(self, "LoadBalancer", export_name="LoadBalancer", value=lb.load_balancer_dns_name) # === # # WAF # # === # # TODO #10 apply the web_acl to a resource # no method to apply the web_acl to a resource in version 1.75.0 web_acl = wafv2.CfnWebACL( scope_=self, id="waf", default_action=wafv2.CfnWebACL.DefaultActionProperty(), scope="REGIONAL", visibility_config=wafv2.CfnWebACL.VisibilityConfigProperty( cloud_watch_metrics_enabled=True, metric_name="waf-web-acl", sampled_requests_enabled=True ) )
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # The code that defines your stack goes here vpc = ec2.Vpc(self, "MyVPC") data = open("./user_data.sh", "rb").read() httpd = ec2.UserData.for_linux() httpd.add_commands(str(data, 'utf-8')) _asg = asg.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType( instance_type_identifier="t2.large"), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE, ), user_data=httpd, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), desired_capacity=2, auto_scaling_group_name="FirstASG") _asg.scale_on_cpu_utilization("ScaleOnCPU_Utilization", target_utilization_percent=50) alb = elb.ApplicationLoadBalancer( self, "ALB", vpc=vpc, vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC), load_balancer_name="FirstALB", internet_facing=True) listener = alb.add_listener("Listener", port=80) listener.add_targets("Target", port=80, targets=[_asg]) listener.connections.allow_from_any_ipv4( ec2.Port.tcp(80), "Allows HTTP from the World to call") core.CfnOutput(self, "LoadBalancer", export_name="LoadBalancer", value=alb.load_balancer_dns_name)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) vpc = ec2.Vpc(self, 'OurDemoVPC', cidr='10.1.0.0/16', max_azs=2, subnet_configuration=[ { 'cidrMask': 24, 'name': 'Web', 'subnetType': ec2.SubnetType.PUBLIC }, { 'cidrMask': 24, 'name': 'Application', 'subnetType': ec2.SubnetType.PRIVATE }, ]) asg = autoscaling.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage()) asg.add_user_data(""" yum update -y yum install httpd -y echo 'Hello from the CDK' > /var/www/html/index.html service httpd start chkconfig httpd on """) lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc, internet_facing=True) listener = lb.add_listener("Listener", port=80) listener.add_targets("Target", port=80, targets=[asg]) listener.connections.allow_default_port_from_any_ipv4( "Open to the world")
def __init__(self, scope: core.Construct, id: str, network_stack: core.Stack, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Create ServiceRole for EC2 instances; enable SSM usage ec2_instance_role = iam.Role( self, "Role", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"), managed_policies=[ iam.ManagedPolicy.from_aws_managed_policy_name( "AmazonSSMManagedInstanceCore") ], description="This is a custom role for assuming the SSM role") # Create security group ec2_sg = ec2.SecurityGroup(self, id='test-ec2-instance-sg', vpc=network_stack.vpc) # Create Ingress rule to allow ping ec2_sg.add_ingress_rule(ec2.Peer.ipv4('172.16.0.0/16'), ec2.Port.all_icmp()) # Create Instance ec2.Instance( self, 'Instance', role=ec2_instance_role, vpc=network_stack.vpc, instance_type=ec2.InstanceType.of( instance_class=ec2.InstanceClass.BURSTABLE3_AMD, instance_size=ec2.InstanceSize.NANO, ), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, ), security_group=ec2_sg) # Set the default route on the subnets to the TGW for subnet in network_stack.vpc.isolated_subnets: ec2.CfnRoute(self, id='vpc-route-all-tgw', route_table_id=subnet.route_table.route_table_id, destination_cidr_block='0.0.0.0/0', transit_gateway_id=network_stack.tgw.ref)
def __init__(self, scope: core.Construct, id: str,vpc: ec2.Vpc, sg: ec2.SecurityGroup, **kwargs) -> None: super().__init__(scope, id, **kwargs) bastion_host = ec2.Instance(self, 'bastion-host', instance_type=ec2.InstanceType('t2.micro'), machine_image=ec2.AmazonLinuxImage( edition=ec2.AmazonLinuxEdition.STANDARD, generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, virtualization=ec2.AmazonLinuxVirt.HVM, storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE ), vpc=vpc, key_name='devops', vpc_subnets=ec2.SubnetSelection( subnet_type=ec2.SubnetType.PUBLIC ), security_group=sg )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) lab03_vpc=ec2.Vpc(self,"Lab03-vpc",nat_gateways=1) #read and base64 encode userdata file data = open("../resource/httpd.sh", "rb").read() encodedBytes = base64.encodebytes(data) encodedStr = str(encodedBytes, "utf-8") #create UserData httpd=ec2.UserData.for_linux() httpd.add_commands(str(data,'utf-8')) #create AutoScaling Group ami=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2) #get AMAZON Linux 2 AMI #ec2.GenericWindowsImage({"cn-northwest-1":"ami-123123"}) asg=autoscaling.AutoScalingGroup( self, "aws-cdk-asg", vpc=lab03_vpc, #machine_image= ec2.GenericWindowsImage({"cn-northwest-1":"ami-00d0173a6c8a76d5f"}), #use custom ami machine_image= ami, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), user_data=httpd, min_capacity=1, desired_capacity=2, max_capacity=2, ) #create Elastic Load Balancer listener_port = 8080 lab03_alb=elb.ApplicationLoadBalancer(self,"lab03_alb",vpc=lab03_vpc,internet_facing=True) alb_listener=lab03_alb.add_listener("lab03_alb_listener",port=listener_port) alb_listener.add_targets('Target',port=80,targets=[asg]) #output ALB DNS core.CfnOutput(self,"Lab03ALB",export_name="Lab03ALB",value=lab03_alb.load_balancer_dns_name+":"+str(listener_port))
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # The code that defines your stack goes here #Creating vpc vpc = ec2.Vpc(self, "test_vpc_id") #Creating a basic web application to view data = open("./httpd.sh", "rb").read() httpd = ec2.UserData.for_linux() httpd.add_commands(str(data, 'utf-8')) # Auto-scaling group and instance creation asginstances = asg.AutoScalingGroup( self, "ASG", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage( generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2), desired_capacity=2, max_capacity=2, min_capacity=0, user_data=httpd) #Creating ALB and allowing internet access lb = alb.ApplicationLoadBalancer(self, 'LB', vpc=vpc, internet_facing=True) #ALB listening on port 80 listener = lb.add_listener("Listener", port=80) #Add the ASG as targets for the ALB listener.add_targets("Target", port=80, targets=[asginstances]) listener.connections.allow_default_port_from_any_ipv4( "Forwarding port 80 to the ASG") #Print out the ALB url to show web instance application core.CfnOutput(self, "LoadBalancer", export_name="Bananatag", value=lb.load_balancer_dns_name)