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"))
Beispiel #2
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"))
Beispiel #3
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # import default VPC
        #vpc = aws_ec2.Vpc.from_lookup(self, 'VPC', is_default=True)
        vpc = aws_ec2.Vpc(self, 'EKS-CDK-VPC', cidr='10.0.0.0/16', nat_gateways=1)

        # create an admin role
        eks_admin_role = aws_iam.Role(self, 'AdminRole',
                                      assumed_by=aws_iam.AccountPrincipal(
                                          account_id=self.account)
                                      )
        # create the cluster
        cluster = aws_eks.Cluster(self, 'cluster',
                                  masters_role=eks_admin_role,
                                  vpc=vpc,
                                  default_capacity=0,
                                  version='1.14',
                                  output_cluster_name=True
                                  )

        cluster.add_capacity('ondemand', instance_type=aws_ec2.InstanceType('t3.large'),
                             max_capacity=1,
                             bootstrap_options=aws_eks.BootstrapOptions(
                                 kubelet_extra_args='--node-labels myCustomLabel=od'
        )
        )

        cluster.add_capacity('spot', instance_type=aws_ec2.InstanceType('t3.large'),
                             max_capacity=1,
                             spot_price='0.1094',
                             bootstrap_options=aws_eks.BootstrapOptions(
                                 kubelet_extra_args='--node-labels myCustomLabel=spot'
        )
        )
Beispiel #4
0
    def __init__(self, scope: Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # This resource alone will create a private/public subnet in each AZ as well as nat/internet gateway(s)
        vpc = ec2.Vpc(self, "VPC")

        # To create number of Batch Compute Environment
        count = 3

        batch_ce = []

        # For loop to create Batch Compute Environments
        for i in range(count):
            name = "MyBatchARM64Env" + str(i)
            batch_environment = batch.ComputeEnvironment(
                self,
                name,
                compute_resources=batch.ComputeResources(
                    type=batch.ComputeResourceType.SPOT,
                    bid_percentage=75,
                    instance_types=[
                        ec2.InstanceType("a1.medium"),
                        ec2.InstanceType("a1.large")
                    ],
                    image=ecs.EcsOptimizedImage.amazon_linux2(
                        ecs.AmiHardwareType.ARM),
                    vpc_subnets=ec2.SubnetSelection(
                        subnet_type=ec2.SubnetType.PRIVATE_WITH_NAT),
                    vpc=vpc))

            batch_ce.append(
                batch.JobQueueComputeEnvironment(
                    compute_environment=batch_environment, order=i))

        # Create AWS Batch Job Queue and associate all Batch CE.
        self.batch_queue = batch.JobQueue(self,
                                          "JobQueueArm64",
                                          compute_environments=batch_ce)

        # Create Job Definition to submit job in batch job queue.
        batch_jobDef = batch.JobDefinition(
            self,
            "MyJobDefArm64",
            job_definition_name="CDKJobDefArm64",
            container=batch.JobDefinitionContainer(
                image=ecs.ContainerImage.from_registry(
                    "public.ecr.aws/amazonlinux/amazonlinux:latest"),
                command=["sleep", "60"],
                memory_limit_mib=512,
                vcpus=1),
        )

        # Output resources
        CfnOutput(self, "BatchJobQueue", value=self.batch_queue.job_queue_name)
        CfnOutput(self,
                  "JobDefinition",
                  value=batch_jobDef.job_definition_name)
    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))
    def __init__(self, scope: core.Construct, name: str, vpc: ec2.IVpc, **kwargs) -> None:
        super().__init__(scope, name, **kwargs)

        cluster = eks.Cluster(
            self, 'jenkins-workshop-eks-control-plane',
            vpc=vpc,
            default_capacity=0
        )

        asg_worker_nodes = cluster.add_capacity(
            'worker-node',
            instance_type=ec2.InstanceType('t3.medium'),
            desired_capacity=2,
        )

        asg_jenkins_slave = cluster.add_capacity(
            'worker-node-jenkins-slave',
            instance_type=ec2.InstanceType('t3.medium'),
            desired_capacity=1,
            bootstrap_options=eks.BootstrapOptions(
                kubelet_extra_args='--node-labels jenkins=slave --register-with-taints jenkins=slave:NoSchedule',
                docker_config_json=read_docker_daemon_resource('kubernetes_resources/docker-daemon.json')
            )
        )
        asg_jenkins_slave.add_to_role_policy(iam.PolicyStatement(
            actions=[
                'ecr:CompleteLayerUpload',
                'ecr:InitiateLayerUpload',
                'ecr:PutImage',
                'ecr:UploadLayerPart'
                ],
            resources=["*"]
            )
        )

        asg_worker_nodes.connections.allow_from(
            asg_jenkins_slave,
            ec2.Port.all_traffic()
        )
        asg_jenkins_slave.connections.allow_from(
            asg_worker_nodes,
            ec2.Port.all_traffic()
        )

        eks_master_role = iam.Role(
            self, 'AdminRole',
            assumed_by=iam.ArnPrincipal(get_eks_admin_iam_username())
        )

        cluster.aws_auth.add_masters_role(eks_master_role)

        helm_tiller_rbac = eks.KubernetesResource(
            self, 'helm-tiller-rbac',
            cluster=cluster,
            manifest=read_k8s_resource('kubernetes_resources/helm-tiller-rbac.yaml')
        )
    def __init__(self, scope: core.Construct, id: str, props, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = props['vpc']
        internal_sg = props['internal_sg']
        bastion_sg = props['bastion_sg']

        # Bastion用Linux
        bastion_linux = ec2.Instance(
            self, 'BastionLinux',
            instance_type=ec2.InstanceType('t3.micro'),
            machine_image=ec2.MachineImage.latest_amazon_linux(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2),
            key_name=self.node.try_get_context('key_name'),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=internal_sg
        )
        bastion_linux.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name('AmazonSSMManagedInstanceCore'))
        bastion_linux.add_security_group(bastion_sg)

        # Bastion用Windows
        bastion_windows = ec2.Instance(
            self, 'BastionWindows',
            instance_type=ec2.InstanceType('t3.large'),
            machine_image=ec2.MachineImage.latest_windows(
                version=ec2.WindowsVersion.WINDOWS_SERVER_2016_JAPANESE_FULL_BASE),
            key_name=self.node.try_get_context('key_name'),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=internal_sg
        )
        bastion_windows.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name('AmazonSSMManagedInstanceCore'))
        bastion_windows.add_security_group(bastion_sg)

        # Radius用EC2ホスト
        radius_host = ec2.Instance(
            self, 'RadiusHost',
            instance_type=ec2.InstanceType('t3.small'),
            machine_image=ec2.MachineImage.latest_amazon_linux(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2),
            key_name=self.node.try_get_context('key_name'),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE),
            security_group=internal_sg
        )
        radius_host.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name('AmazonSSMManagedInstanceCore'))

        self.output_props = props.copy()
    def create_eks(self, vpc):
        # create eks cluster with amd nodegroup
        cluster = eks.Cluster(
            self,
            "EKS",
            vpc=vpc,
            version=eks.KubernetesVersion.V1_18,
            default_capacity_instance=ec2.InstanceType("m5.large"),
            default_capacity=1)
        # add arm/graviton nodegroup
        cluster.add_nodegroup_capacity(
            "graviton",
            desired_size=1,
            instance_type=ec2.InstanceType("m6g.large"),
            nodegroup_name="graviton",
            node_role=cluster.default_nodegroup.role)

        # add secret access to eks node role
        cluster.default_nodegroup.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name(
                "SecretsManagerReadWrite"))

        # create service account
        sa = cluster.add_service_account("LBControllerServiceAccount",
                                         name="aws-load-balancer-controller",
                                         namespace="kube-system")
        sa_annotated = self.add_helm_annotation(cluster, sa)

        # create policy for the service account
        statements = []
        with open('backend/iam_policy.json') as f:
            data = json.load(f)
            for s in data["Statement"]:
                statements.append(iam.PolicyStatement.from_json(s))
        policy = iam.Policy(self, "LBControllerPolicy", statements=statements)
        policy.attach_to_role(sa.role)

        # add helm charts
        ingress = cluster.add_helm_chart(
            "LBIngress",
            chart="aws-load-balancer-controller",
            release="aws-load-balancer-controller",
            repository="https://aws.github.io/eks-charts",
            namespace="kube-system",
            values={
                "clusterName": cluster.cluster_name,
                "serviceAccount.name": "aws-load-balancer-controller",
                "serviceAccount.create": "false"
            })
        ingress.node.add_dependency(sa_annotated)

        return cluster
Beispiel #9
0
    def __init__(self, scope: core.Construct, construct_id: str, vpc: ec2.Vpc,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # The code that defines your stack goes here
        env_name = self.node.try_get_context("env")
        eks_role = iam.Role(
            self,
            "eksadmin",
            assumed_by=iam.ServicePrincipal(service='ec2.amazonaws.com'),
            role_name='eks-cluster-role',
            managed_policies=[
                iam.ManagedPolicy.from_aws_managed_policy_name(
                    managed_policy_name='AdministratorAccess')
            ])
        eks_instance_profile = iam.CfnInstanceProfile(
            self,
            'instanceprofile',
            roles=[eks_role.role_name],
            instance_profile_name='eks-cluster-role')

        cluster = eks.Cluster(
            self,
            'prod',
            cluster_name='ie-prod-snow-common',
            version=eks.KubernetesVersion.V1_19,
            vpc=vpc,
            vpc_subnets=[
                ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE)
            ],
            default_capacity=0,
            masters_role=eks_role)

        nodegroup = cluster.add_nodegroup_capacity(
            'eks-nodegroup',
            instance_types=[
                ec2.InstanceType('t3.large'),
                ec2.InstanceType('m5.large'),
                ec2.InstanceType('c5.large')
            ],
            disk_size=50,
            min_size=2,
            max_size=2,
            desired_size=2,
            subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE),
            remote_access=eks.NodegroupRemoteAccess(
                ssh_key_name='ie-prod-snow-common'),
            capacity_type=eks.CapacityType.SPOT)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        hensu = var()

        for subnetInfo in hensu.subnetInfoArray:
            subnetCfg = ec2.SubnetConfiguration(name=subnetInfo[0],
                                                subnet_type=subnetInfo[1],
                                                cidr_mask=subnetInfo[2])
            hensu.subnetCfgArray.append(subnetCfg)

        myVPC = self.createVpc(hensu.vpcCidr, hensu.vpcName,
                               hensu.enableDnsSupport, hensu.maxAZs,
                               hensu.natGateways, hensu.subnetCfgArray)

        mySecurityGroup = self.createSg(hensu.sgName, myVPC)
        for sgInfo in hensu.sgInfoArray:
            self.addSg(mySecurityGroup, sgInfo[0], sgInfo[1], sgInfo[2],
                       sgInfo[3], sgInfo[4])

        # subnet を指定しないとデフォルトのサブネットにインスタンスを作成してしまうので指定の必要がある
        for public_subnet in myVPC.public_subnets:
            myPublicInstance = self.createInstance(
                id=hensu.PublicInstanceName,
                image_id=hensu.PublicInstanceAmiId,
                instance_type=ec2.InstanceType(
                    hensu.PublicInstanceType).to_string(),
                subnet_id=public_subnet.subnet_id,
                security_group_ids=[mySecurityGroup.security_group_id],
            )

        # isolated には sg をかけないのでコメント扱い
        for isolated_subnet in myVPC.isolated_subnets:
            myIsolatedInstance = self.createInstance(
                id=hensu.IsolatedInstanceName,
                image_id=hensu.IsolatedInstanceAmiId,
                instance_type=ec2.InstanceType(
                    hensu.IsolatedInstanceType).to_string(),
                subnet_id=isolated_subnet.subnet_id,
                #security_group_ids=[mySecurityGroup.security_group_id]
            )

        self.outputCfn("myPublicInstance_attr_public_ip",
                       myPublicInstance.attr_public_ip)
        self.outputCfn("myPublicInstance_attr_private_ip",
                       myPublicInstance.attr_private_ip)
        self.outputCfn("myIsolatedInstance_attr_private_ip",
                       myIsolatedInstance.attr_private_ip)
Beispiel #11
0
    def __init__(self, scope: core.Construct, id: str, vpc: ec2.IVpc, config: dict, region: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self._region = region

        ### EC2 Server for Jenkins
        image = ec2.GenericLinuxImage(
            {
                region: config["ami_id"],
            },
        )

        self._role = iam.Role(self, "InstanceRole", assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"))
        for policy in config["iam_role_policies"]:
            self._role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name(policy))

        subnet = vpc.select_subnets(subnet_type=ec2.SubnetType.PRIVATE).subnets[0]
        subnet_selection = ec2.SubnetSelection(subnets=[subnet])

        self.security_group = ec2.SecurityGroup(
            self, "EC2SG",
            vpc=vpc
        )

        self._instance = ec2.Instance(
            self, "EC2",
            instance_type=ec2.InstanceType(config["instance_type"]),
            machine_image=image,
            vpc=vpc,
            vpc_subnets=subnet_selection,
            role=self._role,
            security_group=self.security_group
        )

        core.CfnOutput(self, "CodeServerInstanceID", value=self._instance.instance_id)
Beispiel #12
0
    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)
Beispiel #13
0
    def setup_emqx(self, N, vpc, zone, sg, key):
        self.emqx_vms = []
        for n in range(0, N):
            name = "emqx-%d" % n
            vm = ec2.Instance(self, id = name,
                              instance_type = ec2.InstanceType(instance_type_identifier=emqx_ins_type),
                              machine_image = linux_ami,
                              user_data = ec2.UserData.custom(user_data),
                              security_group = sg,
                              key_name = key,
                              vpc = vpc,
                              vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE),
            )

            self.emqx_vms.append(vm)

            r53.ARecord(self, id = name + '.int.emqx',
                        record_name = name + '.int.emqx',
                        zone = zone,
                        target = r53.RecordTarget([vm.instance_private_ip])
            )

            # tagging
            if self.user_defined_tags:
                core.Tags.of(vm).add(*self.user_defined_tags)
            core.Tags.of(vm).add('service', 'emqx')
    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, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #import vpc info
        vpc = aws_ec2.Vpc.from_lookup(self, "vpc", vpc_id="vpc-1f39b977")

        #import user-data scripts
        with open("userdata_scripts/setup.sh", mode="r") as file:
            user_data = file.read()

        #get latest ami from any region
        aws_linux_ami = aws_ec2.MachineImage.latest_amazon_linux(
            generation=aws_ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
            edition=aws_ec2.AmazonLinuxEdition.STANDARD,
            storage=aws_ec2.AmazonLinuxStorage.EBS,
            virtualization=aws_ec2.AmazonLinuxVirt.HVM)

        #ec2
        test_server = aws_ec2.Instance(
            self,
            "ec2id",
            instance_type=aws_ec2.InstanceType(
                instance_type_identifier="t2.micro"),
            instance_name="TestServer01",
            machine_image=aws_linux_ami,
            vpc=vpc,
            vpc_subnets=aws_ec2.SubnetSelection(
                subnet_type=aws_ec2.SubnetType.PUBLIC),
            key_name="SAA-C01",
            user_data=aws_ec2.UserData.custom(user_data))

        #add custom ebs for ec2
        test_server.instance.add_property_override(
            "BlockDeviceMappings", [{
                "DeviceName": "/dev/sdb",
                "Ebs": {
                    "VolumeSize": "10",
                    "VolumeType": "io1",
                    "Iops": "100",
                    "DeleteOnTermination": "true"
                }
            }])

        #allow web traffic
        test_server.connections.allow_from_any_ipv4(
            aws_ec2.Port.tcp(80), description="allow web traffic")

        # add permission to instances profile
        test_server.role.add_managed_policy(
            aws_iam.ManagedPolicy.from_aws_managed_policy_name(
                "AmazonSSMManagedInstanceCore"))
        test_server.role.add_managed_policy(
            aws_iam.ManagedPolicy.from_aws_managed_policy_name(
                "AmazonS3ReadOnlyAccess"))

        output_server_ip = core.CfnOutput(self,
                                          "serverip01",
                                          description="test server ip",
                                          value=test_server.instance_public_ip)
Beispiel #16
0
    def __init__(self, scope: core.Construct, id: str, vpc, 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 bastion host
        self.bastion = ec2.Instance(
            self,
            'Instance',
            instance_type=ec2.InstanceType("t3.small"),
            instance_name=f"{name}-bastion",
            key_name=f"{key}",
            machine_image=ubuntu_ami,
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(
                subnet_type=ec2.SubnetType.PRIVATE),
        )
        self.bastion.apply_removal_policy(core.RemovalPolicy.DESTROY)

        self.bastion.connections.allow_from_any_ipv4(
            port_range=ec2.Port.tcp(22),
            description='Allow public SSH connections')
        self.bastion.connections.allow_from_any_ipv4(
            port_range=ec2.Port.icmp_ping(),
            description='Allow public ICMP ping')

        core.CfnOutput(self,
                       f'{name}-private-ip',
                       value=self.bastion.instance_private_ip)
Beispiel #17
0
    def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prj_name = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")

        rds_sg = ec2.SecurityGroup(self,
                                   'rds-sg',
                                   vpc=vpc,
                                   security_group_name=prj_name + env_name +
                                   '-rds-sg',
                                   description="SG for RDS",
                                   allow_all_outbound=True)

        for subnet in vpc.private_subnets:
            rds_sg.add_ingress_rule(
                peer=ec2.Peer.ipv4(subnet.ipv4_cidr_block),
                connection=ec2.Port.tcp(3306),
                description='Allow all private subnet to access RDS')

        db_mysql = rds.DatabaseCluster(
            self,
            'mysql',
            default_database_name=prj_name + env_name,
            engine=rds.DatabaseClusterEngine.aurora_mysql(
                version=rds.AuroraMysqlEngineVersion.VER_5_7_12),
            instances=1,
            instance_props=rds.InstanceProps(
                vpc=vpc,
                instance_type=ec2.InstanceType(
                    instance_type_identifier="t3.small"),
                vpc_subnets=ec2.SubnetSelection(
                    subnet_type=ec2.SubnetType.PRIVATE)),
            removal_policy=core.RemovalPolicy.DESTROY)
Beispiel #18
0
    def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        snapshot_id = ssm.StringParameter.value_for_string_parameter(
            self, "graviton_rds_lab_snapshot")
        g2_db_mysql8 = rds.DatabaseInstanceFromSnapshot(
            self,
            "GravitonMySQL",
            engine=rds.DatabaseInstanceEngine.mysql(
                version=rds.MysqlEngineVersion.VER_8_0_21),
            instance_type=ec2.InstanceType("m6g.4xlarge"),
            snapshot_identifier=snapshot_id,
            vpc=vpc,
            multi_az=False,
            publicly_accessible=True,
            allocated_storage=100,
            storage_type=rds.StorageType.IO1,
            iops=5000,
            cloudwatch_logs_exports=["error", "general", "slowquery"],
            enable_performance_insights=True,
            deletion_protection=False,
            delete_automated_backups=True,
            backup_retention=core.Duration.days(0),
            vpc_subnets={"subnet_type": ec2.SubnetType.PUBLIC},
            parameter_group=rds.ParameterGroup.from_parameter_group_name(
                self,
                "para-group-mysql",
                parameter_group_name="default.mysql8.0"))

        g2_db_mysql8.connections.allow_default_port_from(
            ec2.Peer.ipv4(c9_ip), "Cloud9 MySQL Access")
        core.CfnOutput(self,
                       "G2MySQL8RDSInstanceId",
                       value=g2_db_mysql8.instance_identifier)
Beispiel #19
0
    def __init__(self, scope: core.Construct, id: str, vpc, sg, redissg,
                 kmskey, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        rdskey = kms.Key.from_key_arn(self, "rdskey", key_arn=kmskey)

        db_mysql = rds.DatabaseCluster(
            self,
            "Dev_MySQL",
            default_database_name="msadev",
            engine=rds.DatabaseClusterEngine.AURORA_MYSQL,
            engine_version="5.7.12",
            master_user=rds.Login(username="******"),
            instance_props=rds.InstanceProps(
                vpc=vpc,
                vpc_subnets=ec2.SubnetSelection(
                    subnet_type=ec2.SubnetType.ISOLATED),
                instance_type=ec2.InstanceType(
                    instance_type_identifier="t3.medium")),
            instances=1,
            parameter_group=rds.ClusterParameterGroup.
            from_parameter_group_name(
                self,
                "paramter-group-msadev",
                parameter_group_name="default.aurora-mysql5.7"),
            kms_key=rdskey)
        sgId = ec2.SecurityGroup.from_security_group_id(self, "sgid", sg)
        redis_sg = ec2.SecurityGroup.from_security_group_id(
            self, "redissgid", redissg)

        db_mysql.connections.allow_default_port_from(sgId,
                                                     "Access from Bastion")
        db_mysql.connections.allow_default_port_from(redis_sg,
                                                     "Access from Redis")
    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)
Beispiel #21
0
    def __init__(self, scope: core.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
        )

        cluster.add_capacity("DefaultAutoScalingGroup",
                             instance_type=ec2.InstanceType("t2.micro"))

        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")
            }
        )

        core.CfnOutput(
            self, "LoadBalancerDNS",
            value=ecs_service.load_balancer.load_balancer_dns_name
        )
Beispiel #22
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(self, "EKS_Kafka_PocClusterVPC")

        private_subnets = [snet_id.subnet_id for snet_id in vpc.private_subnets]
        bngi = msk.CfnCluster.BrokerNodeGroupInfoProperty(instance_type="kafka.m5.large",
                                                          client_subnets=private_subnets)

        msk_cluster = msk.CfnCluster(self, "EKS_KafkaPocMSKCluster",
                                     broker_node_group_info=bngi,
                                     cluster_name="EKSKafkaPOCMKSCluster",
                                     kafka_version="2.3.1",
                                     number_of_broker_nodes=3)

        eks_admin_role = iam.Role(self, "EKS_Kafka_PocCluster-AdminRole",
                                  assumed_by=iam.AccountPrincipal(account_id=self.account))

        eks_cluster = eks.Cluster(self, "EKS_Kafka_PocEKSCluster",
                                  cluster_name="EKS_Kafka_PocCluster",
                                  masters_role=eks_admin_role,
                                  kubectl_enabled=True,
                                  version="1.15",
                                  vpc=vpc)
        eks_cluster.add_capacity("worker", instance_type=ec2.InstanceType("t3.large"),
                                 min_capacity=1, max_capacity=10)
Beispiel #23
0
    def __init__(self, scope: core.Construct, id: str, props,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = props['vpc_dr']
        internal_sg = props['internal_sg_dr']
        bastion_sg = props['bastion_sg_dr']

        # Bastion用EC2ホスト
        bastion_windows = ec2.Instance(
            self,
            'Bastion',
            instance_type=ec2.InstanceType('t3.large'),
            machine_image=ec2.MachineImage.latest_windows(
                version=ec2.WindowsVersion.
                WINDOWS_SERVER_2016_JAPANESE_FULL_BASE),
            key_name=self.node.try_get_context('key_name'),
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            security_group=internal_sg)
        bastion_windows.role.add_managed_policy(
            iam.ManagedPolicy.from_aws_managed_policy_name(
                'AmazonSSMManagedInstanceCore'))
        bastion_windows.add_security_group(bastion_sg)

        self.output_props = props.copy()
Beispiel #24
0
    def __init__(self, scope: core.Construct, id: str, vpc, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        db_mysql = rds.DatabaseInstance(
            self,
            "MySQL",
            engine=rds.DatabaseInstanceEngine.mysql(
                version=rds.MysqlEngineVersion.VER_5_0_30),
            instance_type=ec2.InstanceType("m5.4xlarge"),
            vpc=vpc,
            multi_az=False,
            publicly_accessible=True,
            allocated_storage=100,
            storage_type=rds.StorageType.GP2,
            cloudwatch_logs_exports=["audit", "error", "general", "slowquery"],
            deletion_protection=False,
            delete_automated_backups=False,
            backup_retention=core.Duration.days(7),
            parameter_group=rds.ParameterGroup.from_parameter_group_name(
                self,
                "para-group-mysql",
                parameter_group_name="default.mysql5.7"))
        db_mysql.connections.allow_default_port_from(ec2.Peer.ipv4(c9_ip),
                                                     "Cloud9 MySQL Access")

        core.CfnOutput(self,
                       "RDSInstanceId",
                       value=db_mysql.instance_identifier)
Beispiel #25
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)
Beispiel #26
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = _ec2.Vpc.from_lookup(self, "importedVPC", vpc_id="vpc-d0a193aa")

        # Read BootStrap Script
        with open("bootstrap_scripts/install_httpd.sh", mode="r") as file:
            user_data = file.read()

        # WebServer Instance 001
        web_server = _ec2.Instance(
            self,
            "WebServer001Id",
            instance_type=_ec2.InstanceType(
                instance_type_identifier="t2.micro"),
            instance_name="WebServer001",
            machine_image=_ec2.MachineImage.generic_linux(
                {"us-east-1": "ami-0fc61db8544a617ed"}),
            vpc=vpc,
            vpc_subnets=_ec2.SubnetSelection(
                subnet_type=_ec2.SubnetType.PUBLIC),
            user_data=_ec2.UserData.custom(user_data))

        output_1 = core.CfnOutput(
            self,
            "webServer001Ip",
            description="WebServer Public Ip Address",
            value=f"http://{web_server.instance_public_ip}")

        # Allow Web Traffic to WebServer
        web_server.connections.allow_from_any_ipv4(
            _ec2.Port.tcp(80), description="Allow Web Traffic")
Beispiel #27
0
    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: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #vpc
        ecs_vpc = aws_ec2.Vpc(self, "EcsVpc", max_azs=2, nat_gateways=1)

        #ecs cluster
        ecs_cluster = aws_ecs.Cluster(self, "EcsCluster", vpc=ecs_vpc)

        #ecs cluster capacity
        ecs_cluster.add_capacity(
            "ecsClusterASGgroup",
            instance_type=aws_ec2.InstanceType("t2.micro"))

        #ecs attached to load balancer
        ecs_elb_service = aws_ecs_patterns.ApplicationLoadBalancedEc2Service(
            self,
            "EcsElb",
            cluster=ecs_cluster,
            memory_reservation_mib=512,
            task_image_options={
                "image": aws_ecs.ContainerImage.from_registry("httpd"),
                "environment": {
                    "ENVIRONMENT": "PROD"
                }
            })

        #ecs elb url output
        ecs_output = core.CfnOutput(
            self,
            "ecsOutput",
            value=f"{ecs_elb_service.load_balancer.load_balancer_dns_name}",
            description="elb url")
Beispiel #29
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
Beispiel #30
0
    def setup_etcd(self, vpc, zone, sg, key):
        for n in range(0, 3):
            # cdk bug?
            (cloud_user_data, )= ec2.UserData.for_linux(),
            cloud_user_data.add_commands('apt update',
                                         'apt install -y etcd-server etcd-client',
                                         "echo ETCD_INITIAL_ADVERTISE_PEER_URLS=http://etcd%d.int.emqx:2380 >> /etc/default/etcd" % n,
                                         'echo ETCD_LISTEN_PEER_URLS=http://0.0.0.0:2380 >> /etc/default/etcd',
                                         'echo ETCD_LISTEN_CLIENT_URLS=http://0.0.0.0:2379 >> /etc/default/etcd',
                                         "echo ETCD_ADVERTISE_CLIENT_URLS=http://etcd%d.int.emqx:2379 >> /etc/default/etcd" % n,
                                         "echo ETCD_NAME=infra%d >> /etc/default/etcd" % n,
                                         'echo ETCD_INITIAL_CLUSTER_STATE=new >> /etc/default/etcd',
                                         'echo ETCD_INITIAL_CLUSTER_TOKEN=emqx-cluster-1 >> /etc/default/etcd',
                                         'echo ETCD_INITIAL_CLUSTER="infra0=http://etcd0.int.emqx:2380,infra1=http://etcd1.int.emqx:2380,infra2=http://etcd2.int.emqx:2380" >> /etc/default/etcd',
                                         'systemctl restart etcd'
            )
            ins = ec2.Instance(self, id = "etsd.%d" % n,
                               instance_type=ec2.InstanceType(instance_type_identifier="t3a.nano"),
                               machine_image=linux_ami,
                               user_data=cloud_user_data,
                               security_group = sg,
                               key_name=key,
                               vpc = vpc
            )

            r53.ARecord(self, id = "etcd%d.int.emqx" % n,
                        record_name = "etcd%d.int.emqx" % n,
                        zone = zone,
                        target = r53.RecordTarget([ins.instance_private_ip])
            )

            if self.user_defined_tags:
                core.Tags.of(ins).add(*self.user_defined_tags)
            core.Tags.of(ins).add('service', 'etcd')