def __init__(self, scope: core.Construct, id: str, vpc_ip: str,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        if vpc_ip:
            print("VPC_IP " + vpc_ip)
            cidr = vpc_ip
        else:
            cidr = "10.0.0.0/16"

        # 01. VPC 생성
        cfVpc = ec2.CfnVPC(self,
                           "VPC",
                           cidr_block=cidr,
                           tags=[core.Tag(key="Name", value="CDKVPC")])

        # 02. Subnet 생성
        subnet_2a = ec2.CfnSubnet(
            self,
            id="subnet_2a",
            availability_zone="ap-northeast-2a",
            cidr_block="100.0.1.0/24",
            map_public_ip_on_launch=True,
            vpc_id=cfVpc.ref,
            tags=[core.Tag(key="Name", value="subnet-2a")])

        subnet_2c = ec2.CfnSubnet(
            self,
            id="subnet_2c",
            availability_zone="ap-northeast-2c",
            cidr_block="100.0.2.0/24",
            map_public_ip_on_launch=True,
            vpc_id=cfVpc.ref,
            tags=[core.Tag(key="Name", value="subnet-2c")])

        # 03. Internet Gateway 생성
        internet_gateway = ec2.CfnInternetGateway(
            self,
            id="Internet_Gateway_DNS_Example",
            tags=[core.Tag(key="Name", value="Internet_Gateway_for_DNS")])

        # 04. Internat Gateway Attach
        ec2.CfnVPCGatewayAttachment(self,
                                    id="vpcgw",
                                    vpc_id=cfVpc.ref,
                                    internet_gateway_id=internet_gateway.ref)

        #05. Route Table 생성
        route_table = ec2.CfnRouteTable(
            self,
            id="dns_example_routetable",
            vpc_id=cfVpc.ref,
            tags=[core.Tag(key="Name", value="Route_for_DNS")])

        #Route
        ec2.CfnRoute(self,
                     id="IGW_Route",
                     route_table_id=route_table.ref,
                     destination_cidr_block="0.0.0.0/0",
                     gateway_id=internet_gateway.ref)

        ec2.CfnSubnetRouteTableAssociation(self,
                                           id="DnsSubnet_Associate_2a",
                                           route_table_id=route_table.ref,
                                           subnet_id=subnet_2a.ref)

        ec2.CfnSubnetRouteTableAssociation(self,
                                           id="DnsSubnet_Associate_2c",
                                           route_table_id=route_table.ref,
                                           subnet_id=subnet_2c.ref)

        # 03. SG 생성
        sg = ec2.CfnSecurityGroup(self,
                                  id="sg-ssh",
                                  vpc_id=cfVpc.ref,
                                  group_description="Default Group",
                                  tags=[core.Tag(key="Name", value="DNS_SG")])
        #security_group_ingress=[ingress_ssh])
        #security_group_egress=[egress_all])

        ingress_ssh = ec2.CfnSecurityGroupIngress(self,
                                                  "SSH",
                                                  ip_protocol="tcp",
                                                  group_id=sg.ref,
                                                  from_port=22,
                                                  to_port=22,
                                                  cidr_ip="0.0.0.0/0")

        egress_all = ec2.CfnSecurityGroupEgress(
            self,
            id="OUTBOUND",
            group_id=sg.ref,
            ip_protocol="-1",
            #from_port=0,
            #to_port=65535,
            cidr_ip="0.0.0.0/0")

        # 04. DNS Server EC2 생성
        dns_server = ec2.MachineImage.generic_linux(
            {"ap-northeast-2": "ami-00d293396a942208d"})

        ec2.CfnInstance(self,
                        id="dns_master",
                        image_id=dns_server.get_image(self).image_id,
                        instance_type="t2.small",
                        key_name="SeoulRegion",
                        security_group_ids=[sg.ref],
                        subnet_id=subnet_2a.ref,
                        tags=[{
                            "key": "Name",
                            "value": "dns_master"
                        }])

        ec2.CfnInstance(self,
                        id="dns_slave",
                        image_id=dns_server.get_image(self).image_id,
                        instance_type="t2.small",
                        key_name="SeoulRegion",
                        security_group_ids=[sg.ref],
                        subnet_id=subnet_2c.ref,
                        tags=[{
                            "key": "Name",
                            "value": "dns_slave"
                        }])
Example #2
0
 def __init__(self, scope: core.Construct, id: str, data, iam_vars) -> None:
     super().__init__(scope, id)
     # VPC
     vpc = ec2.CfnVPC(self, "cdk-vpc", cidr_block=data["vpc"])
     igw = ec2.CfnInternetGateway(self, id="igw")
     ec2.CfnVPCGatewayAttachment(self,
                                 id="igw-attach",
                                 vpc_id=vpc.ref,
                                 internet_gateway_id=igw.ref)
     public_route_table = ec2.CfnRouteTable(self,
                                            id="public_route_table",
                                            vpc_id=vpc.ref)
     ec2.CfnRoute(self,
                  id="public_route",
                  route_table_id=public_route_table.ref,
                  destination_cidr_block="0.0.0.0/0",
                  gateway_id=igw.ref)
     public_subnets = []
     for i, s in enumerate(data["subnets"]["public"]):
         subnet = ec2.CfnSubnet(self,
                                id="public_{}".format(s),
                                cidr_block=s,
                                vpc_id=vpc.ref,
                                availability_zone=core.Fn.select(
                                    i, core.Fn.get_azs()),
                                map_public_ip_on_launch=True)
         public_subnets.append(subnet)
         ec2.CfnSubnetRouteTableAssociation(
             self,
             id="public_{}_association".format(s),
             route_table_id=public_route_table.ref,
             subnet_id=subnet.ref)
     eip = ec2.CfnEIP(self, id="natip")
     nat = ec2.CfnNatGateway(self,
                             id="nat",
                             allocation_id=eip.attr_allocation_id,
                             subnet_id=public_subnets[0].ref)
     private_route_table = ec2.CfnRouteTable(self,
                                             id="private_route_table",
                                             vpc_id=vpc.ref)
     ec2.CfnRoute(self,
                  id="private_route",
                  route_table_id=private_route_table.ref,
                  destination_cidr_block="0.0.0.0/0",
                  nat_gateway_id=nat.ref)
     private_subnets = []
     for i, s in enumerate(data["subnets"]["private"]):
         subnet = ec2.CfnSubnet(self,
                                id="private_{}".format(s),
                                cidr_block=s,
                                vpc_id=vpc.ref,
                                availability_zone=core.Fn.select(
                                    i, core.Fn.get_azs()),
                                map_public_ip_on_launch=False)
         private_subnets.append(subnet)
         ec2.CfnSubnetRouteTableAssociation(
             self,
             id="private_{}_association".format(s),
             route_table_id=private_route_table.ref,
             subnet_id=subnet.ref)
     # Security groups
     lb_sg = ec2.CfnSecurityGroup(self,
                                  id="lb",
                                  group_description="LB SG",
                                  vpc_id=vpc.ref)
     lambda_sg = ec2.CfnSecurityGroup(self,
                                      id="lambda",
                                      group_description="Lambda SG",
                                      vpc_id=vpc.ref)
     public_prefix = ec2.CfnPrefixList(self,
                                       id="cidr_prefix",
                                       address_family="IPv4",
                                       max_entries=1,
                                       prefix_list_name="public",
                                       entries=[{
                                           "cidr": "0.0.0.0/0",
                                           "description": "Public"
                                       }])
     _sg_rules = [{
         'sg':
         lb_sg.attr_group_id,
         'rules': [{
             "direction": "ingress",
             "description": "HTTP from Internet",
             "from_port": 80,
             "to_port": 80,
             "protocol": "tcp",
             "cidr_blocks": public_prefix.ref
         }, {
             "direction": "egress",
             "description": "LB to Lambda",
             "from_port": 80,
             "to_port": 80,
             "protocol": "tcp",
             "source_security_group_id": lambda_sg.attr_group_id
         }]
     }, {
         "sg":
         lambda_sg.attr_group_id,
         "rules": [{
             "direction": "ingress",
             "description": "HTTP from LB",
             "from_port": 80,
             "to_port": 80,
             "protocol": "tcp",
             "source_security_group_id": lb_sg.attr_group_id
         }, {
             "direction": "egress",
             "description": "All to Internet",
             "from_port": 0,
             "to_port": 65535,
             "protocol": "tcp",
             "cidr_blocks": public_prefix.ref
         }]
     }]
     for ruleset in _sg_rules:
         for rule in ruleset["rules"]:
             if rule["direction"] == "ingress":
                 ec2.CfnSecurityGroupIngress(
                     self,
                     id=rule["description"].replace(" ", "_"),
                     description=rule["description"],
                     to_port=rule["to_port"],
                     from_port=rule["from_port"],
                     ip_protocol=rule["protocol"],
                     group_id=ruleset["sg"],
                     source_prefix_list_id=rule["cidr_blocks"]
                     if "cidr_blocks" in rule else None,
                     source_security_group_id=rule[
                         "source_security_group_id"]
                     if "source_security_group_id" in rule else None)
             else:
                 ec2.CfnSecurityGroupEgress(
                     self,
                     id=rule["description"].replace(" ", "_"),
                     description=rule["description"],
                     to_port=rule["to_port"],
                     from_port=rule["from_port"],
                     ip_protocol=rule["protocol"],
                     group_id=ruleset["sg"],
                     destination_prefix_list_id=rule["cidr_blocks"]
                     if "cidr_blocks" in rule else None,
                     destination_security_group_id=rule[
                         "source_security_group_id"]
                     if "source_security_group_id" in rule else None)
     # IAM
     assume_policy_doc = iam.PolicyDocument()
     for statement in iam_vars["assume"]["Statement"]:
         _statement = iam.PolicyStatement(actions=[statement["Action"]], )
         _statement.add_service_principal(statement["Principal"]["Service"])
         assume_policy_doc.add_statements(_statement)
     role = iam.CfnRole(self,
                        id="iam_role",
                        path="/",
                        assume_role_policy_document=assume_policy_doc)
     role_policy_doc = iam.PolicyDocument()
     for statement in iam_vars["policy"]["Statement"]:
         _statement = iam.PolicyStatement(actions=statement["Action"],
                                          resources=["*"])
         role_policy_doc.add_statements(_statement)
     policy = iam.CfnPolicy(self,
                            id="iam_policy",
                            policy_document=role_policy_doc,
                            policy_name="cdkPolicy",
                            roles=[role.ref])
     # Lambda
     shutil.make_archive("../lambda", 'zip', "../lambda/")
     s3_client = boto3.client('s3')
     s3_client.upload_file("../lambda.zip", "cloudevescops-zdays-demo",
                           "cdk.zip")
     function = lmd.CfnFunction(self,
                                id="lambda_function",
                                handler="lambda.lambda_handler",
                                role=role.attr_arn,
                                runtime="python3.7",
                                code={
                                    "s3Bucket": "cloudevescops-zdays-demo",
                                    "s3Key": "cdk.zip"
                                },
                                vpc_config={
                                    "securityGroupIds": [lambda_sg.ref],
                                    "subnetIds":
                                    [s.ref for s in private_subnets]
                                },
                                environment={"variables": {
                                    "TOOL": "CDK"
                                }})
     # LB
     lb = alb.CfnLoadBalancer(self,
                              id="alb",
                              name="lb-cdk",
                              scheme="internet-facing",
                              type="application",
                              subnets=[s.ref for s in public_subnets],
                              security_groups=[lb_sg.ref])
     lmd.CfnPermission(self,
                       id="lambda_permis",
                       action="lambda:InvokeFunction",
                       function_name=function.ref,
                       principal="elasticloadbalancing.amazonaws.com")
     tg = alb.CfnTargetGroup(self,
                             id="alb_tg",
                             name="lambda-cdk",
                             target_type="lambda",
                             health_check_enabled=True,
                             health_check_interval_seconds=40,
                             health_check_path="/",
                             health_check_timeout_seconds=30,
                             targets=[{
                                 "id":
                                 function.get_att("Arn").to_string()
                             }],
                             matcher={"httpCode": "200"})
     alb.CfnListener(self,
                     id="listener",
                     default_actions=[{
                         "type": "forward",
                         "targetGroupArn": tg.ref
                     }],
                     load_balancer_arn=lb.ref,
                     port=80,
                     protocol="HTTP")
     core.CfnOutput(self, id="fqdn", value=lb.attr_dns_name)
Example #3
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        # instance role
        # instance profile
        # SecurityGroup
        publicsecuritygroup01 = aws_ec2.CfnSecurityGroup(
            self,
            'publicsecuritygroup01',
            group_description='publicsecuritygroup',
            group_name='publicsecuritygroup01',
            vpc_id=core.Fn.import_value('vpcid01'),
            tags=[core.CfnTag(key='Name', value='publicsecuritygroup01')])
        privatesecuritygroup01 = aws_ec2.CfnSecurityGroup(
            self,
            'privatesecuritygroup01',
            group_description='privatesecuritygroup',
            group_name='privatesecuritygroup01',
            vpc_id=core.Fn.import_value('vpcid01'),
            tags=[core.CfnTag(key='Name', value='privatesecuritygroup01')])
        # public Ingress
        aws_ec2.CfnSecurityGroupIngress(self,
                                        'publicsecuritygroupingress01',
                                        group_id=publicsecuritygroup01.ref,
                                        ip_protocol='tcp',
                                        cidr_ip='0.0.0.0/0',
                                        description='for bastion',
                                        from_port=22,
                                        to_port=22)
        # public Egress
        aws_ec2.CfnSecurityGroupEgress(
            self,
            'publicsecuritygroupegress01',
            group_id=publicsecuritygroup01.ref,
            ip_protocol='tcp',
            destination_security_group_id=privatesecuritygroup01.ref,
            description='for private',
            from_port=22,
            to_port=22)
        # private Ingress
        aws_ec2.CfnSecurityGroupIngress(
            self,
            'privatesecuritygroupingress01',
            group_id=privatesecuritygroup01.ref,
            ip_protocol='tcp',
            source_security_group_id=publicsecuritygroup01.ref,
            description='for bastion',
            from_port=22,
            to_port=22)
        # private Egress
        aws_ec2.CfnSecurityGroupEgress(self,
                                       'privatesecuritygroupegress01',
                                       group_id=privatesecuritygroup01.ref,
                                       ip_protocol='tcp',
                                       cidr_ip='0.0.0.0/0',
                                       description='for 443',
                                       from_port=443,
                                       to_port=443)
        aws_ec2.CfnSecurityGroupEgress(self,
                                       'privatesecuritygroupegress02',
                                       group_id=privatesecuritygroup01.ref,
                                       ip_protocol='tcp',
                                       cidr_ip='0.0.0.0/0',
                                       description='for 80',
                                       from_port=80,
                                       to_port=80)
        #        aws_ec2.CfnSecurityGroupEgress(self, 'privatesecuritygroupegress03', group_id=privatesecuritygroup01.ref, ip_protocol='tcp', cidr_ip='0.0.0.0/0', description='for 22', from_port=22, to_port=22)

        core.CfnOutput(self,
                       'output01',
                       value=publicsecuritygroup01.ref,
                       description='publicsecuritygroup',
                       export_name='publicsecuritygroup01')
        core.CfnOutput(self,
                       'output02',
                       value=privatesecuritygroup01.ref,
                       description='privatesecuritygroup',
                       export_name='privatesecuritygroup01')
Example #4
0
    def __init__(self, scope: core.Construct, id: str, vpc, subnet_id,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prefix = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")
        volumne_size = self.node.try_get_context("volumne_size")
        ec2_type = self.node.try_get_context("ec2_type")

        self.security_group = ec2.CfnSecurityGroup(
            self,
            id="web_server_sg",
            vpc_id=vpc.ref,
            group_name=env_name + '-' + prefix + '-www01',
            group_description="Web server security group",
            # security_group_ingress=[ingress_ssh],
            # security_group_egress=[egress_all],
            tags=[
                core.CfnTag(key="Name",
                            value=env_name + '-' + prefix + '-www01')
            ])

        # public Ingress
        ec2.CfnSecurityGroupIngress(self,
                                    'publicsecuritygroupingress01',
                                    group_id=self.security_group.ref,
                                    ip_protocol='tcp',
                                    cidr_ip='0.0.0.0/0',
                                    description='http',
                                    from_port=80,
                                    to_port=80)
        ec2.CfnSecurityGroupIngress(self,
                                    'publicsecuritygroupingress02',
                                    group_id=self.security_group.ref,
                                    ip_protocol='tcp',
                                    cidr_ip='0.0.0.0/0',
                                    description='ssh',
                                    from_port=22,
                                    to_port=22)
        # public Egress
        ec2.CfnSecurityGroupEgress(
            self,
            'publicsecuritygroupegress01',
            group_id=self.security_group.ref,
            ip_protocol='-1',
            cidr_ip='0.0.0.0/0'
            # destination_security_group_id=privatesecuritygroup01.ref,
            # description='for private',
            # from_port=22, to_port=22
        )
        # private Ingress

        image_id = ec2.AmazonLinuxImage(
            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image(
                self).image_id

        self.host = ec2.CfnInstance(
            self,
            env_name + '-' + prefix,
            # availability_zone="ap-northeast-1a",
            image_id=image_id,
            instance_type=ec2_type,
            key_name=key_name,
            #   credit_specification= { "cpu_credits" : "standard" },
            credit_specification=ec2.CfnInstance.CreditSpecificationProperty(
                cpu_credits="standard"),
            disable_api_termination=False,
            security_group_ids=[self.security_group.ref],
            subnet_id=subnet_id.ref,
            block_device_mappings=[{
                "deviceName": "/dev/xvda",
                "ebs": {
                    "volumeSize": volumne_size,
                }
            }],
            tags=[{
                "key": "Name",
                "value": env_name + '-' + prefix + '-www01'
            }])