Exemplo n.º 1
0
    def __init__(self, scope: core.Construct, id: str,
                 out_nw_stack: outNwStack, tgw_stack: tgwStack,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        # contexts
        PRJ = self.node.try_get_context("prj")
        CHILD_VPC_CIDR = self.node.try_get_context("child-vpc-cidr")

        # ### Resources
        # Routes for Natgw subnet
        ec2.CfnRoute(self,
                     "outNgwRouteDefault",
                     route_table_id=out_nw_stack.ngw_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     gateway_id=out_nw_stack.igw.ref)
        child_vpc_cidrs = [
            # (resource_id, cidr)
            ("outNgwRoute1", CHILD_VPC_CIDR)
        ]
        for resource_id, cidr in child_vpc_cidrs:
            ec2.CfnRoute(self,
                         resource_id,
                         route_table_id=out_nw_stack.ngw_rtb.ref,
                         destination_cidr_block=cidr,
                         transit_gateway_id=tgw_stack.tgw.ref)
        # Route for Tgw Subnet
        ec2.CfnRoute(self,
                     "outTgwRouteDefault",
                     route_table_id=out_nw_stack.tgw_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     nat_gateway_id=out_nw_stack.natgw.ref)
Exemplo n.º 2
0
    def __init__(self, scope: core.Construct, id: str,
                 app_nw_stack: appNwStack, out_nw_stack: outNwStack,
                 tgw_stack: tgwStack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        # contexts
        PRJ = self.node.try_get_context("prj")
        CIDR_APP_VPC = self.node.try_get_context("cidr-app-vpc")

        # ### Resources
        # App1: Tgw Subnet Route --> no route required
        # App1: App Subnet Route
        ec2.CfnRoute(self,
                     "appEc2Route1",
                     route_table_id=app_nw_stack.ec2_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     transit_gateway_id=tgw_stack.tgw.ref)
        # Out: Natgw Subnet Route
        ec2.CfnRoute(self,
                     "outNgwRoute1",
                     route_table_id=out_nw_stack.ngw_rtb.ref,
                     destination_cidr_block=CIDR_APP_VPC,
                     transit_gateway_id=tgw_stack.tgw.ref)
        ec2.CfnRoute(self,
                     "outNgwRoute2",
                     route_table_id=out_nw_stack.ngw_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     gateway_id=out_nw_stack.igw.ref)
        # Out: Tgw Subnet Route
        ec2.CfnRoute(self,
                     "outTgwRoute1",
                     route_table_id=out_nw_stack.tgw_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     nat_gateway_id=out_nw_stack.natgw.ref)
Exemplo n.º 3
0
    def __init__(self, scope: core.Construct, id: str, nw_stack: core.Stack,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        tgwRt = _ec2.CfnTransitGatewayRouteTable(
            self,
            id='TgwRt',
            transit_gateway_id=nw_stack.tgw.ref,
            tags=[core.CfnTag(key='Name', value='TGW-Nat-Rt')])

        _ec2.CfnTransitGatewayRouteTablePropagation(
            self,
            id='tgw-natvpc-propagation',
            transit_gateway_route_table_id=tgwRt.ref,
            transit_gateway_attachment_id=nw_stack.tgw_nat_attachment.ref)

        _ec2.CfnTransitGatewayRouteTableAssociation(
            self,
            id='tgw-natvpc-rt-association',
            transit_gateway_route_table_id=tgwRt.ref,
            transit_gateway_attachment_id=nw_stack.tgw_nat_attachment.ref)

        _ec2.CfnTransitGatewayRouteTablePropagation(
            self,
            id='tgw-appvpc-propagation',
            transit_gateway_route_table_id=tgwRt.ref,
            transit_gateway_attachment_id=nw_stack.tgw_app_attachment.ref)

        _ec2.CfnTransitGatewayRouteTableAssociation(
            self,
            id='tgw-appvpc-rt-association',
            transit_gateway_route_table_id=tgwRt.ref,
            transit_gateway_attachment_id=nw_stack.tgw_app_attachment.ref)

        # TGW Routing
        # All traffic is routed to NAT GW VPC
        _ec2.CfnTransitGatewayRoute(
            self,
            id='tgw-nat-route',
            transit_gateway_route_table_id=tgwRt.ref,
            destination_cidr_block='0.0.0.0/0',
            transit_gateway_attachment_id=nw_stack.tgw_nat_attachment.ref)

        for subnet in nw_stack.app_vpc.isolated_subnets:
            _ec2.CfnRoute(self,
                          id='app-vpc-route-all-tgw',
                          route_table_id=subnet.route_table.route_table_id,
                          destination_cidr_block='0.0.0.0/0',
                          transit_gateway_id=nw_stack.tgw.ref)

        for subnet in nw_stack.nat_vpc.public_subnets:
            _ec2.CfnRoute(
                self,
                id='nat-vpc-route-to-app',
                route_table_id=subnet.route_table.route_table_id,
                destination_cidr_block=nw_stack.app_vpc.vpc_cidr_block,
                transit_gateway_id=nw_stack.tgw.ref)
Exemplo n.º 4
0
def create_privagte_route_table(
        scope: core.Construct, vpc: aws_ec2.CfnVPC,
        nat_gateway: aws_ec2.CfnNatGateway) -> aws_ec2.CfnRouteTable:

    prefix = scope.node.try_get_context("prefix")
    az_name = [
        tag['value'] for tag in nat_gateway.tags.render_tags()
        if tag['key'] == 'Name'
    ].pop()
    az_end = az_name[-2:]
    route_table = aws_ec2.CfnRouteTable(
        scope,
        f'{prefix}-route-table-nat-{az_end}',
        vpc_id=vpc.ref,
        tags=[core.CfnTag(
            key='Name',
            value=f'{prefix}-route-table-nat',
        )],
    )

    aws_ec2.CfnRoute(
        scope,
        f'{prefix}-route-nat-{az_end}',
        route_table_id=route_table.ref,
        destination_cidr_block='0.0.0.0/0',
        nat_gateway_id=nat_gateway.ref,
    )
    return route_table
Exemplo n.º 5
0
    def __init__(self, scope: core.Construct, id: str, *, cidr_range: str,
                 transit_gateway: ec2.CfnTransitGateway, role: iam.IRole,
                 **kwargs):
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(
            self,
            'Vpc',
            cidr=cidr_range,
            max_azs=2,
            nat_gateways=1,
        )

        sg = ec2.SecurityGroup(
            self,
            'InstanceSecurityGroup',
            vpc=vpc,
        )
        sg.add_ingress_rule(ec2.Peer.ipv4('10.0.0.0/8'), ec2.Port.tcp(80))

        user_data = ec2.UserData.for_linux()
        user_data.add_commands(raw_user_data)

        ec2.Instance(
            self,
            'Instance',
            role=role,
            vpc=vpc,
            security_group=sg,
            user_data=user_data,
            instance_type=ec2.InstanceType.of(
                instance_class=ec2.InstanceClass.BURSTABLE3_AMD,
                instance_size=ec2.InstanceSize.NANO,
            ),
            machine_image=ec2.AmazonLinuxImage(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, ),
        )

        # TODO: replace by CDK construct when available
        attachment = ec2.CfnTransitGatewayAttachment(
            self,
            'TransitGatewayAttachment',
            transit_gateway_id=transit_gateway.ref,
            vpc_id=vpc.vpc_id,
            subnet_ids=[subnet.subnet_id for subnet in vpc.private_subnets],
        )

        for i, subnet in enumerate(vpc.private_subnets):
            # TODO: replace by CDK construct when available
            route = ec2.CfnRoute(
                self,
                'TransitGatewayRoute{}'.format(i),
                route_table_id=subnet.route_table.route_table_id,
                transit_gateway_id=transit_gateway.ref,
                destination_cidr_block='10.0.0.0/8')
            route.node.add_dependency(attachment)
Exemplo n.º 6
0
  def __add_peers(self)->None:
    for peer in self.peers:
      if peer == self.landing_zone:
        continue

      net_counter=0
      isolated = len(peer.vpc.isolated_subnets)
      private= len(peer.vpc.private_subnets)
      routes = core.Construct(self,'{}-I.{}/Pr.{}'.format(peer.zone_name,isolated, private))
      for net in self.landing_zone.vpc.isolated_subnets:
        net_counter+= 1
        ec2.CfnRoute(routes,'I.{}'.format(net_counter),
          route_table_id= net.route_table.route_table_id,
          destination_cidr_block=peer.cidr_block,
          transit_gateway_id=self.gateway.ref)
      for net in self.landing_zone.vpc.private_subnets:
        net_counter+= 1
        ec2.CfnRoute(routes,'Pr.{}'.format(net_counter),
          route_table_id= net.route_table.route_table_id,
          destination_cidr_block=peer.cidr_block,
          transit_gateway_id=self.gateway.ref)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # VPC with private and public subnets
        self.vpc = ec2.Vpc( self, "FargateVpc", max_azs=3)

        # import default VPC
        self.default_vpc = ec2.Vpc.from_lookup(self, "DefaultVPC",
            # This imports the default VPC but you can also
            # specify a 'vpcName' or 'tags'.
            is_default=True
        )
        self.default_vpc_cidr_block = '172.31.0.0/16'

        # peering connection
        self.peer = ec2.CfnVPCPeeringConnection(
                scope = self, 
                id = "VpcPeer",
                peer_vpc_id = self.default_vpc.vpc_id,
                vpc_id = self.vpc.vpc_id,
                peer_region = self.region
        )

        # routes
        ii = 0
        for subnet in itertools.chain(self.vpc.private_subnets,self.vpc.public_subnets):
            route = ec2.CfnRoute(self, 
                    "PeerRoute{0}".format(ii), 
                    route_table_id= subnet.route_table.route_table_id, 
                    destination_cidr_block= self.default_vpc_cidr_block, 
                    vpc_peering_connection_id= self.peer.ref 
            )
            ii = ii + 1
        subnet = self.default_vpc.public_subnets[0]
        route = ec2.CfnRoute(self, 
                "PeerRoute{0}".format(ii), 
                route_table_id= subnet.route_table.route_table_id, 
                destination_cidr_block= self.vpc.vpc_cidr_block, 
                vpc_peering_connection_id= self.peer.ref 
        )
Exemplo n.º 8
0
    def __init__(self, scope: core.Construct, id: str, vpc_id: str,
                 peer_vpc_id: str, owner_cidr: str,
                 vpc_peering_connection_id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Add route from owner to the peer
        peer = ec2.Vpc.from_lookup(self, 'PeerVpc', vpc_id=peer_vpc_id)
        for iter in peer.private_subnets:
            ec2.CfnRoute(self,
                         iter.subnet_id,
                         route_table_id=iter.route_table.route_table_id,
                         destination_cidr_block=owner_cidr,
                         vpc_peering_connection_id=vpc_peering_connection_id)
Exemplo n.º 9
0
    def __init__(self, scope: core.Construct, id: str,
                 app_nw_stack: appNwStack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        # contexts
        PRJ = self.node.try_get_context("prj")
        TGW_ID = self.node.try_get_context("tgw-id")

        # ### Resources
        # App: Tgw Subnet Route --> no route required
        # App: App Subnet Route
        ec2.CfnRoute(self,
                     "appEc2Route1",
                     route_table_id=app_nw_stack.ec2_rtb.ref,
                     destination_cidr_block="0.0.0.0/0",
                     transit_gateway_id=TGW_ID)
Exemplo n.º 10
0
def create_public_route_table(self, vpc, internet_gateway):

    # RouteTable of PublicSubnet
    route_table_public = _ec2.CfnRouteTable(
        self,
        'CfnRouteTablePublic',
        vpc_id=vpc.ref,
        tags=[
            CfnTag(key="Name", value='DEMO-ROUTE-TABLE-PUBLIC'),
        ])
    _ec2.CfnRoute(self,
                  'CfnRoutePublic',
                  route_table_id=route_table_public.ref,
                  destination_cidr_block="0.0.0.0/0",
                  gateway_id=internet_gateway.ref)
    return route_table_public
Exemplo n.º 11
0
def create_private_route_table(self, vpc, nat_gateway):

    # RouteTable of PrivateSubnet
    route_table_private = _ec2.CfnRouteTable(
        self,
        'CfnRouteTablePrivate',
        vpc_id=vpc.ref,
        tags=[
            CfnTag(key="Name", value='DEMO-ROUTE-TABLE-PRIVATE'),
        ])

    _ec2.CfnRoute(self,
                  'CfnRoutePrivate',
                  route_table_id=route_table_private.ref,
                  destination_cidr_block="0.0.0.0/0",
                  nat_gateway_id=nat_gateway.ref)
    return route_table_private
Exemplo n.º 12
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 network
        vpc = aws_ec2.CfnVPC(self, 'vpc', cidr_block='10.0.0.0/16', enable_dns_hostnames=True, enable_dns_support=True, instance_tenancy='default', tags=[core.CfnTag(key='Name',value='vpc')])
        internetgateway = aws_ec2.CfnInternetGateway(self, 'internetgateway', tags=[core.CfnTag(key='Name',value='internetgateway')])
        aws_ec2.CfnVPCGatewayAttachment(self, 'VPCGatewayAttachment', vpc_id=vpc.ref, internet_gateway_id=internetgateway.ref)

        # public network
        publicsubnet01 = aws_ec2.CfnSubnet(self, 'publicsubnet01', cidr_block='10.0.0.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='publicsubnet01')])
        publicsubnet02 = aws_ec2.CfnSubnet(self, 'publicsubnet02', cidr_block='10.0.1.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='publicsubnet02')])
        publicsubnet03 = aws_ec2.CfnSubnet(self, 'publicsubnet03', cidr_block='10.0.2.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='publicsubnet03')])
        publicroutetable01 = aws_ec2.CfnRouteTable(self, 'publicroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable01')])
        publicroutetable02 = aws_ec2.CfnRouteTable(self, 'publicroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable02')])
        publicroutetable03 = aws_ec2.CfnRouteTable(self, 'publicroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='publicroutetable03')])
        aws_ec2.CfnRoute(self, 'publicroute01', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable01.ref,)
        aws_ec2.CfnRoute(self, 'publicroute02', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable02.ref)
        aws_ec2.CfnRoute(self, 'publicroute03', destination_cidr_block='0.0.0.0/0', gateway_id=internetgateway.ref, route_table_id=publicroutetable03.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation01', route_table_id=publicroutetable01.ref, subnet_id=publicsubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation02', route_table_id=publicroutetable02.ref, subnet_id=publicsubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'publicsubnetroutetableassociation03', route_table_id=publicroutetable03.ref, subnet_id=publicsubnet03.ref)

        # private network
        privatesubnet01 = aws_ec2.CfnSubnet(self, 'privatesubnet01', cidr_block='10.0.11.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='privatesubnet01')])
        privatesubnet02 = aws_ec2.CfnSubnet(self, 'privatesubnet02', cidr_block='10.0.12.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='privatesubnet02')])
        privatesubnet03 = aws_ec2.CfnSubnet(self, 'privatesubnet03', cidr_block='10.0.13.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='privatesubnet03')])
        privateroutetable01 = aws_ec2.CfnRouteTable(self, 'privateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable01')])
        privateroutetable02 = aws_ec2.CfnRouteTable(self, 'privateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable02')])
        privateroutetable03 = aws_ec2.CfnRouteTable(self, 'privateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='privateroutetable03')])
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation01', route_table_id=privateroutetable01.ref, subnet_id=privatesubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation02', route_table_id=privateroutetable02.ref, subnet_id=privatesubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'privatesubnetroutetableassociation03', route_table_id=privateroutetable03.ref, subnet_id=privatesubnet03.ref)
        eip01 = aws_ec2.CfnEIP(self, 'eip01', tags=[core.CfnTag(key='Name',value='eip01')])
        eip02 = aws_ec2.CfnEIP(self, 'eip02', tags=[core.CfnTag(key='Name',value='eip02')])
        eip03 = aws_ec2.CfnEIP(self, 'eip03', tags=[core.CfnTag(key='Name',value='eip03')])
        natgateway01 = aws_ec2.CfnNatGateway(self, 'natgateway01', allocation_id=eip01.attr_allocation_id, subnet_id=publicsubnet01.ref, tags=[core.CfnTag(key='Name',value='natgateway01')])
        natgateway02 = aws_ec2.CfnNatGateway(self, 'natgateway02', allocation_id=eip02.attr_allocation_id, subnet_id=publicsubnet02.ref, tags=[core.CfnTag(key='Name',value='natgateway02')])
        natgateway03 = aws_ec2.CfnNatGateway(self, 'natgateway03', allocation_id=eip03.attr_allocation_id, subnet_id=publicsubnet03.ref, tags=[core.CfnTag(key='Name',value='natgateway03')])
        aws_ec2.CfnRoute(self, 'privateroute01', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway01.ref, route_table_id=privateroutetable01.ref) 
        aws_ec2.CfnRoute(self, 'privateroute02', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway02.ref, route_table_id=privateroutetable02.ref)
        aws_ec2.CfnRoute(self, 'privateroute03', destination_cidr_block='0.0.0.0/0' ,nat_gateway_id=natgateway03.ref, route_table_id=privateroutetable03.ref)

        # isolate network
        isolatesubnet01 = aws_ec2.CfnSubnet(self, 'isolatesubnet01', cidr_block='10.0.21.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name',value='isolatesubnet01')])
        isolatesubnet02 = aws_ec2.CfnSubnet(self, 'isolatesubnet02', cidr_block='10.0.22.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name',value='isolatesubnet02')])
        isolatesubnet03 = aws_ec2.CfnSubnet(self, 'isolatesubnet03', cidr_block='10.0.23.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name',value='isolatesubnet03')])
        isolateroutetable01 = aws_ec2.CfnRouteTable(self, 'isolateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable01')])
        isolateroutetable02 = aws_ec2.CfnRouteTable(self, 'isolateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable02')])
        isolateroutetable03 = aws_ec2.CfnRouteTable(self, 'isolateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name',value='isolateroutetable03')])
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation01', route_table_id=isolateroutetable01.ref, subnet_id=isolatesubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation02', route_table_id=isolateroutetable02.ref, subnet_id=isolatesubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation03', route_table_id=isolateroutetable03.ref, subnet_id=isolatesubnet03.ref)
    def __init__(self, scope: core.Construct, id: str,
                 network_stack: core.Stack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create ServiceRole for EC2 instances; enable SSM usage
        ec2_instance_role = iam.Role(
            self,
            "Role",
            assumed_by=iam.ServicePrincipal("ec2.amazonaws.com"),
            managed_policies=[
                iam.ManagedPolicy.from_aws_managed_policy_name(
                    "AmazonSSMManagedInstanceCore")
            ],
            description="This is a custom role for assuming the SSM role")

        # Create security group
        ec2_sg = ec2.SecurityGroup(self,
                                   id='test-ec2-instance-sg',
                                   vpc=network_stack.vpc)

        # Create Ingress rule to allow ping
        ec2_sg.add_ingress_rule(ec2.Peer.ipv4('172.16.0.0/16'),
                                ec2.Port.all_icmp())

        # Create Instance
        ec2.Instance(
            self,
            'Instance',
            role=ec2_instance_role,
            vpc=network_stack.vpc,
            instance_type=ec2.InstanceType.of(
                instance_class=ec2.InstanceClass.BURSTABLE3_AMD,
                instance_size=ec2.InstanceSize.NANO,
            ),
            machine_image=ec2.AmazonLinuxImage(
                generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2, ),
            security_group=ec2_sg)

        # Set the default route on the subnets to the TGW
        for subnet in network_stack.vpc.isolated_subnets:
            ec2.CfnRoute(self,
                         id='vpc-route-all-tgw',
                         route_table_id=subnet.route_table.route_table_id,
                         destination_cidr_block='0.0.0.0/0',
                         transit_gateway_id=network_stack.tgw.ref)
Exemplo n.º 14
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id)

        self._id = id
        self._routetable_id = kwargs['routetable_id']
        self._internetgateway_id = kwargs['internetgateway_id']

        try: kwargs['tags']
        except: self._tags_wk = None
        else: self._tags_wk = [core.CfnTag(key=kwargs['tags'][i]['key'] ,value=kwargs['tags'][i]['value']) if kwargs['tags'] else None for i in range(len(kwargs['tags']))]

        self._internetgateway_id = kwargs['internetgateway_id']
        self._route = aws_ec2.CfnRoute(self,
            self._id,
            gateway_id=self._internetgateway_id.ref,
            destination_cidr_block='0.0.0.0/0',
            route_table_id=self._routetable_id.ref
        )
Exemplo n.º 15
0
    def __init__(self, scope: core.Construct, id: str, vpc_id: str,
                 peer_vpc_id: str, peer_region: str, peer_cidr: str,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        owner = ec2.Vpc.from_lookup(self, 'OwnerVpc', vpc_id=vpc_id)
        self.peering = ec2.CfnVPCPeeringConnection(
            self,
            'PeerConnection',
            peer_region=peer_region,  # core.Stack.of(peer).region,
            peer_vpc_id=peer_vpc_id,  # peer.vpc_id,
            vpc_id=vpc_id)

        # Add route from owner to the peer
        for iter in owner.private_subnets:
            ec2.CfnRoute(self,
                         iter.subnet_id,
                         route_table_id=iter.route_table.route_table_id,
                         destination_cidr_block=peer_cidr,
                         vpc_peering_connection_id=self.peering.ref)
    def add_peering_route(self,
                          vpc,
                          destination_vpc,
                          peering_id,
                          destination_cidr=""):
        route_table_ids = set()
        # add public route table ids
        for subnet in vpc.public_subnets:
            route_table_ids.add(subnet.route_table.route_table_id)
        # add private route table ids
        for subnet in vpc.private_subnets:
            route_table_ids.add(subnet.route_table.route_table_id)

        for rt_id in route_table_ids:
            # if destination cidr doesn't have a forced value, use destination VPC's CIDR
            # this is here because IVpcProxy created from Vpc.from_lookup() doesn't support vpc_cidr_block yet
            if not destination_cidr:
                destination_cidr = destination_vpc.vpc_cidr_block
            ec2.CfnRoute(self,
                         'PeerRoute%s' % random.getrandbits(32),
                         route_table_id=rt_id,
                         destination_cidr_block=destination_cidr,
                         vpc_peering_connection_id=peering_id)
Exemplo n.º 17
0
def create_public_route_table(
        scope: core.Construct, vpc: aws_ec2.CfnVPC,
        internet_gateway: aws_ec2.CfnInternetGateway) -> aws_ec2.CfnRouteTable:

    prefix = scope.node.try_get_context("prefix")
    route_table = aws_ec2.CfnRouteTable(
        scope,
        f'{prefix}-route-table-igw',
        vpc_id=vpc.ref,
        tags=[core.CfnTag(
            key='Name',
            value=f'{prefix}-route-table-igw',
        )],
    )

    aws_ec2.CfnRoute(
        scope,
        f'{prefix}-route-igw',
        route_table_id=route_table.ref,
        destination_cidr_block='0.0.0.0/0',
        gateway_id=internet_gateway.ref,
    )
    return route_table
    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"
                        }])
Exemplo n.º 19
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prefix = "test""
        cidr = "10.100.0.0/16"
        # def name(s): return "{0}/{1}".format(prefix, s)
        def name(s): return "{0} {1}".format(prefix, s)

        # VPC
        self.vpc = ec2.CfnVPC(
            self, "vpc",
            cidr_block=cidr,
            enable_dns_hostnames=True,
            enable_dns_support=True,
            tags=[
                core.CfnTag(key="Name", value=prefix+" VPC")
            ]
        )

        # InternetGateway
        igw = ec2.CfnInternetGateway(
            self, "igw",
            tags=[
                core.CfnTag(key="Name", value=prefix+" IGW")
            ]
        )
        igw_attachment = ec2.CfnVPCGatewayAttachment(
            self, "igw_attachment",
            vpc_id=self.vpc.ref,
            internet_gateway_id=igw.ref
        )
        dhcpoptions = ec2.CfnDHCPOptions(
            self, "dhcpoptions",
            domain_name="ec2.internal "+prefix,
            domain_name_servers=["AmazonProvidedDNS"],
            tags=[
                core.CfnTag(key="Name", value=prefix)
            ]
        )
        dhcpoptionsassociation = ec2.CfnVPCDHCPOptionsAssociation(
            self, "dhcpoptionsassociation",
            dhcp_options_id=dhcpoptions.ref,
            vpc_id=self.vpc.ref
        )

        # PrivateSubnetA
        # private_subnet_a = ec2.CfnSubnet(
        #     self, "private_a",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.0.0/24",
        #     availability_zone="ap-northeast-1a",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_a"))
        #     ]
        # )
        # PrivateSubnetC
        # private_subnet_c = ec2.CfnSubnet(
        #     self, "private_c",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.1.0/24",
        #     availability_zone="ap-northeast-1c",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_c"))
        #     ]
        # )

        # PublicSubnetA
        self.public_subnet_a = ec2.CfnSubnet(
            self, "public_a",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.0.0/20",
            # availability_zone="ap-northeast-1a",
            availability_zone="us-east-1a",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_a")
            ]
        )
        # PublicSubnetC
        self.public_subnet_c = ec2.CfnSubnet(
            self, "public_c",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.16.0/20",
            availability_zone="us-east-1c",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_c")
            ]
        )
        self.public_subnet_d = ec2.CfnSubnet(
            self, "public_d",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.32.0/20",
            availability_zone="us-east-1d",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_d")
            ]
        )

        # EIP1 (for NATGW)
        # eip1 = ec2.CfnEIP(
        #     self, "eip1",
        #     domain="vpc",
        # )
        # eip1.add_depends_on(igw_attachment)

        # EIP2 (for NATGW)
        # eip2 = ec2.CfnEIP(
        #     self, "eip2",
        #     domain="vpc",
        # )
        # eip2.add_depends_on(igw_attachment)

        # NatGatewayA
        # natgw_a = ec2.CfnNatGateway(
        #     self, "natgw_a",
        #     allocation_id=eip1.attr_allocation_id,
        #     subnet_id=self.public_subnet_a.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_a"))
        #     ]
        # )
        # NatGatewayC
        # natgw_c = ec2.CfnNatGateway(
        #     self, "natgw_c",
        #     allocation_id=eip2.attr_allocation_id,
        #     subnet_id=public_subnet_c.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_c"))
        #     ]
        # )

        # RouteTable of PrivateSubnetA
        # rtb_private_a = ec2.CfnRouteTable(
        #     self, "rtb_private_a",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_a"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_a_association",
        #     route_table_id=rtb_private_a.ref,
        #     subnet_id=private_subnet_a.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_a",
        #     route_table_id=rtb_private_a.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_a.ref
        # )

        # RouteTable of PrivateSubnetC
        # rtb_private_c = ec2.CfnRouteTable(
        #     self, "rtb_private_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_c_association",
        #     route_table_id=rtb_private_c.ref,
        #     subnet_id=private_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_c",
        #     route_table_id=rtb_private_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_c.ref
        # )

        # RouteTable of PublicSubnetA
        self.rtb_public_a = ec2.CfnRouteTable(
            self, "rtb_public_a",
            vpc_id=self.vpc.ref,
            tags=[
                core.CfnTag(key="Name", value=prefix+"rtb_public_a")
            ]
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_a_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_a.ref
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_c_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_c.ref
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_d_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_d.ref
        )
        ec2.CfnRoute(
            self, "route_public_a",
            route_table_id=self.rtb_public_a.ref,
            destination_cidr_block="0.0.0.0/0",
            gateway_id=igw.ref
        )

        # RouteTable of PublicSubnetC
        # rtb_public_c = ec2.CfnRouteTable(
        #     self, "rtb_public_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_public_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_public_c_association",
        #     route_table_id=rtb_public_c.ref,
        #     subnet_id=public_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_public_c",
        #     route_table_id=rtb_public_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     gateway_id=igw.ref
        # )

        ami_id = ec2.AmazonLinuxImage(generation = ec2.AmazonLinuxGeneration.AMAZON_LINUX_2).get_image(self).image_id
        security_group = ec2.SecurityGroup(
            self,
            id='InstanceSecurityGroupwww',
            vpc=self.vpc,
            security_group_name='stg-'+prefix+'www'
        )
        security_group.add_ingress_rule(
            peer=ec2.Peer.ipv4('0.0.0.0/0'),
            connection=ec2.Port.tcp(22),
        )
        security_group.add_ingress_rule(
            peer=ec2.Peer.ipv4('0.0.0.0/0'),
            connection=ec2.Port.tcp(80),
        )
        EC2InstanceStgWeb = ec2.CfnInstance(self,
            "EC2InstanceStgWeb",
            image_id = ami_id,
            instance_type = "t3a.micro",
            monitoring = False,
            key_name = "stg-intrinio-www01",
            security_group_ids=[security_group.security_group_id],
            block_device_mappings = [{
            "deviceName": "/dev/xvda",
            "ebs": {
                "volumeSize": 10,
                # "volumeType": "io1",
                # "iops": 150,
                # "deleteOnTermination": True
                    }
                }
            ],
            tags = [
                { "key": "Name", "value": 'stg'+prefix+'www01' }
            ],
            network_interfaces = [{
                "deviceIndex": "0",
                "associatePublicIpAddress": True,
                "subnetId": self.public_subnet_a.ref,
                # "groupSet": [web_sg.security_group_id]
            }], #https: //github.com/aws/aws-cdk/issues/3419
        )
    # RdsSecurityGroup
        RdsStgSecurityGroup = ec2.CfnSecurityGroup(self, "RdsStgSecurityGroup",
          group_name = 'stg-'+prefix+'db01',
          group_description = 'stg-'+prefix+'db01',
          vpc_id = self.vpc.ref,
          security_group_ingress = [
            {
              "ipProtocol" : "tcp",
              "fromPort" : 3306,
              "toPort" : 3306,
              "cidrIp" : "0.0.0.0/0"
            }
          ],
          security_group_egress = [
            {
              "ipProtocol" : "tcp",
              "fromPort" : 0,
              "toPort" : 65535,
              "cidrIp" : "0.0.0.0/0"
            }
          ],
        )
        # MyDBSubnetGroup
        rds_subnet_group = rds.CfnDBSubnetGroup(self, "DBSubnetGroup",
            db_subnet_group_description = "DBSubnetGroup",
            subnet_ids = [
                    self.public_subnet_a.ref,
                    self.public_subnet_c.ref,
                    self.public_subnet_d.ref
            ]
        )
        DBParameterGroupStg = rds.CfnDBParameterGroup(self, "DBParameterGroupStg",
            description = "",
            family = "",
            parameters = [{'character_set_client': utf8,}]
        )
        rds_params = {
            'db_instance_identifier': "stg-test-db01",
            'engine': "mysql",
            'engine_version': '5.6.39',
            'db_instance_class': 'db.t3.micro',
            'allocated_storage': '5',
            'storage_type': 'gp2',
            'db_name': "test",
            'master_username': "******",
            'master_user_password': "******",
            'db_subnet_group_name' : rds_subnet_group.ref,
            'publicly_accessible': False,
            'multi_az': False,
            'preferred_backup_window': "18:00-18:30",
            'PreferredMaintenanceWindow': "sat:19:00-sat:19:30",
            'auto_minor_version_upgrade': False,
            'db_parameter_group_name': DBParameterGroupStg,
            'vpc_security_groups': [RdsStgSecurityGroup.ref],
            'copy_tags_to_snapshot': True,
            'backup_retention_period': 7,
            'enable_performance_insights': True,
            'delete_automated_backups': True,
            'deletion_protection': False,
            'availability_zone': self.public_subnet_a.ref,
            # 'storage_encrypted': False,
        }

        self.rds = rds.CfnDBInstance(self, 'staff-rds', **rds_params)

        core.CfnOutput(self, "Output",
                       value=self.vpc.ref)
Exemplo n.º 20
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prefix = "test"
        cidr = "192.168.0.0/16"

        # def name(s): return "{0}/{1}".format(prefix, s)
        def name(s):
            return "{0} {1}".format(prefix, s)

        # VPC
        self.vpc = ec2.CfnVPC(self,
                              "vpc",
                              cidr_block=cidr,
                              enable_dns_hostnames=True,
                              enable_dns_support=True,
                              tags=[core.CfnTag(key="Name", value=prefix)])

        # InternetGateway
        igw = ec2.CfnInternetGateway(
            self, "igw", tags=[core.CfnTag(key="Name", value=prefix)])
        igw_attachment = ec2.CfnVPCGatewayAttachment(
            self,
            "igw_attachment",
            vpc_id=self.vpc.ref,
            internet_gateway_id=igw.ref)
        dhcpoptions = ec2.CfnDHCPOptions(
            self,
            "dhcpoptions",
            domain_name="ec2.internal " + prefix,
            domain_name_servers=["AmazonProvidedDNS"],
            tags=[core.CfnTag(key="Name", value=prefix)])
        dhcpoptionsassociation = ec2.CfnVPCDHCPOptionsAssociation(
            self,
            "dhcpoptionsassociation",
            dhcp_options_id=dhcpoptions.ref,
            vpc_id=self.vpc.ref)

        # PrivateSubnetA
        # private_subnet_a = ec2.CfnSubnet(
        #     self, "private_a",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.0.0/24",
        #     availability_zone="ap-northeast-1a",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_a"))
        #     ]
        # )
        # PrivateSubnetC
        # private_subnet_c = ec2.CfnSubnet(
        #     self, "private_c",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.1.0/24",
        #     availability_zone="ap-northeast-1c",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_c"))
        #     ]
        # )

        # PublicSubnetA
        self.public_subnet_a = ec2.CfnSubnet(
            self,
            "public_a",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.0.0/20",
            # availability_zone="ap-northeast-1a",
            availability_zone="us-east-1a",
            tags=[core.CfnTag(key="Name", value=prefix + " public_a")])
        # PublicSubnetC
        self.public_subnet_c = ec2.CfnSubnet(
            self,
            "public_c",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.16.0/20",
            availability_zone="us-east-1c",
            tags=[core.CfnTag(key="Name", value=prefix + " public_c")])
        self.public_subnet_d = ec2.CfnSubnet(
            self,
            "public_d",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.32.0/20",
            availability_zone="us-east-1d",
            tags=[core.CfnTag(key="Name", value=prefix + " public_d")])

        # EIP1 (for NATGW)
        # eip1 = ec2.CfnEIP(
        #     self, "eip1",
        #     domain="vpc",
        # )
        # eip1.add_depends_on(igw_attachment)

        # EIP2 (for NATGW)
        # eip2 = ec2.CfnEIP(
        #     self, "eip2",
        #     domain="vpc",
        # )
        # eip2.add_depends_on(igw_attachment)

        # NatGatewayA
        # natgw_a = ec2.CfnNatGateway(
        #     self, "natgw_a",
        #     allocation_id=eip1.attr_allocation_id,
        #     subnet_id=self.public_subnet_a.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_a"))
        #     ]
        # )
        # NatGatewayC
        # natgw_c = ec2.CfnNatGateway(
        #     self, "natgw_c",
        #     allocation_id=eip2.attr_allocation_id,
        #     subnet_id=public_subnet_c.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_c"))
        #     ]
        # )

        # RouteTable of PrivateSubnetA
        # rtb_private_a = ec2.CfnRouteTable(
        #     self, "rtb_private_a",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_a"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_a_association",
        #     route_table_id=rtb_private_a.ref,
        #     subnet_id=private_subnet_a.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_a",
        #     route_table_id=rtb_private_a.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_a.ref
        # )

        # RouteTable of PrivateSubnetC
        # rtb_private_c = ec2.CfnRouteTable(
        #     self, "rtb_private_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_c_association",
        #     route_table_id=rtb_private_c.ref,
        #     subnet_id=private_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_c",
        #     route_table_id=rtb_private_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_c.ref
        # )

        # RouteTable of PublicSubnetA
        self.rtb_public_a = ec2.CfnRouteTable(
            self,
            "rtb_public_a",
            vpc_id=self.vpc.ref,
            tags=[core.CfnTag(key="Name", value=prefix + "rtb_public_a")])
        ec2.CfnSubnetRouteTableAssociation(
            self,
            "rtb_public_a_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_a.ref)
        ec2.CfnSubnetRouteTableAssociation(
            self,
            "rtb_public_c_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_c.ref)
        ec2.CfnSubnetRouteTableAssociation(
            self,
            "rtb_public_d_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_d.ref)
        ec2.CfnRoute(self,
                     "route_public_a",
                     route_table_id=self.rtb_public_a.ref,
                     destination_cidr_block="0.0.0.0/0",
                     gateway_id=igw.ref)

        # RouteTable of PublicSubnetC
        # rtb_public_c = ec2.CfnRouteTable(
        #     self, "rtb_public_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_public_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_public_c_association",
        #     route_table_id=rtb_public_c.ref,
        #     subnet_id=public_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_public_c",
        #     route_table_id=rtb_public_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     gateway_id=igw.ref
        # )

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

        # security_group = ec2.SecurityGroup(
        #     self,
        #     id='test',
        #     vpc=self.vpc,
        #     security_group_name='test-security-group'
        # )

        # security_group.add_ingress_rule(
        #     peer=ec2.Peer.ipv4(cidr),
        #     connection=ec2.Port.tcp(22),
        # )

        # red_web_inst = ec2.CfnInstance(self,
        #     "testInstance01",
        #     image_id = ami_id,
        #     instance_type = "t3a.micro",
        #     monitoring = False,
        #     key_name = "stg-intrinio-www01",
        #     security_group_ids=[security_group.security_group_id],
        #     block_device_mappings = [{
        #     "deviceName": "/dev/xvda",
        #     "ebs": {
        #         "volumeSize": 10,
        #         "volumeType": "io1",
        #         "iops": 150,
        #         "deleteOnTermination": True
        #             }
        #         }
        #     ],
        #     tags = [
        #         { "key": "Name", "value": prefix }
        #     ],
        #     network_interfaces = [{
        #         "deviceIndex": "0",
        #         "associatePublicIpAddress": True,
        #         "subnetId": self.public_subnet_a.ref,
        #         # "groupSet": [web_sg.security_group_id]
        #     }], #https: //github.com/aws/aws-cdk/issues/3419
        # )
        # RedisSecurityGroup
        redis_security_group = ec2.CfnSecurityGroup(
            self,
            "RedisSecurityGroup",
            group_name="stg-test-redis01",
            group_description="HTTP traffic",
            vpc_id=self.vpc.ref,
            security_group_ingress=[{
                "ipProtocol": "tcp",
                "fromPort": 6379,
                "toPort": 6379,
                "cidrIp": "192.168.0.0/16"
            }],
            security_group_egress=[{
                "ipProtocol": "tcp",
                "fromPort": 0,
                "toPort": 65535,
                "cidrIp": "0.0.0.0/0"
            }],
        )
        # MyDBSubnetGroup
        redis_subnet_group = redis.CfnSubnetGroup(
            self,
            "RedisSubnetGroup",
            cache_subnet_group_name="stg-test-redis01",
            description="stg-test-redis01",
            subnet_ids=[
                self.public_subnet_a.ref, self.public_subnet_c.ref,
                self.public_subnet_d.ref
            ])
        redis_params = {
            'auto_minor_version_upgrade': True,
            'engine': 'redis',
            'at_rest_encryption_enabled': True,
            'automatic_failover_enabled': False,
            'engine_version': '4.0.10',
            'cache_node_type': 'cache.t3.micro',
            'num_cache_clusters': 1,
            'replication_group_description': "stg-test-redis01",
            'security_group_ids': [redis_security_group.ref],
            'cache_subnet_group_name': redis_subnet_group.ref
        }

        self.redis = redis.CfnReplicationGroup(self, 'staff-redis',
                                               **redis_params)

        core.CfnOutput(self, "OutputVpc", value=self.vpc.ref)
        core.CfnOutput(self, "OutputRedis", value=self.redis.ref)
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # vpc = ec2.Vpc(self, "VPC",
        #     cidr = "10.1.0.0/16",
        #     max_azs = 2,
        #     subnet_configuration =[
        #         ec2.SubnetConfiguration(name='edx-subnet-Public', subnet_type=ec2.SubnetType.PUBLIC, cidr_mask=24),
        #         ec2.SubnetConfiguration(name='edx-subnet-Private', subnet_type=ec2.SubnetType.PRIVATE, cidr_mask=24),
        #     ]
        # )

        # core.Tag.add(vpc, key = "Name", value = "edx-build-aws-vpc")
        # core.Tag.add(vpc.public_subnets[0], key = "Name", value = "edx-subnet-public-a")
        # core.Tag.add(vpc.public_subnets[1], key = "Name", value = "edx-subnet-public-b")
        # core.Tag.add(vpc.private_subnets[0], key = "Name", value = "edx-subnet-public-a")
        # core.Tag.add(vpc.private_subnets[1], key = "Name", value = "edx-subnet-public-b")

        # Exercise 3
        # Create VPC
        vpc = ec2.CfnVPC(self,
                         "VPC",
                         cidr_block="10.1.0.0/16",
                         tags=[{
                             "key": "Name",
                             "value": "edx-build-aws-vpc"
                         }])

        # Create Internet Gateway
        internet_gateway = ec2.CfnInternetGateway(self,
                                                  "InternetGateway",
                                                  tags=[{
                                                      "key": "Name",
                                                      "value": "edx-igw"
                                                  }])

        # Attach Gateway
        attach_gateway = ec2.CfnVPCGatewayAttachment(
            self,
            "AttachGateway",
            vpc_id=vpc.ref,
            internet_gateway_id=internet_gateway.ref)

        # Create EIP1
        eip_1 = ec2.CfnEIP(self, "EIP1", domain="vpc")

        # Create Public Subnet 1
        public_subnet_1 = ec2.CfnSubnet(self,
                                        "PublicSubnet1",
                                        availability_zone=core.Fn.select(
                                            0,
                                            core.Fn.get_azs(core.Aws.REGION)),
                                        cidr_block="10.1.1.0/24",
                                        vpc_id=vpc.ref,
                                        map_public_ip_on_launch=True,
                                        tags=[{
                                            "key": "Name",
                                            "value": "edx-subnet-public-a"
                                        }])

        # Create Nat Gateway 1
        nat_gateway_1 = ec2.CfnNatGateway(
            self,
            "NatGateway1",
            allocation_id=eip_1.attr_allocation_id,
            subnet_id=public_subnet_1.ref)

        # Create Private Route Table 1
        private_route_table_1 = ec2.CfnRouteTable(self,
                                                  "PrivateRouteTable1",
                                                  vpc_id=vpc.ref,
                                                  tags=[{
                                                      "key":
                                                      "Name",
                                                      "value":
                                                      "edx-routetable-private1"
                                                  }])

        # Create Private Route 1
        private_route_1 = ec2.CfnRoute(
            self,
            "PrivateRoute1",
            route_table_id=private_route_table_1.ref,
            destination_cidr_block="0.0.0.0/0",
            nat_gateway_id=nat_gateway_1.ref)

        # Create EIP2
        eip_2 = ec2.CfnEIP(self, "EIP2", domain="vpc")

        # Create Public Subnet 2
        public_subnet_2 = ec2.CfnSubnet(self,
                                        "PublicSubnet2",
                                        availability_zone=core.Fn.select(
                                            1,
                                            core.Fn.get_azs(core.Aws.REGION)),
                                        cidr_block="10.1.2.0/24",
                                        vpc_id=vpc.ref,
                                        map_public_ip_on_launch=True,
                                        tags=[{
                                            "key": "Name",
                                            "value": "edx-subnet-public-b"
                                        }])

        # Create Nat Gateway 2
        nat_gateway_2 = ec2.CfnNatGateway(
            self,
            "NatGateway2",
            allocation_id=eip_2.attr_allocation_id,
            subnet_id=public_subnet_2.ref)

        # Create Private Route Table 2
        private_route_table_2 = ec2.CfnRouteTable(self,
                                                  "PrivateRouteTable2",
                                                  vpc_id=vpc.ref,
                                                  tags=[{
                                                      "key":
                                                      "Name",
                                                      "value":
                                                      "edx-routetable-private2"
                                                  }])

        # Create Private Route 2
        private_route_2 = ec2.CfnRoute(
            self,
            "PrivateRoute2",
            route_table_id=private_route_table_2.ref,
            destination_cidr_block="0.0.0.0/0",
            nat_gateway_id=nat_gateway_2.ref)

        # Create Public Route Table
        public_route_table = ec2.CfnRouteTable(self,
                                               "PublicRouteTable",
                                               vpc_id=vpc.ref,
                                               tags=[{
                                                   "key":
                                                   "Name",
                                                   "value":
                                                   "edx-routetable-public"
                                               }])

        # Create Public Default Route
        public_default_route = ec2.CfnRoute(
            self,
            "PublicDefaultRoute",
            route_table_id=public_route_table.ref,
            destination_cidr_block="0.0.0.0/0",
            gateway_id=internet_gateway.ref)

        # Create Public Route Association 1
        public_route_association_1 = ec2.CfnSubnetRouteTableAssociation(
            self,
            "PublicRouteAssociation1",
            route_table_id=public_route_table.ref,
            subnet_id=public_subnet_1.ref)

        # Create Public Route Association 12
        public_route_association_2 = ec2.CfnSubnetRouteTableAssociation(
            self,
            "PublicRouteAssociation2",
            route_table_id=public_route_table.ref,
            subnet_id=public_subnet_2.ref)

        # Create Private Subnet 1
        private_subnet_1 = ec2.CfnSubnet(self,
                                         "PrivateSubnet1",
                                         availability_zone=core.Fn.select(
                                             0,
                                             core.Fn.get_azs(core.Aws.REGION)),
                                         cidr_block="10.1.3.0/24",
                                         vpc_id=vpc.ref,
                                         tags=[{
                                             "key": "Name",
                                             "value": "edx-subnet-private-a"
                                         }])

        # Create Private Subnet 2
        private_subnet_2 = ec2.CfnSubnet(self,
                                         "PrivateSubnet2",
                                         availability_zone=core.Fn.select(
                                             1,
                                             core.Fn.get_azs(core.Aws.REGION)),
                                         cidr_block="10.1.4.0/24",
                                         vpc_id=vpc.ref,
                                         tags=[{
                                             "key": "Name",
                                             "value": "edx-subnet-private-b"
                                         }])

        # Create Private Route Association 1
        private_route_association_1 = ec2.CfnSubnetRouteTableAssociation(
            self,
            "PrivateRouteAssociation1",
            route_table_id=private_route_table_1.ref,
            subnet_id=private_subnet_1.ref)

        # Create Private Route Association 2
        private_route_association_1 = ec2.CfnSubnetRouteTableAssociation(
            self,
            "PrivateRouteAssociation2",
            route_table_id=private_route_table_2.ref,
            subnet_id=private_subnet_2.ref)

        # Output
        core.CfnOutput(self,
                       "VPCOutput",
                       value=vpc.ref,
                       description="VPC",
                       export_name="VPC")
        core.CfnOutput(self,
                       "PublicSubnet1Output",
                       value=public_subnet_1.ref,
                       description="PublicSubnet1",
                       export_name="PublicSubnet1")
        core.CfnOutput(self,
                       "PublicSubnet2Output",
                       value=public_subnet_2.ref,
                       description="PublicSubnet2",
                       export_name="PublicSubnet2")
        core.CfnOutput(self,
                       "PrivateSubnet1Output",
                       value=private_subnet_1.ref,
                       description="PrivateSubnet1",
                       export_name="PrivateSubnet1")
        core.CfnOutput(self,
                       "PrivateSubnet2Output",
                       value=private_subnet_2.ref,
                       description="PrivateSubnet2",
                       export_name="PrivateSubnet2")
Exemplo n.º 22
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Create an empty VPC
        # If you don't specify any other resources EXCEPT the VPC, there's a standard template applied
        vpc = ec2.Vpc(
            self,
            id="MyVPC",
            nat_gateways=0,
            cidr="192.168.0.0/20",
            max_azs=1,
            subnet_configuration=[],
        )

        # A couple of subnets
        app_subnet = ec2.CfnSubnet(
            self,
            id="Application",
            vpc_id=vpc.vpc_id,
            availability_zone="eu-central-1a",
            cidr_block="192.168.1.0/24",
            map_public_ip_on_launch=False,
            tags=[core.CfnTag(key="Name", value="Application")])

        web_subnet = ec2.CfnSubnet(
            self,
            id="Webhost",
            vpc_id=vpc.vpc_id,
            availability_zone="eu-central-1b",
            cidr_block="192.168.2.0/24",
            map_public_ip_on_launch=True,
            tags=[core.CfnTag(key="Name", value="WebHost")])

        # A couple of route tables
        private_rt = ec2.CfnRouteTable(
            self,
            id="Private_RT",
            vpc_id=vpc.vpc_id,
            tags=[core.CfnTag(key="Name", value="Private_RT")])

        public_rt = ec2.CfnRouteTable(
            self,
            id="Public_RT",
            vpc_id=vpc.vpc_id,
            tags=[core.CfnTag(key="Name", value="Public_RT")])

        # How to associate a subnet with a route table
        ec2.CfnSubnetRouteTableAssociation(self,
                                           id="WebHostRTAssoc",
                                           subnet_id=web_subnet.ref,
                                           route_table_id=public_rt.ref)

        ec2.CfnSubnetRouteTableAssociation(self,
                                           id="ApplicationRTAssoc",
                                           subnet_id=app_subnet.ref,
                                           route_table_id=private_rt.ref)

        # A gateway (Internet Gateway in this case)
        igw = ec2.CfnInternetGateway(
            self, id="MyIGW", tags=[core.CfnTag(key="Name", value="IGW")])

        # How to associate a gateway to a VPC (IGW in this case - for VGW use vpn_gateway_id=blablabla)
        ec2.CfnVPCGatewayAttachment(self,
                                    id="IGW_Assoc",
                                    vpc_id=vpc.vpc_id,
                                    internet_gateway_id=igw.ref)

        # Elastic IP
        eip_01 = ec2.CfnEIP(self, id="EIP01")

        # NAT gateway
        ngw = ec2.CfnNatGateway(self,
                                id="NAT_GW",
                                allocation_id=eip_01.attr_allocation_id,
                                subnet_id=web_subnet.ref,
                                tags=[core.CfnTag(key="Name", value="NAT_GW")])

        ngw.add_depends_on(eip_01)

        # Add a route to a route table
        default_route_public = ec2.CfnRoute(self,
                                            id="DefaultRoutePublic",
                                            route_table_id=public_rt.ref,
                                            destination_cidr_block="0.0.0.0/0",
                                            gateway_id=igw.ref)

        default_route_public.add_depends_on(igw)

        default_route_private = ec2.CfnRoute(
            self,
            id="DefaultRouteprivate",
            route_table_id=private_rt.ref,
            destination_cidr_block="0.0.0.0/0",
            nat_gateway_id=ngw.ref)

        default_route_private.add_depends_on(ngw)

        ### Security Groups ###
        # PUBLIC SUBNET SG
        sg_public = ec2.CfnSecurityGroup(
            self,
            id="SG_PUBLIC",
            group_description="SG for the Public Subnet",
            group_name="SG_PUBLIC",
            vpc_id=vpc.vpc_id,
            tags=[core.CfnTag(key="Name", value="SG_Public")])

        my_home_ip = requests.get("https://api.my-ip.io/ip.json").json()['ip']

        ports_pub = {'tcp': [22, 80], 'icmp': [-1]}

        for protocl, ports_list in ports_pub.items():
            for port in ports_list:
                ec2.CfnSecurityGroupIngress(
                    self,
                    id=f"sg_pub_in_{protocl}_{port}",
                    group_id=sg_public.attr_group_id,
                    ip_protocol=protocl,
                    cidr_ip=f"{my_home_ip}/32",
                    to_port=port,
                    from_port=port,
                    description=f"{protocl.upper()} {port} from home IP")

        # SG INGRESS ENTRIES - ICMP - EXAMPLE
        # sg_in_icmp = ec2.CfnSecurityGroupIngress(self, id="SG_PUB_IN_ICMP",
        #                                          group_id=sg_public.attr_group_id,
        #                                          ip_protocol = "icmp",
        #                                          cidr_ip = f"{my_home_ip}/32",
        #                                          to_port = -1,
        #                                          from_port = -1,
        #                                          description = "ICMP FROM HOME")

        # SG EGRESS ENTRIES - AUTO-IMPLIED IF NOT CONFIGURED
        # sg_out_all = ec2.CfnSecurityGroupEgress(self, id="SG_PUB_OUT_ALL",
        #                                         group_id=sg_public.attr_group_id,
        #                                         ip_protocol="-1",
        #                                         cidr_ip="0.0.0.0/0")

        # PRIVATE SUBNET SG
        sg_private = ec2.CfnSecurityGroup(
            self,
            id="SG_PRIVATE",
            group_description="SG for the Private Subnet",
            group_name="SG_PRIVATE",
            vpc_id=vpc.vpc_id,
            tags=[core.CfnTag(key="Name", value="SG_Private")])

        sg_private.add_depends_on(sg_public)

        ports_priv = {'tcp': [22, 21, 53, 3368, 80], 'icmp': [-1]}

        for protocl, ports_list in ports_priv.items():
            for port in ports_list:
                ec2.CfnSecurityGroupIngress(
                    self,
                    id=f"sg_priv_in_{protocl}_{port}",
                    group_id=sg_private.attr_group_id,
                    description=
                    f"{protocl.upper()}:{port} from the public subnet only",
                    ip_protocol=protocl,
                    from_port=port,
                    to_port=port,
                    source_security_group_id=sg_public.ref)

        ### EC2 Instances ###
        # Generate some user data _ WIP
        # user_data = ec2.UserData.custom

        # One in the public subnet
        webserver01 = ec2.CfnInstance(
            self,
            id="WebServer01",
            image_id="ami-0de9f803fcac87f46",
            instance_type="t2.micro",
            subnet_id=web_subnet.ref,
            key_name="proton_mail_kp",
            security_group_ids=[sg_public.ref],
            tags=[core.CfnTag(key="Name", value="WebServer01")])

        appserver01 = ec2.CfnInstance(
            self,
            id="AppServer01",
            image_id="ami-0de9f803fcac87f46",
            instance_type="t2.micro",
            subnet_id=app_subnet.ref,
            key_name="proton_mail_kp",
            security_group_ids=[sg_private.ref],
            tags=[core.CfnTag(key="Name", value="AppServer01")])
Exemplo n.º 23
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)
Exemplo n.º 24
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # IAMロールを作成
        my_role_ec2 = iam.CfnRole(
            self,
            id="my-role-ec2",
            assume_role_policy_document={
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Action": "sts:AssumeRole",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "ec2.amazonaws.com"
                    }
                }]
            },
            description="the ec2 role",
            managed_policy_arns=[
                # "arn:aws:iam::aws:policy/AmazonS3FullAccess" # 付与したいアクセス権をリストする
            ],
            role_name="my-role-ec2",
            tags=[{
                "key": "Name",
                "value": "my-role-ec2"
            }])
        # Instance Profileを作成
        my_instance_profile = iam.CfnInstanceProfile(self,
                                                     id="my-instance-profile",
                                                     roles=[my_role_ec2.ref])

        # VPCを作成
        my_vpc = ec2.CfnVPC(self,
                            id="my-vpc",
                            cidr_block="192.168.0.0/16",
                            enable_dns_hostnames=True,
                            tags=[{
                                "key": "Name",
                                "value": "my-vpc"
                            }])

        # Subnetを作成
        my_subnet_1 = ec2.CfnSubnet(self,
                                    id="my-subnet",
                                    cidr_block="192.168.0.0/24",
                                    vpc_id=my_vpc.ref,
                                    availability_zone=core.Fn.select(
                                        0, core.Fn.get_azs("")),
                                    tags=[{
                                        "key": "Name",
                                        "value": "my-subnet-1"
                                    }])

        # Internet Gatewayを作成
        my_igw = ec2.CfnInternetGateway(self,
                                        id="my-igw",
                                        tags=[{
                                            "key": "Name",
                                            "value": "my-igw"
                                        }])
        # Internet Gatewayをアタッチ
        ec2.CfnVPCGatewayAttachment(self,
                                    id="my-igw-attachment",
                                    vpc_id=my_vpc.ref,
                                    internet_gateway_id=my_igw.ref)

        # Routetableを作成
        my_rtb = ec2.CfnRouteTable(self,
                                   id="my-rtb",
                                   vpc_id=my_vpc.ref,
                                   tags=[{
                                       "key": "Name",
                                       "value": "my-rtb"
                                   }])
        # Routetableとサブネットの関連付け
        ec2.CfnSubnetRouteTableAssociation(self,
                                           id="my-rtb-association",
                                           route_table_id=my_rtb.ref,
                                           subnet_id=my_subnet_1.ref)

        # Routeの設定
        my_rt = ec2.CfnRoute(self,
                             id="my-rt",
                             route_table_id=my_rtb.ref,
                             destination_cidr_block="0.0.0.0/0",
                             gateway_id=my_igw.ref)

        # Security Groupの作成
        my_sg_ec2 = ec2.CfnSecurityGroup(
            self,
            id="my-sg-ec2",
            vpc_id=my_vpc.ref,
            group_description="my-sg-ec2",
            group_name="my-sg-ec2",
            security_group_ingress=[
                ec2.CfnSecurityGroup.IngressProperty(ip_protocol="tcp",
                                                     cidr_ip="0.0.0.0/0",
                                                     from_port=22,
                                                     to_port=22)
            ],
            tags=[{
                "key": "Name",
                "value": "my-sg-ec2"
            }])

        #  AMIを指定してimage_idを取得
        amzn_linux = ec2.MachineImage.latest_amazon_linux(
            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
            edition=ec2.AmazonLinuxEdition.STANDARD,
            virtualization=ec2.AmazonLinuxVirt.HVM,
            storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE,
            cpu_type=ec2.AmazonLinuxCpuType.X86_64).get_image(self).image_id

        # EC2を作成
        my_ec2 = ec2.CfnInstance(
            self,
            id="my-ec2",
            availability_zone=core.Fn.select(0, core.Fn.get_azs("")),
            block_device_mappings=[
                ec2.CfnInstance.BlockDeviceMappingProperty(
                    device_name="/dev/sda1",
                    ebs=ec2.CfnInstance.EbsProperty(delete_on_termination=True,
                                                    encrypted=False,
                                                    volume_size=10,
                                                    volume_type="gp2"))
            ],
            credit_specification=ec2.CfnInstance.CreditSpecificationProperty(
                cpu_credits="standard"),
            iam_instance_profile=my_instance_profile.ref,
            image_id=amzn_linux,
            instance_type="t2.micro",
            security_group_ids=[my_sg_ec2.ref],
            subnet_id=my_subnet_1.ref,
            tags=[{
                "key": "Name",
                "value": "my-ec2"
            }])
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        self._ip_range = 0

        # Crete a custom VPC
        id = hashlib.md5(f'VPC'.encode()).hexdigest()
        vpc = _ec2.CfnVPC(
            self,
            f'vpc-{id}',
            cidr_block='10.0.0.0/16',
            enable_dns_hostnames=True,
            enable_dns_support=True,
            instance_tenancy=None,
            tags=[{'key': 'Name', 'value': 'My Lab VPC'}]
        )

        # TODO IPv6WorkAround for subnet cidr allocation.
        # https://github.com/aws/aws-cdk/issues/894#issuecomment-606140766
        id = hashlib.md5(f'ipv6cidrblock'.encode()).hexdigest()
        assign_ipv6 = _ec2.CfnVPCCidrBlock(self, f'ipv6cidr-{id}', vpc_id=vpc.ref,
                                           amazon_provided_ipv6_cidr_block=True)

        # Create an Internet Gateway and attach it to the VPC
        id = hashlib.md5(f'IGWVPC'.encode()).hexdigest()
        igw = _ec2.CfnInternetGateway(self,
                                      id=f'igw-{id}',
                                      tags=[
                                          {'key': 'Name', 'value': 'My Lab IGW'}]
                                      )
        igw_vpc_attach = _ec2.CfnVPCGatewayAttachment(self, id=f'IGWVPCAttach-{id}',
                                                      vpc_id=vpc.ref,
                                                      internet_gateway_id=igw.ref)

        # Need to create 3 subnets per tier and attach it to custom route table
        for sub_type in ["web", "reserved", "db"]:
            id = hashlib.md5(f'RouteTable-{sub_type}'.encode()).hexdigest()
            route_table = _ec2.CfnRouteTable(self,
                                             f'rtb-{id}',
                                             vpc_id=vpc.ref,
                                             tags=[
                                                 {'key': 'Name', 'value': f'RouteTable-{sub_type}'}])

            # Create Route to internet via IGW for Web Subnets
            if sub_type == 'web':
                route_to_internet = _ec2.CfnRoute(self, f'routetointernet-{id}',
                                                  route_table_id=route_table.ref,
                                                  destination_cidr_block='0.0.0.0/0',
                                                  gateway_id=igw.ref)

            for i in range(0, 3):
                id = hashlib.md5(f'Subnet-{sub_type}{i}'.encode()).hexdigest()
                subnet = _ec2.CfnSubnet(
                    self,
                    id=f'subnet-{id}',
                    cidr_block=f'10.0.{self._ip_range}.0/20',
                    vpc_id=vpc.ref,
                    availability_zone=core.Fn.select(
                        i, core.Fn.get_azs(core.Aws.REGION)),
                    tags=[
                        {'key': 'Name', 'value': f'Subnet-{sub_type}{i + 1}'}])

                self._ip_range = self._ip_range + 16

                # Associate subnets with RouteTable
                id = hashlib.md5(
                    f'RouteTableAssoc-{sub_type}{i}'.encode()).hexdigest()
                route_table_association = _ec2.CfnSubnetRouteTableAssociation(
                    self,
                    f'rtbassoc-{id}',
                    route_table_id=route_table.ref,
                    subnet_id=subnet.ref,
                )
Exemplo n.º 26
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prefix = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")
        cidr = self.node.try_get_context("cidir")
        # cidr = "192.168.0.0/16"
        # prefix = "test"
        # def name(s): return "{0}/{1}".format(prefix, s)
        def name(s): return "{0} {1}".format(prefix, s)

        # VPC
        self.vpc = ec2.CfnVPC(
            self, "vpc",
            cidr_block=cidr,
            enable_dns_hostnames=True,
            enable_dns_support=True,
            tags=[
                core.CfnTag(key="Name", value=prefix+' VPC')
            ]
        )

        # InternetGateway
        igw = ec2.CfnInternetGateway(
            self, "igw",
            tags=[
                core.CfnTag(key="Name", value=prefix+' IGW')
            ]
        )
        igw_attachment = ec2.CfnVPCGatewayAttachment(
            self, "igw_attachment",
            vpc_id=self.vpc.ref,
            internet_gateway_id=igw.ref
        )
        dhcpoptions = ec2.CfnDHCPOptions(
            self, "dhcpoptions",
            domain_name="ec2.internal "+prefix,
            domain_name_servers=["AmazonProvidedDNS"],
            tags=[
                core.CfnTag(key="Name", value=prefix)
            ]
        )
        dhcpoptionsassociation = ec2.CfnVPCDHCPOptionsAssociation(
            self, "dhcpoptionsassociation",
            dhcp_options_id=dhcpoptions.ref,
            vpc_id=self.vpc.ref
        )

        # PrivateSubnetA
        # private_subnet_a = ec2.CfnSubnet(
        #     self, "private_a",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.0.0/24",
        #     availability_zone="ap-northeast-1a",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_a"))
        #     ]
        # )
        # PrivateSubnetC
        # private_subnet_c = ec2.CfnSubnet(
        #     self, "private_c",
        #     vpc_id=vpc.ref,
        #     cidr_block="192.168.1.0/24",
        #     availability_zone="ap-northeast-1c",
        #     tags=[
        #         core.CfnTag(key="Name", value=name("private_c"))
        #     ]
        # )

        # PublicSubnetA
        self.public_subnet_a = ec2.CfnSubnet(
            self, "public_a",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.0.0/20",
            # availability_zone="ap-northeast-1a",
            map_public_ip_on_launch=True,
            availability_zone="us-east-1a",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_a")
            ]
        )
        # PublicSubnetC
        self.public_subnet_c = ec2.CfnSubnet(
            self, "public_c",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.16.0/20",
            map_public_ip_on_launch=True,
            availability_zone="us-east-1c",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_c")
            ]
        )
        self.public_subnet_d = ec2.CfnSubnet(
            self, "public_d",
            vpc_id=self.vpc.ref,
            cidr_block="192.168.32.0/20",
            map_public_ip_on_launch=True,
            availability_zone="us-east-1d",
            tags=[
                core.CfnTag(key="Name", value=prefix+" public_d")
            ]
        )

        # EIP1 (for NATGW)
        # eip1 = ec2.CfnEIP(
        #     self, "eip1",
        #     domain="vpc",
        # )
        # eip1.add_depends_on(igw_attachment)

        # EIP2 (for NATGW)
        # eip2 = ec2.CfnEIP(
        #     self, "eip2",
        #     domain="vpc",
        # )
        # eip2.add_depends_on(igw_attachment)

        # NatGatewayA
        # natgw_a = ec2.CfnNatGateway(
        #     self, "natgw_a",
        #     allocation_id=eip1.attr_allocation_id,
        #     subnet_id=self.public_subnet_a.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_a"))
        #     ]
        # )
        # NatGatewayC
        # natgw_c = ec2.CfnNatGateway(
        #     self, "natgw_c",
        #     allocation_id=eip2.attr_allocation_id,
        #     subnet_id=public_subnet_c.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("natgw_c"))
        #     ]
        # )

        # RouteTable of PrivateSubnetA
        # rtb_private_a = ec2.CfnRouteTable(
        #     self, "rtb_private_a",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_a"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_a_association",
        #     route_table_id=rtb_private_a.ref,
        #     subnet_id=private_subnet_a.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_a",
        #     route_table_id=rtb_private_a.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_a.ref
        # )

        # RouteTable of PrivateSubnetC
        # rtb_private_c = ec2.CfnRouteTable(
        #     self, "rtb_private_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_private_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_private_c_association",
        #     route_table_id=rtb_private_c.ref,
        #     subnet_id=private_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_private_c",
        #     route_table_id=rtb_private_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     nat_gateway_id=natgw_c.ref
        # )

        # RouteTable of PublicSubnetA
        self.rtb_public_a = ec2.CfnRouteTable(
            self, "rtb_public_a",
            vpc_id=self.vpc.ref,
            tags=[
                core.CfnTag(key="Name", value=prefix+" rtb_public_a")
            ]
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_a_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_a.ref
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_c_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_c.ref
        )
        ec2.CfnSubnetRouteTableAssociation(
            self, "rtb_public_d_association",
            route_table_id=self.rtb_public_a.ref,
            subnet_id=self.public_subnet_d.ref
        )
        ec2.CfnRoute(
            self, "route_public_a",
            route_table_id=self.rtb_public_a.ref,
            destination_cidr_block="0.0.0.0/0",
            gateway_id=igw.ref
        )

        # RouteTable of PublicSubnetC
        # rtb_public_c = ec2.CfnRouteTable(
        #     self, "rtb_public_c",
        #     vpc_id=vpc.ref,
        #     tags=[
        #         core.CfnTag(key="Name", value=name("rtb_public_c"))
        #     ]
        # )
        # ec2.CfnSubnetRouteTableAssociation(
        #     self, "rtb_public_c_association",
        #     route_table_id=rtb_public_c.ref,
        #     subnet_id=public_subnet_c.ref
        # )
        # ec2.CfnRoute(
        #     self, "route_public_c",
        #     route_table_id=rtb_public_c.ref,
        #     destination_cidr_block="0.0.0.0/0",
        #     gateway_id=igw.ref
        # )

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

        # security_group = ec2.SecurityGroup(
        #     self,
        #     id='test',
        #     vpc=self.vpc,
        #     security_group_name='test-security-group'
        # )

        # security_group.add_ingress_rule(
        #     peer=ec2.Peer.ipv4(cidr),
        #     connection=ec2.Port.tcp(22),
        # )
        
        # test_web = ec2.CfnInstance(self,
        #     "testInstance01",
        #     image_id = ami_id,
        #     instance_type = "t3a.micro",
        #     monitoring = False,
        #     key_name = "stg-intrinio-www01",
        #     security_group_ids=[security_group.security_group_id],
        #     block_device_mappings = [{
        #     "deviceName": "/dev/xvda",
        #     "ebs": {
        #         "volumeSize": 10,
        #         "volumeType": "io1",
        #         "iops": 150,
        #         "deleteOnTermination": True
        #             }
        #         }
        #     ],
        #     tags = [
        #         { "key": "Name", "value": prefix }
        #     ],
        #     network_interfaces = [{
        #         "deviceIndex": "0",
        #         "associatePublicIpAddress": True,
        #         "subnetId": self.public_subnet_a.ref,
        #         # "groupSet": [web_sg.security_group_id]
        #     }], #https: //github.com/aws/aws-cdk/issues/3419
        # )

        core.CfnOutput(self, "Output",
                       value=self.vpc.ref)
Exemplo n.º 27
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.defaultVpc = aws_ec2.Vpc(
            self,
            "Default",
            cidr='10.0.0.0/24',
            nat_gateways=2,
            subnet_configuration=[
                aws_ec2.SubnetConfiguration(
                    name="public",
                    cidr_mask=27,
                    reserved=False,
                    subnet_type=aws_ec2.SubnetType.PUBLIC),
                aws_ec2.SubnetConfiguration(
                    name="private",
                    cidr_mask=27,
                    reserved=False,
                    subnet_type=aws_ec2.SubnetType.PRIVATE)
            ])

        self.eksVpc = aws_ec2.Vpc(
            self,
            "EKSvpc",
            cidr='192.168.0.0/24',
            subnet_configuration=[
                aws_ec2.SubnetConfiguration(
                    name="private",
                    cidr_mask=26,
                    reserved=False,
                    subnet_type=aws_ec2.SubnetType.ISOLATED)
            ])

        self.transitGw = aws_ec2.CfnTransitGateway(
            self,
            "DefaultTransitGw",
            default_route_table_association="disable",
        )

        self.tgAttachmentPrivate = aws_ec2.CfnTransitGatewayAttachment(
            self,
            "DefaultTGAttachment",
            transit_gateway_id=self.transitGw.ref,
            vpc_id=self.defaultVpc.vpc_id,
            subnet_ids=[
                self.defaultVpc.private_subnets[0].subnet_id,
                self.defaultVpc.private_subnets[1].subnet_id
            ],
            tags=None)
        self.tgAttachmentPrivate.add_depends_on(self.transitGw)

        self.tgAttachmentEks = aws_ec2.CfnTransitGatewayAttachment(
            self,
            "EksTGAttachment",
            transit_gateway_id=self.transitGw.ref,
            vpc_id=self.eksVpc.vpc_id,
            subnet_ids=[
                self.eksVpc.isolated_subnets[0].subnet_id,
                self.eksVpc.isolated_subnets[1].subnet_id
            ],
            tags=None)
        self.tgAttachmentEks.add_depends_on(self.transitGw)

        isolatedSubnetRoutes = core.Construct(self, 'Isolated Subnet Routes')
        for (i, subnet) in enumerate(self.eksVpc.isolated_subnets):
            aws_ec2.CfnRoute(
                isolatedSubnetRoutes,
                id=f"Default Route EKS {i}",
                route_table_id=subnet.route_table.route_table_id,
                destination_cidr_block="0.0.0.0/0",
                transit_gateway_id=self.transitGw.ref).add_depends_on(
                    self.tgAttachmentEks)

        privateSubnetRoutes = core.Construct(self, 'Private Subnet Routes')
        for (i, subnet) in enumerate(self.defaultVpc.private_subnets):
            aws_ec2.CfnRoute(
                privateSubnetRoutes,
                id=f"Eks route defalt {i}",
                route_table_id=subnet.route_table.route_table_id,
                destination_cidr_block=self.eksVpc.vpc_cidr_block,
                transit_gateway_id=self.transitGw.ref).add_depends_on(
                    self.tgAttachmentEks)

        publicSubnetRoutes = core.Construct(self, 'Public Subnet Routes')
        for (i, subnet) in enumerate(self.defaultVpc.public_subnets):
            aws_ec2.CfnRoute(
                publicSubnetRoutes,
                id=f"Eks route defalt {i}",
                route_table_id=subnet.route_table.route_table_id,
                destination_cidr_block=self.eksVpc.vpc_cidr_block,
                transit_gateway_id=self.transitGw.ref).add_depends_on(
                    self.tgAttachmentEks)

        self.transitGwRT = aws_ec2.CfnTransitGatewayRouteTable(
            self,
            'transitGw Route Table',
            transit_gateway_id=self.transitGw.ref,
            tags=None)

        self.transitGwRoute = aws_ec2.CfnTransitGatewayRoute(
            self,
            'transitGW Route',
            transit_gateway_route_table_id=self.transitGwRT.ref,
            destination_cidr_block='0.0.0.0/0',
            transit_gateway_attachment_id=self.tgAttachmentPrivate.ref)

        self.TGRouteTableAssociationDefaultVPC = aws_ec2.CfnTransitGatewayRouteTableAssociation(
            self,
            'DefaultVPC Association',
            transit_gateway_attachment_id=self.tgAttachmentPrivate.ref,
            transit_gateway_route_table_id=self.transitGwRoute.
            transit_gateway_route_table_id)

        self.TGRouteTablePropagationDefaultVPC = aws_ec2.CfnTransitGatewayRouteTablePropagation(
            self,
            'DefaultVPC Propagation',
            transit_gateway_attachment_id=self.tgAttachmentPrivate.ref,
            transit_gateway_route_table_id=self.transitGwRoute.
            transit_gateway_route_table_id)

        self.TGRouteTableAssociationEksVPC = aws_ec2.CfnTransitGatewayRouteTableAssociation(
            self,
            'EksVPC Association',
            transit_gateway_attachment_id=self.tgAttachmentEks.ref,
            transit_gateway_route_table_id=self.transitGwRoute.
            transit_gateway_route_table_id)

        self.TGRouteTablePropagationEksVPC = aws_ec2.CfnTransitGatewayRouteTablePropagation(
            self,
            'EksVPC Propagation',
            transit_gateway_attachment_id=self.tgAttachmentEks.ref,
            transit_gateway_route_table_id=self.transitGwRoute.
            transit_gateway_route_table_id)
Exemplo n.º 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
        # vpc network
        vpc = aws_ec2.CfnVPC(self,
                             'VPC',
                             cidr_block='10.0.0.0/16',
                             enable_dns_hostnames=True,
                             enable_dns_support=True,
                             instance_tenancy='default',
                             tags=[core.CfnTag(key='Name', value='vpc')])
        internetgateway = aws_ec2.CfnInternetGateway(
            self,
            'internetgateway',
            tags=[core.CfnTag(key='Name', value='internetgateway')])
        aws_ec2.CfnVPCGatewayAttachment(
            self,
            'VPCGatewayAttachment',
            vpc_id=vpc.ref,
            internet_gateway_id=internetgateway.ref)
        networkacl = aws_ec2.CfnNetworkAcl(
            self,
            'NetworkAcl',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='networkacl')])
        aws_ec2.CfnNetworkAclEntry(self,
                                   'NetworkAclEntry01',
                                   network_acl_id=networkacl.ref,
                                   protocol=-1,
                                   rule_action='allow',
                                   rule_number=100,
                                   cidr_block='0.0.0.0/0',
                                   egress=True)
        aws_ec2.CfnNetworkAclEntry(self,
                                   'NetworkAclEntry03',
                                   network_acl_id=networkacl.ref,
                                   protocol=-1,
                                   rule_action='allow',
                                   rule_number=100,
                                   cidr_block='0.0.0.0/0',
                                   egress=False)

        # public network
        publicsubnet01 = aws_ec2.CfnSubnet(
            self,
            'publicsubnet01',
            cidr_block='10.0.0.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1a',
            tags=[core.CfnTag(key='Name', value='publicsubnet01')])
        publicsubnet02 = aws_ec2.CfnSubnet(
            self,
            'publicsubnet02',
            cidr_block='10.0.1.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1c',
            tags=[core.CfnTag(key='Name', value='publicsubnet02')])
        publicsubnet03 = aws_ec2.CfnSubnet(
            self,
            'publicsubnet03',
            cidr_block='10.0.2.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1d',
            tags=[core.CfnTag(key='Name', value='publicsubnet03')])
        publicroutetable01 = aws_ec2.CfnRouteTable(
            self,
            'publicroutetable01',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='publicroutetable01')])
        publicroutetable02 = aws_ec2.CfnRouteTable(
            self,
            'publicroutetable02',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='publicroutetable02')])
        publicroutetable03 = aws_ec2.CfnRouteTable(
            self,
            'publicroutetable03',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='publicroutetable03')])
        aws_ec2.CfnRoute(
            self,
            'publicroute01',
            destination_cidr_block='0.0.0.0/0',
            gateway_id=internetgateway.ref,
            route_table_id=publicroutetable01.ref,
        )
        aws_ec2.CfnRoute(self,
                         'publicroute02',
                         destination_cidr_block='0.0.0.0/0',
                         gateway_id=internetgateway.ref,
                         route_table_id=publicroutetable02.ref)
        aws_ec2.CfnRoute(self,
                         'publicroute03',
                         destination_cidr_block='0.0.0.0/0',
                         gateway_id=internetgateway.ref,
                         route_table_id=publicroutetable03.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'publicsubnetroutetableassociation01',
            route_table_id=publicroutetable01.ref,
            subnet_id=publicsubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'publicsubnetroutetableassociation02',
            route_table_id=publicroutetable02.ref,
            subnet_id=publicsubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'publicsubnetroutetableassociation03',
            route_table_id=publicroutetable03.ref,
            subnet_id=publicsubnet03.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'publicSubnetNetworkAclAssociation01',
            network_acl_id=networkacl.ref,
            subnet_id=publicsubnet01.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'publicSubnetNetworkAclAssociation02',
            network_acl_id=networkacl.ref,
            subnet_id=publicsubnet02.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'publicSubnetNetworkAclAssociation03',
            network_acl_id=networkacl.ref,
            subnet_id=publicsubnet03.ref)

        # private network
        privatesubnet01 = aws_ec2.CfnSubnet(
            self,
            'privatesubnet01',
            cidr_block='10.0.11.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1a',
            tags=[core.CfnTag(key='Name', value='privatesubnet01')])
        privatesubnet02 = aws_ec2.CfnSubnet(
            self,
            'privatesubnet02',
            cidr_block='10.0.12.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1c',
            tags=[core.CfnTag(key='Name', value='privatesubnet02')])
        privatesubnet03 = aws_ec2.CfnSubnet(
            self,
            'privatesubnet03',
            cidr_block='10.0.13.0/24',
            vpc_id=vpc.ref,
            availability_zone='ap-northeast-1d',
            tags=[core.CfnTag(key='Name', value='privatesubnet03')])
        privateroutetable01 = aws_ec2.CfnRouteTable(
            self,
            'privateroutetable01',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='privateroutetable01')])
        privateroutetable02 = aws_ec2.CfnRouteTable(
            self,
            'privateroutetable02',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='privateroutetable02')])
        privateroutetable03 = aws_ec2.CfnRouteTable(
            self,
            'privateroutetable03',
            vpc_id=vpc.ref,
            tags=[core.CfnTag(key='Name', value='privateroutetable03')])
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'privatesubnetroutetableassociation01',
            route_table_id=privateroutetable01.ref,
            subnet_id=privatesubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'privatesubnetroutetableassociation02',
            route_table_id=privateroutetable02.ref,
            subnet_id=privatesubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(
            self,
            'privatesubnetroutetableassociation03',
            route_table_id=privateroutetable03.ref,
            subnet_id=privatesubnet03.ref)
        eip01 = aws_ec2.CfnEIP(self,
                               'eip01',
                               tags=[core.CfnTag(key='Name', value='eip01')])
        eip02 = aws_ec2.CfnEIP(self,
                               'eip02',
                               tags=[core.CfnTag(key='Name', value='eip02')])
        eip03 = aws_ec2.CfnEIP(self,
                               'eip03',
                               tags=[core.CfnTag(key='Name', value='eip03')])
        natgateway01 = aws_ec2.CfnNatGateway(
            self,
            'natgateway01',
            allocation_id=eip01.attr_allocation_id,
            subnet_id=publicsubnet01.ref,
            tags=[core.CfnTag(key='Name', value='natgateway01')])
        natgateway02 = aws_ec2.CfnNatGateway(
            self,
            'natgateway02',
            allocation_id=eip02.attr_allocation_id,
            subnet_id=publicsubnet02.ref,
            tags=[core.CfnTag(key='Name', value='natgateway02')])
        natgateway03 = aws_ec2.CfnNatGateway(
            self,
            'natgateway03',
            allocation_id=eip03.attr_allocation_id,
            subnet_id=publicsubnet03.ref,
            tags=[core.CfnTag(key='Name', value='natgateway03')])
        aws_ec2.CfnRoute(self,
                         'privateroute01',
                         destination_cidr_block='0.0.0.0/0',
                         nat_gateway_id=natgateway01.ref,
                         route_table_id=privateroutetable01.ref)
        aws_ec2.CfnRoute(self,
                         'privateroute02',
                         destination_cidr_block='0.0.0.0/0',
                         nat_gateway_id=natgateway02.ref,
                         route_table_id=privateroutetable02.ref)
        aws_ec2.CfnRoute(self,
                         'privateroute03',
                         destination_cidr_block='0.0.0.0/0',
                         nat_gateway_id=natgateway03.ref,
                         route_table_id=privateroutetable03.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'privateSubnetNetworkAclAssociation01',
            network_acl_id=networkacl.ref,
            subnet_id=privatesubnet01.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'privateSubnetNetworkAclAssociation02',
            network_acl_id=networkacl.ref,
            subnet_id=privatesubnet02.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(
            self,
            'privateSubnetNetworkAclAssociation03',
            network_acl_id=networkacl.ref,
            subnet_id=privatesubnet03.ref)

        # isolate network
        '''
        isolatesubnet01 = aws_ec2.CfnSubnet(self, 'isolatesubnet01', cidr_block='10.0.21.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1a', tags=[core.CfnTag(key='Name', value='isolatesubnet01')])
        isolatesubnet02 = aws_ec2.CfnSubnet(self, 'isolatesubnet02', cidr_block='10.0.22.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1c', tags=[core.CfnTag(key='Name', value='isolatesubnet02')])
        isolatesubnet03 = aws_ec2.CfnSubnet(self, 'isolatesubnet03', cidr_block='10.0.23.0/24', vpc_id=vpc.ref, availability_zone='ap-northeast-1d', tags=[core.CfnTag(key='Name', value='isolatesubnet03')])
        isolateroutetable01 = aws_ec2.CfnRouteTable(self, 'isolateroutetable01', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable01')])
        isolateroutetable02 = aws_ec2.CfnRouteTable(self, 'isolateroutetable02', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable02')])
        isolateroutetable03 = aws_ec2.CfnRouteTable(self, 'isolateroutetable03', vpc_id=vpc.ref, tags=[core.CfnTag(key='Name', value='isolateroutetable03')])
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation01', route_table_id=isolateroutetable01.ref, subnet_id=isolatesubnet01.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation02', route_table_id=isolateroutetable02.ref, subnet_id=isolatesubnet02.ref)
        aws_ec2.CfnSubnetRouteTableAssociation(self, 'isolatesubnetroutetableassociation03', route_table_id=isolateroutetable03.ref, subnet_id=isolatesubnet03.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation01', network_acl_id=networkacl.ref, subnet_id=isolatesubnet01.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation02', network_acl_id=networkacl.ref, subnet_id=isolatesubnet02.ref)
        aws_ec2.CfnSubnetNetworkAclAssociation(self, 'isolateSubnetNetworkAclAssociation03', network_acl_id=networkacl.ref, subnet_id=isolatesubnet03.ref)
        '''
        # output
        core.CfnOutput(self,
                       'output01',
                       value=vpc.ref,
                       description='vpcid',
                       export_name='vpcid01')
        core.CfnOutput(self,
                       'output02',
                       value=publicsubnet01.ref,
                       description='publicsubnet01',
                       export_name='publicsubnet01')
        core.CfnOutput(self,
                       'output03',
                       value=publicsubnet02.ref,
                       description='publicsubnet02',
                       export_name='publicsubnet02')
        core.CfnOutput(self,
                       'output04',
                       value=publicsubnet03.ref,
                       description='publicsubnet03',
                       export_name='publicsubnet03')
        core.CfnOutput(self,
                       'output05',
                       value=privatesubnet01.ref,
                       description='privatesubnet01',
                       export_name='privatesubnet01')
        core.CfnOutput(self,
                       'output06',
                       value=privatesubnet02.ref,
                       description='privatesubnet02',
                       export_name='privatesubnet02')
        core.CfnOutput(self,
                       'output07',
                       value=privatesubnet03.ref,
                       description='privatesubnet03',
                       export_name='privatesubnet03')
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # create defalut vpc (us-east-1)
        # 1 VPC
        # 2 PublicSubnet, 2 Private Subnet
        # 4 Route Table, Each subnet will get each route table
        # Private Route Table will attach NATGateway (2 NATGateway, 2 EIP)
        # Public Route Table will attach InternetGateway
        # vpc = ec2.Vpc(self, "Mindy-VPC")

        # #############################
        # # VPC
        # #############################
        # # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/Vpc.html

        # subnet_amount = 2
        # subnet_list = []

        # # public subnet
        # public_subnet = ec2.SubnetConfiguration(
        #     name = 'My-Public',
        #     subnet_type = ec2.SubnetType.PUBLIC,
        #     cidr_mask=24
        # )
        # subnet_list.append(public_subnet)

        # # private subnet
        # # private_subnet = ec2.SubnetConfiguration(
        # #     name = 'My-Private',
        # #     subnet_type = ec2.SubnetType.PRIVATE,
        # #     cidr_mask=24
        # # )
        # # subnet_list.append(private_subnet)

        # # vpc setting
        # VPC_id = 'My Lab VPC'
        # CIDR = '10.0.0.0/16'
        # vpc = ec2.Vpc(
        #     self,
        #     VPC_id,
        #     cidr=CIDR,
        #     max_azs=subnet_amount,
        #     nat_gateways=0,
        #     nat_gateway_subnets=None,
        #     subnet_configuration=subnet_list,
        #     vpn_connections=None,
        #     vpn_gateway=None,
        #     vpn_gateway_asn=None,
        #     vpn_route_propagation=None
        #     )

        # # output
        # core.CfnOutput(
        #     self,
        #     'VPC-CIDR',
        #     value=vpc.vpc_cidr_block
        # )
        # core.CfnOutput(
        #     self,
        #     'VPC-id',
        #     value=vpc.vpc_id
        # )

        # for i in range(len(vpc.availability_zones)):
        #     core.CfnOutput(
        #         self,
        #         'VPC-AZ-%s'%(i+1),
        #         value=vpc.availability_zones[i]
        #     )

        # for i in range(len(vpc.public_subnets)):
        #     core.CfnOutput(
        #         self,
        #         'VPC-Public-Subnet-%s'%(i+1),
        #         value=vpc.public_subnets[i].subnet_id
        #     )
        #     core.CfnOutput(
        #         self,
        #         'VPC-Public-Subnet-%s-Route-Table-id'%(i+1),
        #         value=vpc.public_subnets[i].route_table.route_table_id
        #     )

        # # for i in range(len(vpc.private_subnets)):
        # #     core.CfnOutput(
        # #         self,
        # #         'VPC-Private-Subnet-%s'%(i+1),
        # #         value=vpc.private_subnets[i].subnet_id
        # #     )
        # #     core.CfnOutput(
        # #         self,
        # #         'VPC-Private-Subnet-%s-Route-Table-id'%(i+1),
        # #         value=vpc.private_subnets[i].route_table.route_table_id
        # #     )
        ##########################
        # Resource
        ##########################
        ##########################
        # VPC setting
        ##########################
        # VPC
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnVPC.html#
        vpc = ec2.CfnVPC(self,
                         'My Lab VPC',
                         cidr_block='10.0.0.0/16',
                         enable_dns_hostnames=None,
                         enable_dns_support=None,
                         instance_tenancy=None,
                         tags=[{
                             'key': 'Name',
                             'value': 'My Lab VPC'
                         }])

        # Sets the deletion policy of the resource based on the removal policy specified.
        vpc.apply_removal_policy(policy=core.RemovalPolicy.DESTROY)

        # Internet Gateway
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnInternetGateway.html
        igw = ec2.CfnInternetGateway(self,
                                     'My Internet Gateway',
                                     tags=[{
                                         'key': 'Name',
                                         'value': 'My IGW'
                                     }])
        igw.apply_removal_policy(policy=core.RemovalPolicy.DESTROY)

        # VPC Gateway Attachment
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnVPCGatewayAttachment.html
        vpc_gateway_attachment = ec2.CfnVPCGatewayAttachment(
            self,
            'My VPC Gateway Attachment',
            vpc_id=vpc.ref,
            internet_gateway_id=igw.ref)

        # Public Route Table
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnRouteTable.html
        public_route_table = ec2.CfnRouteTable(self,
                                               'My Public Route Table',
                                               vpc_id=vpc.ref,
                                               tags=[{
                                                   'key':
                                                   'Name',
                                                   'value':
                                                   'My Public Route Table'
                                               }])

        # Public Route
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnRoute.html
        public_route = ec2.CfnRoute(self,
                                    'My Public Route',
                                    destination_cidr_block='0.0.0.0/0',
                                    route_table_id=public_route_table.ref,
                                    gateway_id=igw.ref)

        # get all az in this regions
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.core/Fn.html
        azs = core.Fn.get_azs()

        # Public Subnet
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnSubnet.html
        public_sunet1 = ec2.CfnSubnet(self,
                                      'Public-Subnet-1',
                                      cidr_block='10.0.1.0/24',
                                      vpc_id=vpc.ref,
                                      assign_ipv6_address_on_creation=None,
                                      availability_zone=core.Fn.select(0, azs),
                                      ipv6_cidr_block=None,
                                      map_public_ip_on_launch=True,
                                      tags=[{
                                          'key': 'Name',
                                          'value': 'Public-Subnet-1'
                                      }])

        public_sunet2 = ec2.CfnSubnet(self,
                                      'Public-Subnet-2',
                                      cidr_block='10.0.3.0/24',
                                      vpc_id=vpc.ref,
                                      assign_ipv6_address_on_creation=None,
                                      availability_zone=core.Fn.select(1, azs),
                                      ipv6_cidr_block=None,
                                      map_public_ip_on_launch=True,
                                      tags=[{
                                          'key': 'Name',
                                          'value': 'Public-Subnet-2'
                                      }])

        # Route Table Association (Public-Subnet-1, Public-Subnet-2)
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnSubnetRouteTableAssociation.html
        associate_public_subnet1 = ec2.CfnSubnetRouteTableAssociation(
            self,
            'PublicSubnet1RouteTableAssociation',
            route_table_id=public_route_table.ref,
            subnet_id=public_sunet1.ref)

        associate_public_subnet2 = ec2.CfnSubnetRouteTableAssociation(
            self,
            'PublicSubnet2RouteTableAssociation',
            route_table_id=public_route_table.ref,
            subnet_id=public_sunet2.ref)

        # NACL Association to subnets
        # https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnSubnetNetworkAclAssociation.html
        public_subnet1_network_acl_association = ec2.CfnSubnetNetworkAclAssociation(
            self,
            'PublicSubnet1NetworkAclAssociation',
            network_acl_id=vpc.attr_default_network_acl,
            subnet_id=public_sunet1.ref)
        public_subnet2_network_acl_association = ec2.CfnSubnetNetworkAclAssociation(
            self,
            'PublicSubnet2NetworkAclAssociation',
            network_acl_id=vpc.attr_default_network_acl,
            subnet_id=public_sunet2.ref)

        ##########################
        # Output
        ##########################
        core.CfnOutput(self, 'vpc-id', value=vpc.ref)
        core.CfnOutput(self, 'vpc-CIDR', value=vpc.cidr_block)
        core.CfnOutput(self, 'igw-id', value=igw.ref)
        core.CfnOutput(self, 'Public Sunet 1', value=public_sunet1.ref)
        core.CfnOutput(self, 'Public Sunet 2', value=public_sunet2.ref)