コード例 #1
0
ファイル: app.py プロジェクト: kol999/alb-vpc-apache
    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)
コード例 #2
0
    def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        alb = elb.ApplicationLoadBalancer(self,
                                          "myALB",
                                          vpc=vpc,
                                          internet_facing=True,
                                          load_balancer_name="myALB")
        alb.connections.allow_from_any_ipv4(ec2.Port.tcp(80),
                                            "Internet access ALB 80")
        listener = alb.add_listener("my80", port=80, open=True)
        self.asg = autoscaling.AutoScalingGroup(
            self,
            "myASG",
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE),
            instance_type=ec2.InstanceType(instance_type_identifier=ec2_type),
            machine_image=linux_ami,
            #                                                key_name=key_name,
            user_data=ec2.UserData.custom(userdata),
            desired_capacity=1,
            min_capacity=1,
            max_capacity=2,
        )
        self.asg.connections.allow_from_any_ipv4(
            ec2.Port.tcp(22), "Access SSH port of EC2 in Autoscaling Instance")
        self.asg.connections.allow_from(
            alb, ec2.Port.tcp(80),
            "ALB access 80 port of EC2 in Autoscaling Group")
        listener.add_targets("addTargetGroup", port=80, targets=[self.asg])
        core.CfnOutput(self,
                       "OUTPUT_ALB_DNS",
                       value=alb.load_balancer_dns_name)
コード例 #3
0
 def create_asg(self, asg_type, vpc, instance_type, ami, userdata, role,
                key_name, capacity, security_group, device_name,
                volume_size):
     # ASG
     asg = autoscaling.AutoScalingGroup(
         self,
         "ASG_" + asg_type,
         auto_scaling_group_name="ASG_" + asg_type,
         vpc=vpc,
         vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
         instance_type=ec2.InstanceType(instance_type),
         machine_image=ami,
         user_data=userdata,
         role=role,
         key_name=key_name,
         desired_capacity=capacity,
         min_capacity=capacity,
         max_capacity=capacity,
         security_group=security_group,
         signals=autoscaling.Signals.wait_for_count(
             capacity, timeout=core.Duration.minutes(30)),
         block_devices=[
             autoscaling.BlockDevice(
                 device_name=device_name,
                 volume=autoscaling.BlockDeviceVolume.ebs(
                     volume_type=autoscaling.EbsDeviceVolumeType.GP2,
                     volume_size=volume_size,
                     delete_on_termination=True))
         ])
     return asg
コード例 #4
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, *kwargs)

        vpc = ec2.Vpc(
            self, "MyVpc",
            max_azs=2
        )

        asg = autoscaling.AutoScalingGroup(
            self, "MyFleet",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ecs.EcsOptimizedAmi(),
            associate_public_ip_address=True,
            update_type=autoscaling.UpdateType.REPLACING_UPDATE,
            desired_capacity=3,
            vpc=vpc,
            vpc_subnets={ 'subnet_type': ec2.SubnetType.PUBLIC },
        )

        cluster = ecs.Cluster(
            self, 'EcsCluster',
            vpc=vpc
        )

        cluster.add_auto_scaling_group(asg)
        cluster.add_capacity("DefaultAutoScalingGroup",
                             instance_type=ec2.InstanceType("t2.micro"))
コード例 #5
0
    def create_asg(self, vpc):
        asg = autoscaling.AutoScalingGroup(
            self,
            'SingleInstanceAsg',
            vpc=vpc,
            machine_image=ecs.EcsOptimizedAmi(),
            instance_type=ec2.InstanceType('t2.micro'),
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            associate_public_ip_address=True,
            # We only need 1 instance in the ASG
            max_capacity=1,
            desired_capacity=1,
        )

        security_group = ec2.SecurityGroup(
            self,
            'GhostSg',
            vpc=vpc,
        )

        # Allow ingress traffic to port 80
        security_group.add_ingress_rule(
            peer=ec2.Peer.any_ipv4(),
            connection=ec2.Port.tcp(80),
        )

        # Allow NFS traffic for mounting EFS volumes
        security_group.add_ingress_rule(peer=ec2.Peer.ipv4('10.0.0.0/16'),
                                        connection=ec2.Port.tcp(2049))

        asg.add_security_group(security_group)
        return asg
コード例 #6
0
ファイル: app.py プロジェクト: zelfick/aws-cdk-examples
    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)
コード例 #7
0
    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])
コード例 #8
0
  def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
    super().__init__(scope, id, **kwargs)
    ZachECSName= self.__class__.__name__
    vpc = ec2.Vpc(
      self, ZachECSName+"Vpc",
      max_azs=2
    )

    asg = autoscaling.AutoScalingGroup(
      self, ZachECSName+"SCG" ,
      instance_type=ec2.InstanceType("t3a.nano"),
      machine_image=ecs.EcsOptimizedAmi(),
      associate_public_ip_address=True,
      update_type=autoscaling.UpdateType.REPLACING_UPDATE,
      desired_capacity=3,
      vpc=vpc,
      vpc_subnets={'subnetType': ec2.SubnetType.PUBLIC}
    )

    cluster = ecs.Cluster(
      self, ZachECSName+"Cluster",
      vpc=vpc
    )

    cluster.add_auto_scaling_group(asg)
    cluster.add_capacity(ZachECSName+"AutoScalingGroup",
                         instance_type=ec2.InstanceType("t3a.nano"))
コード例 #9
0
 def _add_autoscaling_group(
   self,
   vpc: ec2.Vpc,
   public_subnet,
   security_group: ec2.SecurityGroup,
   key_name: str
 ) -> autoscaling.AutoScalingGroup:
   """
   Add autoscaling group for running ec2 instance automatically
   """
   Zach_Ec2_InstanceImage = ec2.GenericLinuxImage(ami_map={"ap-southeast-1":"ami-048a01c78f7bae4aa"})
   ZachInitInstall=ec2.UserData.for_linux()
   ZachInitInstall.add_commands("yum install -y psmisc nginx")
   group = autoscaling.AutoScalingGroup(
     self,
     'zach-autoscale',
     vpc=vpc,
     instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
     machine_image=Zach_Ec2_InstanceImage,
     max_capacity=2,
     vpc_subnets=public_subnet,
     associate_public_ip_address=True,
     key_name=key_name,
     user_data=ec2.UserData.add_commands(self,"yum install -y psmisc nginx")
   )
   group.add_security_group(security_group)
   core.CfnOutput(self, "ASG-GROUP-ARN", export_name="ASG-GROUP-ARN", value=group.auto_scaling_group_arn)
   core.CfnOutput(self, "ASG-GROUP", export_name="ASG-GROUP", value=group.auto_scaling_group_name)
   return group
コード例 #10
0
ファイル: cdk_stack_asg.py プロジェクト: yanmanr/cdk
    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"]))
コード例 #11
0
    def __create_asg(self, user_data: str, vpc: ec2.Vpc):
        subnets = ec2.SubnetSelection(one_per_az=True,
                                      subnet_type=ec2.SubnetType.PUBLIC)
        asg = autoscaling.AutoScalingGroup(
            self,
            id=common.generate_id("ImagizerAutoscalingGroup"),
            vpc=vpc,
            vpc_subnets=subnets,
            instance_type=ec2.InstanceType.of(
                instance_class=ec2.InstanceClass[variables.ASG_INSTANCE_TYPE],
                instance_size=ec2.InstanceSize[variables.ASG_INSTANCE_SIZE]),
            machine_image=ec2.GenericLinuxImage(
                ami_map={self.region: variables.IMAGIZER_AMI_ID}),
            user_data=ec2.UserData.custom(user_data),
            update_type=autoscaling.UpdateType.ROLLING_UPDATE,
            health_check=autoscaling.HealthCheck.ec2(
                grace=core.Duration.seconds(
                    variables.ASG_HEALTH_CHECK_GRACE_PERIOD)),
            cooldown=core.Duration.seconds(
                variables.ASG_HEALTH_CHECK_GRACE_PERIOD),
            min_capacity=variables.ASG_MIN_CAPACITY,
            max_capacity=variables.ASG_MAX_CAPACITY,
            rolling_update_configuration=autoscaling.
            RollingUpdateConfiguration(
                min_instances_in_service=variables.ASG_ROLL_OUT_BATCH_SIZE,
                max_batch_size=variables.ASG_ROLL_OUT_BATCH_SIZE,
                wait_on_resource_signals=True,
                pause_time=core.Duration.minutes(
                    variables.ASG_ROLL_OUT_PATCH_MINUTES)))

        common.add_tags(self, asg, variables.IMAGIZER_CLUSTER_TAGS)
        return asg
コード例 #12
0
    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)
コード例 #13
0
    def __init__(self, scope: Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, *kwargs)

        vpc = ec2.Vpc(self, "MyVpc", max_azs=2)

        cluster = ecs.Cluster(self, 'Ec2Cluster', vpc=vpc)

        asg = autoscaling.AutoScalingGroup(
            self,
            "DefaultAutoScalingGroup",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
            vpc=vpc,
        )
        capacity_provider = ecs.AsgCapacityProvider(self,
                                                    "AsgCapacityProvider",
                                                    auto_scaling_group=asg)
        cluster.add_asg_capacity_provider(capacity_provider)

        ecs_service = ecs_patterns.NetworkLoadBalancedEc2Service(
            self,
            "Ec2Service",
            cluster=cluster,
            memory_limit_mib=512,
            task_image_options={
                'image':
                ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
            })

        CfnOutput(self,
                  "LoadBalancerDNS",
                  value=ecs_service.load_balancer.load_balancer_dns_name)
コード例 #14
0
    def __init__(self, scope: core.Construct, id: str, vpc: ec2.IVpc,  **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Fargate cluster
        self.cluster = ecs.Cluster(
                scope = self,
                id = 'ecs-dev-cluster',
                cluster_name = 'ecs-dev-cluster',
                vpc = vpc
        )
        # Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
        self.auto_scaling_group1 = autoscaling.AutoScalingGroup(self, "ASG1",
            vpc=vpc,
            instance_type=ec2.InstanceType("t2.xlarge"),
            machine_image=ecs.EcsOptimizedImage.amazon_linux(),
            update_type=autoscaling.UpdateType.REPLACING_UPDATE,
            # Or use Amazon ECS-Optimized Amazon Linux 2 AMI
            # machineImage: EcsOptimizedImage.amazonLinux2(),
            desired_capacity=3
        )
            
        self.auto_scaling_group2 = autoscaling.AutoScalingGroup(self, "ASG2",
            vpc=vpc,
            instance_type=ec2.InstanceType("t2.xlarge"),
            machine_image=ecs.EcsOptimizedImage.amazon_linux(),
            update_type=autoscaling.UpdateType.REPLACING_UPDATE,
            # Or use Amazon ECS-Optimized Amazon Linux 2 AMI
            # machineImage: EcsOptimizedImage.amazonLinux2(),
            desired_capacity=3
        )

        self.cluster.add_auto_scaling_group(self.auto_scaling_group1)
        self.cluster.add_auto_scaling_group(self.auto_scaling_group2)

        self.lb = elbv2.ApplicationLoadBalancer(
            self, "LB",
            vpc=vpc,
            internet_facing=True
        )

        self.listener1 = self.lb.add_listener("Listener1", port=80)
        self.listener1.add_targets("Target", port=80, targets=[self.auto_scaling_group1])
        self.listener1.connections.allow_default_port_from_any_ipv4("Open to the world")

        self.listener2 = self.lb.add_listener("Listener2", port=8080)
        self.listener2.add_targets("Target", port=8080, targets=[self.auto_scaling_group2])
        self.listener2.connections.allow_default_port_from_any_ipv4("Open to the world")
コード例 #15
0
  def __init__(self,scope:core.Construct, id:str, infra:RtspBaseResourcesConstruct, subnet_group_name:str='Default', **kwargs) -> None:
    super().__init__(scope, id, **kwargs)
    
    self.container = ecs.ContainerImage.from_docker_image_asset(
      asset=ecr.DockerImageAsset(self,'RtspConnectorContainer',
        directory='src/rtsp/connector',
        file='Dockerfile'))

    self.task_role = iam.Role(self,'TaskRole',
      assumed_by=iam.ServicePrincipal(service='ecs-tasks'),
      role_name='ecs-video-producer-task@homenet-{}'.format(core.Stack.of(self).region),
      managed_policies=[
        iam.ManagedPolicy.from_aws_managed_policy_name(
          managed_policy_name='AmazonRekognitionFullAccess')
      ],
      description='Role for VideoSubnet Tasks')

    self.execution_role = iam.Role(self,'ExecutionRole',
      assumed_by=iam.ServicePrincipal(service='ecs-tasks'),
      role_name='ecs-rtsp-cluster-execution-role@homenet-{}'.format(core.Stack.of(self).region),      
      description='ECS Execution Role for '+ RtspBaseResourcesConstruct.__name__)

    self.cluster = ecs.Cluster(self,'RtspCluster',
      vpc=self.landing_zone.vpc,
      cluster_name='{}-rtsp-services'.format(infra.landing_zone.zone_name))

    # Tag all cluster resources for auto-domain join.
    core.Tags.of(self.cluster).add('domain','virtual.world')
    
    self.autoscale_group = autoscale.AutoScalingGroup(self,'WinASG',
      security_group=infra.landing_zone.security_group,
      instance_type= ec2.InstanceType.of(
        instance_class= ec2.InstanceClass.BURSTABLE3,
        instance_size=ec2.InstanceSize.SMALL),
      machine_image= ec2.MachineImage.generic_windows(ami_map={
        'us-east-1':'ami-0f93c815788872c5d'
      }),
      vpc= infra.landing_zone.vpc,
      role= self.execution_role,
      allow_all_outbound=True,
      associate_public_ip_address=False,
      #auto_scaling_group_name='{}-Rtsp-Windows'.format(landing_zone.zone_name),
      min_capacity= min_capacity,
      max_capacity= max_capacity,
      rolling_update_configuration= autoscale.RollingUpdateConfiguration(
        min_instances_in_service=0),
      update_type= autoscale.UpdateType.REPLACING_UPDATE,
      vpc_subnets=ec2.SubnetSelection(subnet_group_name=subnet_group_name))

    self.cluster.add_auto_scaling_group(
      auto_scaling_group= self.autoscale_group,
      can_containers_access_instance_role=True,
      task_drain_time= task_drain_time)

    # Enable management from Managed AD and SSM
    for policy in ['AmazonSSMDirectoryServiceAccess','AmazonSSMManagedInstanceCore']:
      self.autoscale_group.role.add_managed_policy(
        iam.ManagedPolicy.from_aws_managed_policy_name(
          managed_policy_name=policy))
コード例 #16
0
    def __init__(self, scope: core.Construct, id: str, vpc, bastion, config,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        prj_name = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")
        name = config['ec2']['name']
        key = config['ec2']['ssh_key']

        ubuntu_ami = ec2.GenericLinuxImage(
            {"ap-southeast-1": "ami-028be27cf930f7a43"})

        # Create security group for webapp instances
        webapp_sg = ec2.SecurityGroup(self,
                                      'webapp-sg',
                                      vpc=vpc,
                                      security_group_name=prj_name + env_name +
                                      '-webapp-sg',
                                      description="SG for webapp Instances",
                                      allow_all_outbound=True)

        webapp_sg.add_ingress_rule(
            peer=ec2.Peer.ipv4(f"{bastion.instance_private_ip}/32"),
            connection=ec2.Port.tcp(22),
            description='Allow all bastion instance to SSH')

        for subnet in vpc.public_subnets:
            webapp_sg.add_ingress_rule(
                peer=ec2.Peer.ipv4(subnet.ipv4_cidr_block),
                connection=ec2.Port.tcp(80),
                description=
                'Allow ELB public subnets to access webapp instances')

        # Create launch template and attach to autoscaling group
        webapp_launch_template = ec2.LaunchTemplate(
            self,
            'launch-template',
            detailed_monitoring=False,
            ebs_optimized=False,
            instance_type=ec2.InstanceType("t3.small"),
            launch_template_name=f"{name}-launch-template",
            key_name=f"{key}",
            machine_image=ubuntu_ami,
            security_group=webapp_sg)

        self.webapp_asg = autoscaling.AutoScalingGroup(
            self,
            'webapp-asg',
            vpc=vpc,
            auto_scaling_group_name=prj_name + env_name + '-webapp-asg',
            instance_type=ec2.InstanceType("t3.small"),
            machine_image=ubuntu_ami,
            min_capacity=1,
            max_capacity=1,
            desired_capacity=1,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE))
コード例 #17
0
    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}")
コード例 #18
0
 def create_auto_scaling_group(self):
     auto_scaling_group = autoscaling.AutoScalingGroup(
         self,
         guid('ASG-'),
         vpc=self.vpc,
         instance_type=self.DEFAULT_EC2_TYPE,
         machine_image=self.DEFAULT_IMAGE,
         min_capacity=1,
         max_capacity=5)
     auto_scaling_group.scale_on_cpu_utilization(
         "keepCpuUtilization", target_utilization_percent=10)
     return auto_scaling_group
コード例 #19
0
 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:*]))
コード例 #20
0
ファイル: FrontEndStack.py プロジェクト: nicoaws/aws-sa
 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
コード例 #21
0
    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")
コード例 #22
0
    def __init__(self, scope: core.Construct, construct_id: str, vpc,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        alb = elbv2.ApplicationLoadBalancer(self,
                                            "ALB",
                                            vpc=vpc,
                                            internet_facing=True)
        listener = alb.add_listener("Listener", port=80, open=True)

        security_group = ec2.SecurityGroup(
            self,
            "SecurityGroup",
            vpc=vpc,
            description="Allow access to ec2 instances",
            allow_all_outbound=True)
        security_group.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(80),
                                        "allow HTTP access from the world")
        security_group.add_ingress_rule(ec2.Peer.any_ipv4(), ec2.Port.tcp(22),
                                        "allow ssh access from the world")

        asg = autoscaling.AutoScalingGroup(
            self,
            "ASG",
            vpc=vpc,
            instance_type=ec2.InstanceType("t3.small"),
            machine_image=ec2.MachineImage.generic_linux(
                {"ap-east-1": "ami-0312f467545f742c4"}),
            min_capacity=2,
            max_capacity=5,
            security_group=security_group,
            #    block_devices=[autoscaling.BlockDevice(
            #        device_name="EBSApp",
            #        volume=autoscaling.BlockDeviceVolume.ebs(20,
            #                                                 encrypted=True
            #                                                 )
            #    )]
        )
        asg.scale_on_cpu_utilization("KeepSpareCPU",
                                     target_utilization_percent=70)

        group = listener.add_targets("ApplicationFleet",
                                     port=80,
                                     targets=[asg])

        # Output
        core.CfnOutput(self, "Output", value=alb.load_balancer_dns_name)
        self.security_group = security_group
        self.alb = alb
コード例 #23
0
ファイル: app.py プロジェクト: gsy0911/aws-cdk-small-examples
    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
            )
        )
コード例 #24
0
    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

        # creating a machine image
        ami = ec2.MachineImage.latest_amazon_linux(
            cpu_type=ec2.AmazonLinuxCpuType.X86_64,
            edition=ec2.AmazonLinuxEdition.STANDARD,
            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
            storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE,
        )

        # creating vpc
        vpc = ec2.Vpc.from_lookup(self, "vpc", is_default=True)

        # creating security group
        skull_sg = ec2.SecurityGroup(
            self,
            "myec2sg",
            vpc=vpc,
            security_group_name="skull-sg",
            description="sg for ec2 cdk example",
            allow_all_outbound=True,
        )

        # creating autoscaling group
        asg = autoscaling.AutoScalingGroup(
            self,
            "autoscaling",
            instance_type=ec2.InstanceType("t2.micro"),
            machine_image=ami,
            vpc=vpc,
            security_group=skull_sg,
        )

        # creating load balancer
        load_balancer = elb.LoadBalancer(
            self, "loadbalancer", internet_facing=True, vpc=vpc
        )

        # adding listeners to load balancer
        listener = load_balancer.add_listener(
            external_port=80, external_protocol=elb.LoadBalancingProtocol.HTTP
        )

        # add targets for load balancer such as the autoscaling group created above
        load_balancer.add_target(asg)
    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)
コード例 #26
0
ファイル: compute_stack.py プロジェクト: tstachlewski/cdk
    def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        #Creating Bastion
        bastion = ec2.BastionHostLinux(self,
                                       'webapp-bastion',
                                       vpc=vpc,
                                       subnet_selection=ec2.SubnetSelection(
                                           subnet_type=ec2.SubnetType.PUBLIC))
        bastion.instance.instance.add_property_override("KeyName", key_name)
        bastion.connections.allow_from_any_ipv4(ec2.Port.tcp(22),
                                                "Internet access SSH")

        #Creating AutoScaling group
        self.asg = autoscaling.AutoScalingGroup(
            self,
            "webapp-autoscaling",
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE),
            instance_type=ec2.InstanceType(instance_type_identifier=ec2_type),
            machine_image=linux_ami,
            key_name=key_name,
            user_data=ec2.UserData.custom(user_data),
            desired_capacity=2,
            min_capacity=2,
            max_capacity=2,
        )

        #Creating Load Balancer
        alb = elb.ApplicationLoadBalancer(self,
                                          "webapp-alb",
                                          vpc=vpc,
                                          internet_facing=True,
                                          load_balancer_name="webapp-alb")
        alb.connections.allow_from_any_ipv4(ec2.Port.tcp(80),
                                            "Internet access ALB 80")
        listener = alb.add_listener("my80", port=80, open=True)

        #Final Configuration
        self.asg.connections.allow_from(
            alb, ec2.Port.tcp(80),
            "ALB access 80 port of EC2 in Autoscaling Group")
        listener.add_targets("addTargetGroup", port=80, targets=[self.asg])

        core.CfnOutput(self, "Output", value=alb.load_balancer_dns_name)
コード例 #27
0
    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")
コード例 #28
0
    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)
コード例 #29
0
    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))
コード例 #30
0
 def _add_autoscaling_group(self, vpc: ec2.Vpc,
                            public_subnet: ec2.SubnetConfiguration,
                            security_group: ec2.SecurityGroup,
                            role: iam.Role) -> autoscaling.AutoScalingGroup:
     """
     Add autoscaling group for running ec2 instance automatically
     """
     group = autoscaling.AutoScalingGroup(
         self,
         'vpn-autoscale',
         vpc=vpc,
         instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2,
                                           ec2.InstanceSize.MICRO),
         machine_image=ec2.AmazonLinuxImage(),
         max_capacity=1,
         vpc_subnets=public_subnet,
         associate_public_ip_address=True,
         key_name='vpn-key',
         role=role)
     group.add_security_group(security_group)
     return group