예제 #1
0
        def network_acl_add(cidr_block, cidr_block_idx=None):
            acl_props = {
                'NetworkAclId':
                Ref(name),
                'RuleNumber':
                int(pieces[1]) +
                cidr_block_idx if cidr_block_idx else int(pieces[1]),
                'Protocol':
                int(pieces[2]),
                'RuleAction':
                pieces[3],
                'CidrBlock':
                fix_refs(cidr_block),
                'Egress':
                pieces[6]
            }
            if pieces[5] != '-':
                port_range = pieces[5].split(':')
                acl_props['PortRange'] = ec2.PortRange(From=port_range[0],
                                                       To=port_range[1])
            if len(pieces) > 7:
                icmp = pieces[7].split(':')
                acl_props['Icmp'] = ec2.ICMP(Code=int(icmp[0]),
                                             Type=int(icmp[1]))

            acl_name = pieces[0]
            if mangle_name:
                acl_name = '%s%sEntry' % (pieces[0], name)
                if cidr_block_idx:
                    acl_name = '%s%s' % (acl_name, cidr_block_idx + 1)
            acl_entries.append(ec2.NetworkAclEntry(acl_name, **acl_props))
예제 #2
0
 def _port_range(self, port_range):
     try:
         (_from, _to) = port_range.split(",")
         p = ec2.PortRange(From=_from, To=_to)
         return p
     except ValueError as e:
         #if isinstance( port_range, ( int, long ) ):
         #    return ec2.PortRange(From=port_range,To=port_range)
         #else:
         print "_port_range: ValueError - input: %s" % port_range
         raise
예제 #3
0
def create_network_acl_entry(template, name, network_acl, rule_number,
                             port_range, rule_action='allow', egress=False,
                             protocol=6, cidr_block=None, **attrs):
    cidr_block = cidr_block or WILDCARD_CIDR
    return template.add_resource(ec2.NetworkAclEntry(
        name,
        NetworkAclId=Ref(network_acl),
        RuleNumber=rule_number,
        Protocol=protocol,
        RuleAction=rule_action,
        Egress=egress,
        CidrBlock=cidr_block,
        PortRange=ec2.PortRange(From=port_range[0], To=port_range[1]),
        **attrs
    ))
예제 #4
0
def get_property(property_name, property_values):
    """
    Gets property from property_name and property_values which troposphere
    supports.
    """
    if isinstance(property_values, int):
        data = {property_name: str(property_values)}
    elif 'Ref' in property_values:
        data = {property_name: Ref(property_values['Ref'])}
    elif 'PortRange' in property_name:
        data = {property_name: ec2.PortRange(**property_values)}
    else:
        data = {property_name: property_values}

    return data
예제 #5
0
    def gen_network_acl(self):
        self.network_acl = ec2.NetworkAcl("NetworkAcl", VpcId=Ref(self.vpc))
        self.template.add_resource(self.network_acl)

        # Allow all inbound and outbound traffic for http, https, and
        # ephemeral ports for load balancers. Deny all other traffic.
        rule_number = 100
        port_ranges = [(80, 80), (443, 443), (1024, 65535)]
        for p in port_ranges:
            for egress in [False, True]:
                entry_type = "Egress" if egress else "Ingress"
                name = f"NetworkAcl{entry_type}{p[0]}"
                network_acl_entry = ec2.NetworkAclEntry(
                    name,
                    NetworkAclId=Ref(self.network_acl),
                    CidrBlock="0.0.0.0/0",
                    Egress=egress,
                    PortRange=ec2.PortRange(From=p[0], To=p[1]),
                    Protocol=6,  # TCP
                    RuleAction="allow",
                    RuleNumber=rule_number,
                )
                self.template.add_resource(network_acl_entry)
            rule_number += 10
예제 #6
0
    def sg_subnet_vpc(self, template, provision_refs):
        ref_stack_id = Ref('AWS::StackId')

        if 'aws_vpc_id' in self.app.config['provision']:
            vpc = self.app.config['provision']['aws_vpc_id']
            use_subnet = self.app.config['provision']['aws_subnet_id']
            use_subnet2 = self.app.config['provision']['aws_subnet2_id']
            use_sg = self.app.config['provision']['aws_sg_id']
            use_alb_sg = self.app.config['provision']['alb_sg_id']
            self.app.log.info(
                'Using your AWS subnet, make sure the routes and ports are configured correctly'
            )
        else:
            vpc = Ref(
                template.add_resource(
                    ec2.VPC('VPC',
                            CidrBlock='10.0.0.0/16',
                            Tags=Tags(Application=ref_stack_id))))

            internet_gateway = template.add_resource(
                ec2.InternetGateway('InternetGateway',
                                    Tags=Tags(Application=ref_stack_id)))

            template.add_resource(
                ec2.VPCGatewayAttachment(
                    'AttachGateway',
                    VpcId=vpc,
                    InternetGatewayId=Ref(internet_gateway)))

            route_table = template.add_resource(
                ec2.RouteTable('RouteTable',
                               VpcId=vpc,
                               Tags=Tags(Application=ref_stack_id)))

            subnet = template.add_resource(
                ec2.Subnet('Subnet',
                           CidrBlock='10.0.0.0/24',
                           VpcId=vpc,
                           AvailabilityZone=Select(0, GetAZs("")),
                           Tags=Tags(Application=ref_stack_id)))

            subnet2 = template.add_resource(
                ec2.Subnet('Subnet2',
                           CidrBlock='10.0.1.0/24',
                           VpcId=vpc,
                           AvailabilityZone=Select(1, GetAZs("")),
                           Tags=Tags(Application=ref_stack_id)))

            template.add_resource(
                ec2.Route(
                    'Route',
                    DependsOn='AttachGateway',
                    GatewayId=Ref('InternetGateway'),
                    DestinationCidrBlock='0.0.0.0/0',
                    RouteTableId=Ref(route_table),
                ))

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'SubnetRouteTableAssociation',
                    SubnetId=Ref(subnet),
                    RouteTableId=Ref(route_table),
                ))

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'Subnet2RouteTableAssociation',
                    SubnetId=Ref(subnet2),
                    RouteTableId=Ref(route_table),
                ))

            network_acl = template.add_resource(
                ec2.NetworkAcl(
                    'NetworkAcl',
                    VpcId=vpc,
                    Tags=Tags(Application=ref_stack_id),
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'InboundSSHNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='100',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='22', To='22'),
                    Egress='false',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'InboundResponsePortsNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='101',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='1024', To='65535'),
                    Egress='false',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'InboundICMPNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='102',
                    Protocol='1',
                    Icmp=ec2.ICMP(Code=-1, Type=-1),
                    Egress='false',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            # Only used when Blockscout is deployed
            template.add_resource(
                ec2.NetworkAclEntry(
                    'InboundHttpsNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='103',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='443', To='443'),
                    Egress='false',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'OutBoundHTTPNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='100',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='80', To='80'),
                    Egress='true',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'OutBoundHTTPSNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='101',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='443', To='443'),
                    Egress='true',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'OutBoundResponsePortsNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='102',
                    Protocol='6',
                    PortRange=ec2.PortRange(From='1024', To='65535'),
                    Egress='true',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.NetworkAclEntry(
                    'OutboundICMPNetworkAclEntry',
                    NetworkAclId=Ref(network_acl),
                    RuleNumber='103',
                    Protocol='1',
                    Icmp=ec2.ICMP(Code=-1, Type=-1),
                    Egress='true',
                    RuleAction='allow',
                    CidrBlock='0.0.0.0/0',
                ))

            template.add_resource(
                ec2.SubnetNetworkAclAssociation(
                    'SubnetNetworkAclAssociation',
                    SubnetId=Ref(subnet),
                    NetworkAclId=Ref(network_acl),
                ))
            template.add_resource(
                ec2.SubnetNetworkAclAssociation(
                    'Subnet2NetworkAclAssociation',
                    SubnetId=Ref(subnet2),
                    NetworkAclId=Ref(network_acl),
                ))
            use_subnet = Ref(subnet)
            use_subnet2 = Ref(subnet2)

            alb_security_group = template.add_resource(
                ec2.SecurityGroup(
                    'ALBSecurityGroup',
                    GroupDescription=
                    'ALB allows traffic from public, is used to terminate SSL',
                    SecurityGroupIngress=[
                        ec2.SecurityGroupRule(IpProtocol='tcp',
                                              FromPort='46658',
                                              ToPort='46658',
                                              CidrIp='0.0.0.0/0'),
                    ],
                    VpcId=vpc,
                ))
            use_alb_sg = Ref(alb_security_group)

            instance_security_group = template.add_resource(
                ec2.SecurityGroup(
                    'InstanceSecurityGroup',
                    GroupDescription='Enable tendermint and SSH for all nodes',
                    SecurityGroupIngress=[
                        ec2.SecurityGroupRule(IpProtocol='tcp',
                                              FromPort='22',
                                              ToPort='22',
                                              CidrIp='0.0.0.0/0'),
                        ec2.SecurityGroupRule(IpProtocol='tcp',
                                              FromPort='46656',
                                              ToPort='46656',
                                              CidrIp='0.0.0.0/0'),
                        ec2.SecurityGroupRule(IpProtocol='tcp',
                                              FromPort='46658',
                                              ToPort='46658',
                                              CidrIp='0.0.0.0/0'),
                        ec2.SecurityGroupRule(IpProtocol='icmp',
                                              FromPort='-1',
                                              ToPort='-1',
                                              CidrIp='0.0.0.0/0'),
                    ],
                    VpcId=vpc,
                ))
            use_sg = Ref(instance_security_group)

        provision_refs.vpc = vpc
        provision_refs.security_group_ec2 = use_sg
        provision_refs.security_group_alb = use_alb_sg
        provision_refs.subnets.append(use_subnet)
        provision_refs.subnets.append(use_subnet2)
예제 #7
0
def dump_base_yaml(cfn_file):

    template = Template()

    vpc_cidr_param = template.add_parameter(
        Parameter(
            "vpcCidrParam",
            Description="string of vpc cidr block to use",
            Type="String",
        ))

    subnet_cidr_param = template.add_parameter(
        Parameter(
            "subnetCidrParam",
            Description="string of subnet cidr block to use",
            Type="String",
        ))

    igw = template.add_resource(
        ec2.InternetGateway(
            "Igw",
            Tags=resource_tags,
        ))

    vpc = template.add_resource(
        ec2.VPC(
            "Vpc",
            CidrBlock=Ref(vpc_cidr_param),
            EnableDnsSupport=True,
            EnableDnsHostnames=True,
            InstanceTenancy="default",
            Tags=resource_tags,
        ))

    igwa = template.add_resource(
        ec2.VPCGatewayAttachment(
            "IgwA",
            VpcId=Ref(vpc),
            InternetGatewayId=Ref(igw),
        ))

    route_tbl = template.add_resource(
        ec2.RouteTable(
            "RouteTable",
            VpcId=Ref(vpc),
            Tags=resource_tags,
        ))

    default_route = template.add_resource(
        ec2.Route("defaultRoute",
                  DestinationCidrBlock="0.0.0.0/0",
                  GatewayId=Ref(igw),
                  RouteTableId=Ref(route_tbl)))

    subnet = template.add_resource(
        ec2.Subnet(
            "Subnet",
            VpcId=Ref(vpc),
            CidrBlock=Ref(subnet_cidr_param),
            MapPublicIpOnLaunch=True,
            AvailabilityZone=Select(0, GetAZs()),
            Tags=resource_tags,
        ))

    route_tbl_asoc = template.add_resource(
        ec2.SubnetRouteTableAssociation("RouteTblSubnetAsoc",
                                        RouteTableId=Ref(route_tbl),
                                        SubnetId=Ref(subnet)))

    priv_route_tbl = template.add_resource(
        ec2.RouteTable(
            "PrivRouteTable",
            VpcId=Ref(vpc),
            Tags=resource_tags,
        ))

    priv_subnet = template.add_resource(
        ec2.Subnet(
            "PrivSubnet",
            VpcId=Ref(vpc),
            CidrBlock="10.10.1.0/24",
            MapPublicIpOnLaunch=False,
            AvailabilityZone=Select(0, GetAZs()),
            Tags=resource_tags,
        ))

    route_tbl_asoc = template.add_resource(
        ec2.SubnetRouteTableAssociation("RouteTblPrivSubnetAsoc",
                                        RouteTableId=Ref(priv_route_tbl),
                                        SubnetId=Ref(priv_subnet)))

    ngw_elastic_ip = template.add_resource(
        ec2.EIP(
            "MyNgwEip",
            Tags=resource_tags,
        ))

    nat_gateway = template.add_resource(
        ec2.NatGateway(
            "MyNatGateway",
            AllocationId=GetAtt(ngw_elastic_ip, "AllocationId"),
            SubnetId=Ref(subnet),
        ))

    private_out_route = template.add_resource(
        ec2.Route("privateOutRoute",
                  DestinationCidrBlock="0.0.0.0/0",
                  NatGatewayId=Ref(nat_gateway),
                  RouteTableId=Ref(priv_route_tbl)))

    first_network_acl = template.add_resource(
        ec2.NetworkAcl(
            "MyFirstNetAcl",
            Tags=resource_tags,
            VpcId=Ref(vpc),
        ))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry(
            "MyPrivOutNetAclEntry",
            NetworkAclId=Ref(first_network_acl),
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            Egress=True,
            RuleAction="allow",
            RuleNumber=100,
        ))

    network_inbound_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyInNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="74.77.86.69/32",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=100,
                            PortRange=ec2.PortRange(From=22, To=22)))

    private_to_public_client_ports_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubClientPortsNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="10.10.1.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=101,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_internet_client_ports_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPub2DefaultClientPortsNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="0.0.0.0/0",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=102,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_private_icmpv4_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPubIcmpv4NetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="10.10.1.0/24",
                            Protocol=1,
                            Icmp=ec2.ICMP(Code=-1, Type=-1),
                            RuleAction="allow",
                            RuleNumber=103))

    second_network_acl = template.add_resource(
        ec2.NetworkAcl(
            "MySecondNetAcl",
            Tags=resource_tags,
            VpcId=Ref(vpc),
        ))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPriv2InternetClientPortsNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="0.0.0.0/0",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=100,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_private_ssh_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivSshNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=101,
                            PortRange=ec2.PortRange(From=22, To=22)))

    public_to_private_http_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivHttpNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=102,
                            PortRange=ec2.PortRange(From=80, To=80)))

    private_to_public_icmpv4_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivIcmpv4NetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=1,
                            Icmp=ec2.ICMP(Code=-1, Type=-1),
                            RuleAction="allow",
                            RuleNumber=103))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry(
            "MyPubOutNetAclEntry",
            NetworkAclId=Ref(second_network_acl),
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            Egress=True,
            RuleAction="allow",
            RuleNumber=100,
        ))

    subnet_nacl_asociation = template.add_resource(
        ec2.SubnetNetworkAclAssociation("subNaclAsoc",
                                        NetworkAclId=Ref(first_network_acl),
                                        SubnetId=Ref(subnet)))

    priv_subnet_nacl_asociation = template.add_resource(
        ec2.SubnetNetworkAclAssociation("privSubNaclAsoc",
                                        NetworkAclId=Ref(second_network_acl),
                                        SubnetId=Ref(priv_subnet)))

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
        Output(
            "PrivSubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(priv_subnet),
            Export=Export("PrivSubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
예제 #8
0
    def __init__(
        self,
        region: str,
        cidr_block: str,
        name: str = "VPC",
        internet_access_enabled: bool = True,
        internal_networks: list = [],
    ):
        """Create VPC, internet gateway, route tables and network ACLs

        Args:
            region (str): Region to use when setting up the VPC. The
                maximum number of subnets set up depends on the number
                of availability zones present in the region.
            cidr_block (str): IP range used by the VPC
            name (str, optional): VPC name. Defaults to "VPC".
            internet_access_enabled (bool, optional): If False, internet
                gateway will not be set up. Public network ACLs and
                route tables will still be created.
                Defaults to True.
            internal_networks (list, optional): IP ranges for private
                networks that this VPC will be connected to. They will
                be added to network ACLs. Defaults to [].
        """
        self.name = name
        self.region = region
        self.cidr_block = cidr_block
        self.internal_networks = internal_networks
        self.internet_access_enabled = internet_access_enabled
        self.public_subnets = []
        # Gateway subnets are public subnets hosting exit points like
        # NAT Gateway and VPC Endpoint interfaces
        self.gateway_subnets = []
        self.public_route_table = None
        self.natted_route_tables = []
        self.nat_gateways = []
        self._t = Template()  # Template
        self._r = dict()  # Resources
        self._o = dict()  # Outputs
        self._r["Vpc"] = t_ec2.VPC(
            title=f"{self.name}Vpc",
            CidrBlock=self.cidr_block,
            EnableDnsHostnames=True,
            EnableDnsSupport=True,
            Tags=[{
                "Key": "Name",
                "Value": self.name
            }],
        )
        self.vpc = self._r["Vpc"]
        self._o["VpcId"] = Output(
            title="VpcId",
            Value=Ref(self.vpc),
            Export=Export(Sub("${AWS::StackName}-vpc-id")),
        )
        if internet_access_enabled:
            # Create Internet Gateway
            title = "Igw"
            self._r[title] = t_ec2.InternetGateway(
                title=title,
                Tags=[{
                    "Key": "Name",
                    "Value": f"{self.name}-igw"
                }],
            )
            self._r["igw_attachment"] = t_ec2.VPCGatewayAttachment(
                title="IgwAttachment",
                VpcId=Ref(self.vpc),
                InternetGatewayId=Ref(self._r["Igw"]),
            )
        # Public routing table
        self._r["PubRouteTable"] = t_ec2.RouteTable(
            title="PubRouteTable",
            VpcId=Ref(self.vpc),
            Tags=[{
                "Key": "Name",
                "Value": "Public"
            }],
        )
        self.public_route_table = self._r["PubRouteTable"]
        if internet_access_enabled:
            self._r["pub_rtt_rt_pub"] = t_ec2.Route(
                title="PubRoute",
                RouteTableId=Ref(self._r["PubRouteTable"]),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=Ref(self._r["Igw"]),
            )
        # Network ACL for public subnets
        self._r["PubNacl"] = t_ec2.NetworkAcl(
            title="PubNacl",
            VpcId=Ref(self.vpc),
            Tags=[{
                "Key": "Name",
                "Value": "Public"
            }],
        )
        self.public_nacl = self._r["PubNacl"]
        self._r["pub_nacl_out_all"] = t_ec2.NetworkAclEntry(
            title="PubNaclOutAll",
            NetworkAclId=Ref(self.public_nacl),
            Egress=True,
            RuleNumber=500,
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            RuleAction="allow",
        )
        self._r["pub_nacl_in_icmp"] = t_ec2.NetworkAclEntry(
            title="PubNaclInIcmp",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=99,
            CidrBlock="0.0.0.0/0",
            Protocol=1,
            Icmp=t_ec2.ICMP(Code=-1, Type=-1),
            RuleAction="allow",
        )
        self._r["pub_nacl_in_vpc"] = t_ec2.NetworkAclEntry(
            title="PubNaclInVpc",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=100,
            CidrBlock=GetAtt(self.vpc, "CidrBlock"),
            Protocol=-1,
            RuleAction="allow",
        )
        for index, cidr_block in enumerate(self.internal_networks):
            self._r[f"pub_nacl_in_internal_{index}"] = t_ec2.NetworkAclEntry(
                title=f"PubNaclInInternal{index}",
                NetworkAclId=Ref(self.public_nacl),
                Egress=False,
                RuleNumber=101 + index,
                CidrBlock=cidr_block,
                Protocol=-1,
                RuleAction="allow",
            )
        self._r["pub_nacl_in_ssh"] = t_ec2.NetworkAclEntry(
            title="PubNaclInSsh",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=210,
            CidrBlock="0.0.0.0/0",
            Protocol=6,
            PortRange=t_ec2.PortRange(From=22, To=22),
            RuleAction="allow",
        )
        self._r["pub_nacl_in_http"] = t_ec2.NetworkAclEntry(
            title="PubNaclInHttp",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=220,
            CidrBlock="0.0.0.0/0",
            Protocol=6,
            PortRange=t_ec2.PortRange(From=80, To=80),
            RuleAction="allow",
        )
        self._r["pub_nacl_in_https"] = t_ec2.NetworkAclEntry(
            title="PubNaclInHttps",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=221,
            CidrBlock="0.0.0.0/0",
            Protocol=6,
            PortRange=t_ec2.PortRange(From=443, To=443),
            RuleAction="allow",
        )
        self._r["pub_nacl_in_nat_tcp"] = t_ec2.NetworkAclEntry(
            title="PubNaclInNatTcp",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=500,
            CidrBlock="0.0.0.0/0",
            Protocol=6,
            PortRange=t_ec2.PortRange(From=1024, To=65535),
            RuleAction="allow",
        )
        self._r["pub_nacl_in_nat_udp"] = t_ec2.NetworkAclEntry(
            title="PubNaclInNatUdp",
            NetworkAclId=Ref(self.public_nacl),
            Egress=False,
            RuleNumber=501,
            CidrBlock="0.0.0.0/0",
            Protocol=17,
            PortRange=t_ec2.PortRange(From=1024, To=65535),
            RuleAction="allow",
        )
        # Network ACL for private subnets
        self._r["InternalNacl"] = t_ec2.NetworkAcl(
            title="InternalNacl",
            VpcId=Ref(self.vpc),
            Tags=[{
                "Key": "Name",
                "Value": "Private"
            }],
        )
        self.internal_nacl = self._r["InternalNacl"]
        self._r["internal_nacl_out_all"] = t_ec2.NetworkAclEntry(
            title="InternalNaclOutAll",
            NetworkAclId=Ref(self.internal_nacl),
            Egress=True,
            RuleNumber=500,
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            RuleAction="allow",
        )
        self._r["internal_nacl_in_icmp"] = t_ec2.NetworkAclEntry(
            title="InternalNaclInIcmp",
            NetworkAclId=Ref(self.internal_nacl),
            Egress=False,
            RuleNumber=99,
            CidrBlock="0.0.0.0/0",
            Protocol=1,
            Icmp=t_ec2.ICMP(Code=-1, Type=-1),
            RuleAction="allow",
        )
        self._r["internal_nacl_in_vpc"] = t_ec2.NetworkAclEntry(
            title="InternalNaclInVpc",
            NetworkAclId=Ref(self.internal_nacl),
            Egress=False,
            RuleNumber=100,
            CidrBlock=GetAtt(self.vpc, "CidrBlock"),
            Protocol=-1,
            RuleAction="allow",
        )
        for index, cidr_block in enumerate(self.internal_networks):
            self._r[
                f"internal_nacl_in_internal_{index}"] = t_ec2.NetworkAclEntry(
                    title=f"InternalNaclInInternal{index}",
                    NetworkAclId=Ref(self.internal_nacl),
                    Egress=False,
                    RuleNumber=101 + index,
                    CidrBlock=cidr_block,
                    Protocol=-1,
                    RuleAction="allow",
                )
        self._r["internal_nacl_in_nat_tcp"] = t_ec2.NetworkAclEntry(
            title="InternalNaclInNatTcp",
            NetworkAclId=Ref(self.internal_nacl),
            Egress=False,
            RuleNumber=500,
            CidrBlock="0.0.0.0/0",
            Protocol=6,
            PortRange=t_ec2.PortRange(From=1024, To=65535),
            RuleAction="allow",
        )
        self._r["internal_nacl_in_nat_udp"] = t_ec2.NetworkAclEntry(
            title="InternalNaclInNatUdp",
            NetworkAclId=Ref(self.internal_nacl),
            Egress=False,
            RuleNumber=501,
            CidrBlock="0.0.0.0/0",
            Protocol=17,
            PortRange=t_ec2.PortRange(From=1024, To=65535),
            RuleAction="allow",
        )
예제 #9
0
def east_vpc_stack(cfn_file):

    template = Template()

    vpc_cidr_param = template.add_parameter(
        Parameter(
            "vpcCidrParam",
            Description="string of vpc cidr block to use",
            Type="String",
        ))

    subnet_cidr_param = template.add_parameter(
        Parameter(
            "subnetCidrParam",
            Description="string of subnet cidr block to use",
            Type="String",
        ))

    west_peer_cidr_param = template.add_parameter(
        Parameter(
            "westPeerCidrParam",
            Type="String",
        ))

    igw = template.add_resource(
        ec2.InternetGateway(
            "Igw",
            Tags=resource_tags,
        ))

    vpc = template.add_resource(
        ec2.VPC(
            "Vpc",
            CidrBlock=Ref(vpc_cidr_param),
            EnableDnsSupport=True,
            EnableDnsHostnames=True,
            InstanceTenancy="default",
            Tags=resource_tags,
        ))

    igwa = template.add_resource(
        ec2.VPCGatewayAttachment(
            "IgwA",
            VpcId=Ref(vpc),
            InternetGatewayId=Ref(igw),
        ))

    route_tbl = template.add_resource(
        ec2.RouteTable(
            "RouteTable",
            VpcId=Ref(vpc),
            Tags=resource_tags,
        ))

    default_route = template.add_resource(
        ec2.Route("defaultRoute",
                  DestinationCidrBlock="0.0.0.0/0",
                  GatewayId=Ref(igw),
                  RouteTableId=Ref(route_tbl)))

    # stage 3: delete me and update to remove peering stack
    # peer_route=template.add_resource(
    #     ec2.Route(
    #         "peerRoute",
    #         DestinationCidrBlock=Ref(west_peer_cidr_param),
    #         VpcPeeringConnectionId="pcx-0d27f0252e6c8ac93",
    #         RouteTableId=Ref(route_tbl)
    #     )
    # )
    # /stage3

    subnet = template.add_resource(
        ec2.Subnet(
            "Subnet",
            VpcId=Ref(vpc),
            CidrBlock=Ref(subnet_cidr_param),
            MapPublicIpOnLaunch=True,
            AvailabilityZone=Select(0, GetAZs()),
            Tags=resource_tags,
        ))

    route_tbl_asoc = template.add_resource(
        ec2.SubnetRouteTableAssociation("RouteTblSubnetAsoc",
                                        RouteTableId=Ref(route_tbl),
                                        SubnetId=Ref(subnet)))

    my_net_acl = template.add_resource(
        ec2.NetworkAcl(
            "MyFirstNetAcl",
            Tags=resource_tags,
            VpcId=Ref(vpc),
        ))

    template.add_resource(
        ec2.NetworkAclEntry(
            "MyAllOutNetAclEntry",
            NetworkAclId=Ref(my_net_acl),
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            Egress=True,
            RuleAction="allow",
            RuleNumber=100,
        ))

    template.add_resource(
        ec2.NetworkAclEntry("MyInNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock="74.77.86.69/32",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=100,
                            PortRange=ec2.PortRange(From=22, To=22)))

    template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock=Ref(west_peer_cidr_param),
                            Protocol=-1,
                            RuleAction="allow",
                            RuleNumber=101))

    template.add_resource(
        ec2.NetworkAclEntry("MyClientPortsNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock="0.0.0.0/0",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=102,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    template.add_resource(
        ec2.SubnetNetworkAclAssociation("subNaclAsoc",
                                        NetworkAclId=Ref(my_net_acl),
                                        SubnetId=Ref(subnet)))

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
예제 #10
0
template.add_resource(VpcGatewayAttachment)

# Add VPC Network ACL
resource_tags.update({"Name": "ApiDev-Dev-NetworkAcl"})
VpcNetworkAcl = ec2.NetworkAcl("VpcNetworkAcl",
                               Tags=Tags(resource_tags),
                               VpcId=Ref("VPC"))
template.add_resource(VpcNetworkAcl)

# Add ACL rule for inbound public traffic over port 443
VpcNetworkAclInboundRulePublic443 = ec2.NetworkAclEntry(
    "VpcNetworkAclInboundRulePublic443",
    CidrBlock="0.0.0.0/0",
    Egress="false",
    NetworkAclId=Ref("VpcNetworkAcl"),
    PortRange=ec2.PortRange(From="443", To="443"),
    Protocol="6",
    RuleAction="allow",
    RuleNumber=20001)
template.add_resource(VpcNetworkAclInboundRulePublic443)

# Add ACL rule for inbound public traffic over port 80
VpcNetworkAclInboundRulePublic80 = ec2.NetworkAclEntry(
    "VpcNetworkAclInboundRulePublic80",
    CidrBlock="0.0.0.0/0",
    Egress="false",
    NetworkAclId=Ref("VpcNetworkAcl"),
    PortRange=ec2.PortRange(From="80", To="80"),
    Protocol="6",
    RuleAction="allow",
    RuleNumber=20000)
예제 #11
0
        ec2.NetworkAclEntry(
            "InboundDeny",
            CidrBlock="0.0.0.0/0",
            NetworkAclId=Ref(nacl),
            Protocol=-1,
            RuleAction="deny",
            RuleNumber=10,
        )
    )

    naclINSSH = t.add_resource(
        ec2.NetworkAclEntry(
            "SSHAllow",
            CidrBlock=Join("", [Ref(sshAddress), "/32"]),
            NetworkAclId=Ref(nacl),
            PortRange=ec2.PortRange(From=22, To=22),
            Protocol=6,
            RuleAction="allow",
            RuleNumber=20,
        )
    )

    naclOut = t.add_resource(
        ec2.NetworkAclEntry(
            "OutBoundAllow",
            CidrBlock="0.0.0.0/0",
            Egress=True,
            NetworkAclId=Ref(nacl),
            Protocol=-1,
            RuleAction="allow",
            RuleNumber=10,
예제 #12
0
    Tags=Tags(Name='PublicACL')
))

subnetNetworkAclAssociation = t.add_resource(ec2.SubnetNetworkAclAssociation(
    'SubnetNetworkAclAssociation',
    SubnetId=Ref(subnet_public),
    NetworkAclId=Ref(public_subnet_acl),
))

# outbound acls for Public network
t.add_resource(ec2.NetworkAclEntry(
        'sshOutbound',
        NetworkAclId=Ref(public_subnet_acl),
        RuleNumber='90',
        Protocol='6',
        PortRange=ec2.PortRange(To='22', From='22'),
        Egress='true',
        RuleAction='allow',
        CidrBlock='0.0.0.0/0',
))
t.add_resource(ec2.NetworkAclEntry(
        'OutBoundResponsePortsNetworkAclEntry',
        NetworkAclId=Ref(public_subnet_acl),
        RuleNumber='100',
        Protocol='6',
        PortRange=ec2.PortRange(From='49152', To='65535'),
        Egress='true',
        RuleAction='allow',
        CidrBlock='0.0.0.0/0',
))
t.add_resource(ec2.NetworkAclEntry(
예제 #13
0
    def configure(self):
        self.vpc_metadata = constants.ENVIRONMENTS[self.env]['vpc']
        self.set_description('VPC, Routes, Base Security Groups, and NATs')

        common_vpc_tags = [ec2.Tag('Name', self.env)
                           ] + self.get_tags(service_override='VPC')

        _vpc = self.add_resource(
            ec2.VPC('VPC',
                    CidrBlock=self.vpc_metadata['cidrblock'],
                    EnableDnsSupport=True,
                    EnableDnsHostnames=True,
                    Tags=common_vpc_tags))

        _dhcp_options = self.add_resource(
            ec2.DHCPOptions('DHCPOptions',
                            DomainName="node.{}.{}".format(
                                self.env, constants.TAG),
                            DomainNameServers=['AmazonProvidedDNS'],
                            Tags=common_vpc_tags))

        self.add_resource(
            ec2.VPCDHCPOptionsAssociation('VPCDHCPOptionsAssociation',
                                          DhcpOptionsId=Ref(_dhcp_options),
                                          VpcId=Ref(_vpc)))

        _internet_gateway = self.add_resource(
            ec2.InternetGateway('InternetGateway',
                                Tags=self.get_tags(
                                    service_override='InternetGateway',
                                    role_override='InternetGateway')))
        self.add_resource(
            ec2.VPCGatewayAttachment('AttachInternetGateway',
                                     VpcId=Ref(_vpc),
                                     InternetGatewayId=Ref(_internet_gateway)))
        # route_tables stores all ec2.RouteTables generated and adds them to
        # a private vpc s3 endpoint
        route_tables = []
        _public_route_table = self.add_resource(
            ec2.RouteTable('PublicRouteTable',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PublicRouteTable',
                               role_override='PublicRouteTable')))
        route_tables.append(_public_route_table)
        # Public Subnet Routes and ACLs
        self.add_resource(
            ec2.Route('PublicRoute',
                      RouteTableId=Ref(_public_route_table),
                      DestinationCidrBlock='0.0.0.0/0',
                      GatewayId=Ref(_internet_gateway)))
        _public_network_acl = self.add_resource(
            ec2.NetworkAcl('PublicNetworkAcl',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PublicNetworkAcl',
                               role_override='PublicNetworkAcl')))
        self.add_resource(
            ec2.NetworkAclEntry('IngressPublicNetworkAclEntry',
                                NetworkAclId=Ref(_public_network_acl),
                                RuleNumber=100,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=False,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        self.add_resource(
            ec2.NetworkAclEntry('EgressPublicNetworkAclEntry',
                                NetworkAclId=Ref(_public_network_acl),
                                RuleNumber=101,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=True,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        # Private Network ACLs
        _private_network_acl = self.add_resource(
            ec2.NetworkAcl('PrivateNetworkAcl',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PrivateNetworkAcl',
                               role_override='PrivateNetworkAcl')))
        self.add_resource(
            ec2.NetworkAclEntry('IngressPrivateNetworkAclEntry',
                                NetworkAclId=Ref(_private_network_acl),
                                RuleNumber=100,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=False,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        self.add_resource(
            ec2.NetworkAclEntry('EgressPrivateNetworkAclEntry',
                                NetworkAclId=Ref(_private_network_acl),
                                RuleNumber=101,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=True,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))

        # Default security groups - referenced by name by constants/default-security-groups
        # _nat_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'NATSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Security Group for NAT Instances',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': '-1', 'FromPort': 1, 'ToPort': 65535, 'CidrIp': self.vpc_metadata['cidrblock']},
        #             {'IpProtocol': '-1', 'FromPort': 1, 'ToPort': 65535, 'CidrIp': '10.0.0.0/8'}
        #         ],
        #         Tags=self.get_tags(service_override='NAT', role_override='NAT-SecurityGroup')
        #     )
        # )
        # _consul_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'ConsulSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Security Group for Consul access',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': 'tcp', 'FromPort': 8300, 'ToPort': 8302, 'CidrIp': '10.0.0.0/8'},  # consul server rpc/serf
        #             {'IpProtocol': 'udp', 'FromPort': 8300, 'ToPort': 8302, 'CidrIp': '10.0.0.0/8'},  # consul server rpc/serf
        #             {'IpProtocol': 'tcp', 'FromPort': 8400, 'ToPort': 8400, 'CidrIp': '10.0.0.0/8'},  # consul client rpc
        #             {'IpProtocol': 'tcp', 'FromPort': 8500, 'ToPort': 8500, 'CidrIp': '10.0.0.0/8'},  # consul http
        #             {'IpProtocol': 'tcp', 'FromPort': 8600, 'ToPort': 8600, 'CidrIp': '10.0.0.0/8'},  # consul dns
        #             {'IpProtocol': 'udp', 'FromPort': 8600, 'ToPort': 8600, 'CidrIp': '10.0.0.0/8'}   # consul dns
        #         ],
        #         Tags=[
        #             ec2.Tag('ivy:team', self.TEAM['email']),
        #             ec2.Tag('ivy:environment', self.env),
        #             ec2.Tag('ivy:service', 'Consul'),
        #             ec2.Tag('ivy:role', 'Consul-SecurityGroup')
        #         ]
        #     )
        # )
        # _ssh_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'InternalSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Internal Rules',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'CidrIp': '10.0.0.0/8'},
        #             {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'CidrIp': '10.0.0.0/8'}
        #         ],
        #         SecurityGroupEgress=[
        #             {'IpProtocol': '-1', 'FromPort': 0, 'ToPort': 65535, 'CidrIp': '0.0.0.0/0'}
        #         ],
        #         Tags=[
        #             ec2.Tag('ivy:team', self.TEAM['email']),
        #             ec2.Tag('ivy:environment', self.env),
        #             ec2.Tag('ivy:service', 'infrastructure'),
        #             ec2.Tag('ivy:role', 'internal')
        #         ]
        #     )
        # )
        #
        # self.add_security_group(Ref(_nat_security_group), Ref(_consul_security_group), Ref(_ssh_security_group))

        ## This sets up all private and public AZs
        for index, zone in enumerate(self.vpc_metadata['zones'], 1):
            _public_subnet = self.add_resource(
                ec2.Subnet(
                    'PublicSubnet{}'.format(index),
                    VpcId=Ref(_vpc),
                    CidrBlock=zone['public-cidrblock'],
                    AvailabilityZone=zone['availability-zone'],
                    MapPublicIpOnLaunch=True,
                    Tags=self.get_tags(
                        service_override='PublicSubnet',
                        role_override='PublicSubnet{}'.format(index)) +
                    [
                        ec2.Tag('Name', '{}-PublicSubnet{}'.format(
                            self.env, index))
                    ]))
            self.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PublicSubnetRouteTableAssociation{}'.format(index),
                    SubnetId=Ref(_public_subnet),
                    RouteTableId=Ref(_public_route_table)))
            self.add_resource(
                ec2.SubnetNetworkAclAssociation(
                    'PublicSubnetNetworkAclAssociation{}'.format(index),
                    SubnetId=Ref(_public_subnet),
                    NetworkAclId=Ref(_public_network_acl)))

            # Allow VPCs with no private subnets (save money on NAT instances for VPCs with only public instances)
            if zone.get('private-cidrblock'):
                _private_subnet = self.add_resource(
                    ec2.Subnet(
                        'PrivateSubnet{}'.format(index),
                        VpcId=Ref(_vpc),
                        CidrBlock=zone['private-cidrblock'],
                        AvailabilityZone=zone['availability-zone'],
                        Tags=self.get_tags(
                            service_override='PrivateSubnet',
                            role_override='PrivateSubnet{}'.format(index)) + [
                                ec2.Tag(
                                    'Name', '{}-PrivateSubnet{}'.format(
                                        self.env, index))
                            ]))
                # Private subnets get their own route table for AZ-specific NATs
                _private_route_table = self.add_resource(
                    ec2.RouteTable(
                        'PrivateRouteTable{}'.format(index),
                        VpcId=Ref(_vpc),
                        Tags=self.get_tags(
                            service_override='PrivateRouteTable',
                            role_override='PrivateRouteTable{}'.format(
                                index))))
                route_tables.append(_private_route_table)

                # Create an EIP to be used with the NAT instance or gateway
                _nat_eip = self.add_resource(
                    ec2.EIP('NATInstanceEIP{}'.format(index), Domain='vpc'))

                # Use VPC NAT Gateway
                _nat_gw = self.add_resource(
                    ec2.NatGateway('NATGateway{}'.format(index),
                                   AllocationId=GetAtt(_nat_eip,
                                                       "AllocationId"),
                                   SubnetId=Ref(_public_subnet)))
                # Create a route via the NAT GW for the private route table
                self.add_resource(
                    ec2.Route('PrivateRoute{}'.format(index),
                              RouteTableId=Ref(_private_route_table),
                              DestinationCidrBlock='0.0.0.0/0',
                              NatGatewayId=Ref(_nat_gw)))

                self.add_resource(
                    ec2.SubnetRouteTableAssociation(
                        'PrivateSubnetRouteTableAssociation{}'.format(index),
                        SubnetId=Ref(_private_subnet),
                        RouteTableId=Ref(_private_route_table)))
                self.add_resource(
                    ec2.SubnetNetworkAclAssociation(
                        'PrivateSubnetNetworkAclAssociation{}'.format(index),
                        SubnetId=Ref(_private_subnet),
                        NetworkAclId=Ref(_private_network_acl)))

        # use route_table to create a VPC S3 endpoint
        self.add_resource(
            ec2.VPCEndpoint('S3VPCEndpoint',
                            RouteTableIds=[Ref(rt) for rt in route_tables],
                            ServiceName='com.amazonaws.{}.s3'.format(
                                self.region),
                            VpcId=Ref(_vpc)))
예제 #14
0
    def __setup_template(self):
        """
        Produces a valid template instance which can then be print as json or yaml
        """
        template = Template()
        template.add_description("Service VPC - used for services")

        template.add_metadata({
            "Build": "development",
            "DependsOn": [],
            "Environment": "ApiDev",
            "Revision": "develop",
            "StackName": "ApiDev-Dev-VPC",
            "StackType": "InfrastructureResource",
            "TemplateBucket": "cfn-apidev",
            "TemplateName": "VPC",
            "TemplatePath": "ApiDev/Dev/VPC"
        })

        vpc = template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock="10.0.0.0/16",
                EnableDnsHostnames="true",
                EnableDnsSupport="true",
                InstanceTenancy="default",
                Tags=self.__get_tags("ServiceVPC"),
            )
        )

        instance_sg = template.add_resource(
            ec2.SecurityGroup(
                "BastionSG",
                GroupDescription="Used for source/dest rules",
                Tags=self.__get_tags("VPC-Bastion-SG"),
                VpcId=Ref(
                    vpc
                )
            ),
        )

        cw_alarm_topic = template.add_resource(
            Topic(
                "CloudWatchAlarmTopic",
                TopicName="ApiDev-Dev-CloudWatchAlarms",
            )
        )

        dhcp_options = template.add_resource(
            ec2.DHCPOptions(
                "DhcpOptions",
                DomainName=Join(
                    "",
                    [
                        Ref("AWS::Region"),
                        ".compute.internal"
                    ]
                ),
                DomainNameServers=["AmazonProvidedDNS"],
                Tags=self.__get_tags("DhcpOptions"),
            )
        )

        gateway = template.add_resource(
            ec2.InternetGateway(
                "InternetGateway",
                Tags=self.__get_tags("InternetGateway")
            )
        )

        nat_emergency_topic = template.add_resource(
            Topic(
                "NatEmergencyTopic",
                TopicName="ApiDev-Dev-NatEmergencyTopic",
            )
        )

        vpc_dhcp_options_assoc = template.add_resource(
            ec2.VPCDHCPOptionsAssociation(
                "VpcDhcpOptionsAssociation",
                DhcpOptionsId=Ref(
                    dhcp_options
                ),
                VpcId=Ref(
                    vpc
                )
            )
        )

        vpc_gw_attachment = template.add_resource(
            ec2.VPCGatewayAttachment(
                "VpcGatewayAttachment",
                InternetGatewayId=Ref(
                    gateway
                ),
                VpcId=Ref(
                    vpc
                )
            )
        )

        vpc_network_acl = template.add_resource(
            ec2.NetworkAcl(
                "VpcNetworkAcl",
                Tags=self.__get_tags("NetworkAcl"),
                VpcId=Ref(
                    vpc
                )
            )
        )

        vpc_network_acl_rules = template.add_resource([
            ec2.NetworkAclEntry(
                "VpcNetworkAclInboundRulePublic443",
                CidrBlock="0.0.0.0/0",
                Egress="false",
                NetworkAclId=Ref(
                    vpc_network_acl
                ),
                PortRange=ec2.PortRange(
                    From="443",
                    To="443",
                ),
                Protocol="6",
                RuleAction="allow",
                RuleNumber=20001
            ),
            ec2.NetworkAclEntry(
                "VpcNetworkAclInboundRulePublic80",
                CidrBlock="0.0.0.0/0",
                Egress="false",
                NetworkAclId=Ref(
                    vpc_network_acl
                ),
                PortRange=ec2.PortRange(
                    From="80",
                    To="80",
                ),
                Protocol="6",
                RuleAction="allow",
                RuleNumber=20000
            ),
            ec2.NetworkAclEntry(
                "VpcNetworkAclOutboundRule",
                CidrBlock="0.0.0.0/0",
                Egress="true",
                NetworkAclId=Ref(
                    vpc_network_acl
                ),
                Protocol="-1",
                RuleAction="allow",
                RuleNumber=30000
            ),
            ec2.NetworkAclEntry(
                "VpcNetworkAclSsh",
                CidrBlock="127.0.0.1/32",
                Egress="false",
                NetworkAclId=Ref(
                    vpc_network_acl
                ),
                PortRange=ec2.PortRange(
                    From="22",
                    To="22",
                ),
                Protocol="6",
                RuleAction="allow",
                RuleNumber=10000
            )
        ])

        template.add_output([
            Output(
                "BastionSG",
                Value=Ref(instance_sg)
            ),
            Output(
                "CloudWatchAlarmTopic",
                Value=Ref(cw_alarm_topic)
            ),
            Output(
                "InternetGateway",
                Value=Ref(gateway)
            ),
            Output(
                "NatEmergencyTopicARN",
                Value=Ref(nat_emergency_topic)
            ),
            Output(
                "VPCID",
                Value=Ref(vpc)
            ),
            Output(
                "VPCName",
                Value=Ref("AWS::StackName")
            ),
            Output(
                "VpcNetworkAcl",
                Value=Ref(vpc_network_acl)
            )

        ])

        return template
networkAcl = t.add_resource(
    ec2.NetworkAcl(
        'NetworkAcl',
        VpcId=Ref(VPC),
        Tags=Tags(
            Application=ref_stack_id),
    ))

inBoundPrivateNetworkAclEntry = t.add_resource(
    ec2.NetworkAclEntry(
        'InboundHTTPNetworkAclEntry',
        NetworkAclId=Ref(networkAcl),
        RuleNumber='100',
        Protocol='6',
        PortRange=ec2.PortRange(To='80', From='80'),
        Egress='false',
        RuleAction='allow',
        CidrBlock=ALLOW_ALL_CIDR,
    ))

inboundSSHNetworkAclEntry = t.add_resource(
    ec2.NetworkAclEntry(
        'InboundSSHNetworkAclEntry',
        NetworkAclId=Ref(networkAcl),
        RuleNumber='101',
        Protocol='6',
        PortRange=ec2.PortRange(To='22', From='22'),
        Egress='false',
        RuleAction='allow',
        CidrBlock=ALLOW_ALL_CIDR,