Пример #1
0
def create_subnets():
    return [
        ec2.Subnet(
            'subnetA',
            AvailabilityZone='us-east-1a',
            CidrBlock=Ref('cidrSubnetA'),
            MapPublicIpOnLaunch=True,
            Tags=_tags(),
            VpcId=Ref('vpc'),
        ),
        ec2.SubnetRouteTableAssociation(
            'subnetAToRouteTable',
            RouteTableId=Ref('routeTable'),
            SubnetId=Ref('subnetA'),
        ),
        ec2.Subnet(
            'subnetB',
            AvailabilityZone='us-east-1b',
            CidrBlock=Ref('cidrSubnetB'),
            MapPublicIpOnLaunch=True,
            Tags=_tags(),
            VpcId=Ref('vpc'),
        ),
        ec2.SubnetRouteTableAssociation(
            'subnetBToRouteTable',
            RouteTableId=Ref('routeTable'),
            SubnetId=Ref('subnetB'),
        ),
    ]
Пример #2
0
    def create_subnets(self):
        self.default_azs = []
        self.default_private_subnets = []
        self.default_public_subnets = []

        for num, availability_zone in enumerate(self.availability_zones):
            public_subnet_name = '{}PublicSubnet'.format(
                availability_zone.cfn_name)
            public_subnet = self.create_resource(ec2.Subnet(
                public_subnet_name,
                VpcId=Ref(self.vpc),
                CidrBlock=cidr_generator.next(),
                AvailabilityZone=availability_zone.name,
                Tags=self.get_tags(Name=public_subnet_name)),
                                                 output=public_subnet_name)

            self.create_resource(
                ec2.SubnetRouteTableAssociation(
                    '{}PublicRouteTableAssociation'.format(
                        public_subnet.title),
                    SubnetId=Ref(public_subnet),
                    RouteTableId=Ref(self.public_route_table)))

            private_subnet_name = '{}PrivateSubnet'.format(
                availability_zone.cfn_name)
            private_subnet = self.create_resource(ec2.Subnet(
                private_subnet_name,
                VpcId=Ref(self.vpc),
                CidrBlock=cidr_generator.next(),
                AvailabilityZone=availability_zone.name,
                Tags=self.get_tags(Name=private_subnet_name)),
                                                  output=private_subnet_name)

            private_route_table_name = '{}PrivateRouteTable'.format(
                availability_zone.cfn_name)
            private_route_table = self.create_resource(
                ec2.RouteTable(
                    private_route_table_name,
                    VpcId=Ref(self.vpc),
                    Tags=self.get_tags(Name=private_route_table_name)))

            self.PRIVATE_ROUTE_TABLES.append(private_route_table)

            self.create_resource(
                ec2.SubnetRouteTableAssociation(
                    '{}PrivateSubnetRouteTableAssociation'.format(
                        private_subnet.title),
                    SubnetId=Ref(private_subnet),
                    RouteTableId=Ref(private_route_table)))

            self.PUBLIC_SUBNETS.append(public_subnet)
            self.PRIVATE_SUBNETS.append(private_subnet)

            if availability_zone.name in self.get_input('AvailabilityZones'):
                self.create_nat_gateway(availability_zone, public_subnet,
                                        private_route_table)
                self.default_azs.append(availability_zone.name)
                self.default_private_subnets.append(private_subnet)
                self.default_public_subnets.append(public_subnet)
Пример #3
0
    def create_subnets(self, public_route_table):
        self.default_azs = []
        self.default_private_subnets = []
        self.default_public_subnets = []

        for num, availability_zone in enumerate(self.availability_zones):
            public_subnet_name = '{}PublicSubnet'.format(
                availability_zone.cfn_name)  # NOQA

            public_subnet = self.create_resource(
                ec2.Subnet(public_subnet_name,
                           VpcId=Ref(self.vpc),
                           CidrBlock=next(self.public_subnet_cidr_ranges),
                           AvailabilityZone=availability_zone.name,
                           Tags=self.get_tags(Name=public_subnet_name)))

            self.create_resource(
                ec2.SubnetRouteTableAssociation(
                    '{}PublicRouteTableAssociation'.format(
                        public_subnet.title),
                    SubnetId=Ref(public_subnet),
                    RouteTableId=Ref(public_route_table)))

            private_subnet_name = '{}PrivateSubnet'.format(
                availability_zone.cfn_name)  # NOQA

            private_subnet = self.create_resource(
                ec2.Subnet(private_subnet_name,
                           VpcId=Ref(self.vpc),
                           CidrBlock=next(self.private_subnet_cidr_ranges),
                           AvailabilityZone=availability_zone.name,
                           Tags=self.get_tags(Name=private_subnet_name)))

            private_route_table_name = '{}PrivateRouteTable'.format(
                availability_zone.cfn_name)  # NOQA

            private_route_table = self.create_resource(
                ec2.RouteTable(
                    private_route_table_name,
                    VpcId=Ref(self.vpc),
                    Tags=self.get_tags(Name=private_route_table_name)))

            self.create_resource(
                ec2.SubnetRouteTableAssociation(
                    '{}PrivateSubnetRouteTableAssociation'.format(
                        private_subnet.title),  # NOQA
                    SubnetId=Ref(private_subnet),
                    RouteTableId=Ref(private_route_table)))

            if availability_zone.name in self.get_input(
                    'AvailabilityZones').split(','):  # NOQA
                self.create_nat(availability_zone, public_subnet,
                                private_route_table)
                self.default_azs.append(availability_zone.name)
                self.default_private_subnets.append(private_subnet)
                self.default_public_subnets.append(public_subnet)
Пример #4
0
    def resources(self, stack: Stack) -> list[AWSObject]:
        """Return resources associated with the construct."""
        igw = ec2.InternetGateway(name_to_id(f"{self.name_prefix}-igw"))
        attachement = ec2.VPCGatewayAttachment(
            name_to_id(f"{self.name_prefix}-igw-attachement"),
            InternetGatewayId=Ref(igw),
            VpcId=Ref(self.vpc),
        )
        route = ec2.Route(
            name_to_id(f"{self.name_prefix}-igw-route"),
            RouteTableId=Ref(self.route_table),
            DestinationCidrBlock="0.0.0.0/0",
            GatewayId=Ref(igw),
        )
        result = [igw, attachement, route]

        # If a new route table has to be created associate it with provided subnets
        if self.add_route_table_to_stack:
            result.append(self.route_table)
            assert self.subnets is not None
            result.extend([
                ec2.SubnetRouteTableAssociation(
                    name_to_id(f"{self.name_prefix}-{num}"),
                    RouteTableId=Ref(self.route_table),
                    SubnetId=Ref(subnet),
                )
                for subnet, num in zip(self.subnets, range(len(self.subnets)))
            ])

        return result
Пример #5
0
 def route_table_assoc(self) -> ec2.SubnetRouteTableAssociation:
     """Return association of route table to this subnet."""
     return ec2.SubnetRouteTableAssociation(
         name_to_id(f"{self.name}RouteTableAssoc"),
         RouteTableId=Ref(self.route_table),
         SubnetId=Ref(self.subnet),
     )
Пример #6
0
 def s3_route_table_assoc(self) -> ec2.SubnetRouteTableAssociation:
     """Return route table association."""
     return ec2.SubnetRouteTableAssociation(
         name_to_id(f"{self.name}S3RouteTableAssoc"),
         RouteTableId=Ref(self.s3_route_table),
         SubnetId=Ref(self.subnet),
     )
def createCouchbaseSubnetRouteTableAssociation(t, subnet, routetable):
    couchbaseSubnetRouteTableAssociation = t.add_resource(ec2.SubnetRouteTableAssociation(
        'SUBNETROUTETABLEASSOCATION',
        RouteTableId=Ref(routetable),
        SubnetId=Ref(subnet)
    ))
    return couchbaseSubnetRouteTableAssociation
Пример #8
0
 def route_subnet_association(self, t, subnetName, subnetId, routeTableId):
     association = t.add_resource(
         ec2.SubnetRouteTableAssociation(
             'AssociateRt' + subnetName,
             SubnetId=subnetId,
             RouteTableId=routeTableId,
         ))
Пример #9
0
 def resources(self, stack: Stack) -> list[AWSObject]:
     """Return resources associated with the construct."""
     igw = ec2.InternetGateway(name_to_id(f"{self.name_prefix}-igw"))
     attachement = ec2.VPCGatewayAttachment(
         name_to_id(f"{self.name_prefix}-igw-attachement"),
         InternetGatewayId=Ref(igw),
         VpcId=Ref(self.vpc),
     )
     route_table = ec2.RouteTable(
         name_to_id(f"{self.name_prefix}-igw-route-table"), VpcId=Ref(self.vpc)
     )
     route = ec2.Route(
         name_to_id(f"{self.name_prefix}-igw-route"),
         RouteTableId=Ref(route_table),
         DestinationCidrBlock="0.0.0.0/0",
         GatewayId=Ref(igw),
     )
     route_table_associations = (
         ec2.SubnetRouteTableAssociation(
             name_to_id(f"{self.name_prefix}-{num}"),
             RouteTableId=Ref(route_table),
             SubnetId=Ref(subnet),
         )
         for subnet, num in zip(self.subnets, range(len(self.subnets)))
     )
     return [igw, attachement, route_table, route, *route_table_associations]
Пример #10
0
    def create_route_table(self):
        t = self.template

        self.route_table = t.add_resource(
            ec2.RouteTable(
                "RouteTable",
                VpcId=self.vpc_id,
                Tags=self.tags,
            )
        )

        t.add_output(Output("RouteTableId", Value=self.route_table.Ref()))

        self.route_table_assoc = t.add_resource(
            ec2.SubnetRouteTableAssociation(
                "SubnetRouteTableAssociation",
                SubnetId=self.subnet.Ref(),
                RouteTableId=self.route_table.Ref(),
            )
        )

        t.add_output(
            Output(
                "SubnetRouteTableAssociationId",
                Value=self.route_table_assoc.Ref()
            )
        )
Пример #11
0
    def assign_subnet_route_table(self, subnet, route_table):
        name = "%s%s" % (subnet, route_table.name)
        a = ec2.SubnetRouteTableAssociation(
            name, DeletionPolicy=self.deletion_policy)
        a.SubnetId = Ref(subnet)
        a.RouteTableId = Ref(route_table)

        self._add_resource(a)
Пример #12
0
 def add_subnet_db2_rta(self):
     name, tags = self._name_tags('subnet_db2_rta')
     self.subnet_db1_rta = self.t.add_resource(
         ec2.SubnetRouteTableAssociation(
             name,
             SubnetId=Ref(self.subnet_db2),
             RouteTableId=Ref(self.igw_route_table),
             # Doesn't support: Tags=Tags(**tags),
         ))
Пример #13
0
def build_public_route_table_associations(public_subnets):
    public_route_table_associations = [
        ec2.SubnetRouteTableAssociation(name=public_subnet["Name"] +
                                        "PublicRouteTableAssociation",
                                        SubnetId=Ref(public_subnet["Name"]),
                                        RouteTableId=Ref("PublicRouteTable"))
        for public_subnet in public_subnets
        if public_subnet["Type"] is "Public"
    ]
    return public_route_table_associations
Пример #14
0
 def create_route_table_associations(self):
     # Accociate each az subnet to a route table
     t = self.template
     for name in self.subnets.keys():
         for i in range(len(self.zones)):
             if self.subnets[name]['net_type'] == 'public':
                 route_table_name = self.subnets[name]['route_table']
             else:
                 route_table_name = self.subnets[name]['route_table'][i]
             t.add_resource(
                 ec2.SubnetRouteTableAssociation(
                     '%sRouteTableAssociation%d' % (name, i),
                     SubnetId=Ref(self.subnets[name]['az_subnets'][i]),
                     RouteTableId=Ref(route_table_name)))
Пример #15
0
def create_routes(t, env, vpc_objects, subnet_config, subnet_mapping):
    '''
    Takes template t and vpc_objects to add routes and security_groups
    '''
    # Create Route Tables
    vpc_objects['route_tables'] = {}
    for tier in subnet_mapping['service_name_for_subnets'].keys():
        for az in range(1, subnet_mapping['number_of_azs'] + 1):
            rt_name = "{}{}{}RT".format(env.title(), tier.title(), az)
            vpc_objects['route_tables'][rt_name] = t.add_resource(
                ec2.RouteTable(rt_name,
                               VpcId=Ref(vpc_objects['vpc']),
                               Tags=Tags(Name=rt_name)))
            #add route for IGW in DMZ route table
            if tier == "dmz":
                t.add_resource(
                    ec2.Route(
                        '{}{}{}IGW'.format(env.title(), tier.title(), az),
                        #DependsOn=Ref(vpc_objects['igw_attachment']),
                        GatewayId=Ref('InternetGateway'),
                        DestinationCidrBlock='0.0.0.0/0',
                        RouteTableId=Ref(
                            vpc_objects['route_tables'][rt_name])))
            elif tier == "app" or tier == "internal":
                t.add_resource(
                    ec2.Route(
                        '{}{}{}NAT'.format(env.title(), tier.title(), az),
                        #DependsOn=Ref(vpc_objects['igw_attachment']),
                        NatGatewayId=Ref('{}{}NatGW'.format(env.title(), az)),
                        DestinationCidrBlock='0.0.0.0/0',
                        RouteTableId=Ref(
                            vpc_objects['route_tables'][rt_name])))

    for subid in subnet_config:
        tier = subnet_config[subid]['tier'].lower()
        az = subnet_config[subid]['az_number']
        route_table_name = '{}{}{}RT'.format(env.title(), tier.title(), az)
        #associate subnet with route table
        t.add_resource(
            ec2.SubnetRouteTableAssociation(
                '{}{}{}RTA'.format(route_table_name.title(), subid.title(),
                                   az),
                SubnetId=Ref(vpc_objects['subnets'][subid]),
                RouteTableId=Ref(
                    vpc_objects['route_tables'][route_table_name])))
    return t, vpc_objects
Пример #16
0
    def add_natted_subnet_group(self,
                                cidr_block: str,
                                name_prefix: str,
                                no_of_subnets: int = 4):
        """Create private subnets behind NAT gateways

        Creates a group of subnets, attaches the private network ACL and
        the corresponding private route table depending on AZ

        Args:
            cidr_block (str): Will be split across AZs
            name_prefix (str): Subnet name. AZ will be added at the end.
            no_of_subnets (int, optional): How many subnets to set up.
                Must be a power of 2. Defaults to 4.

        Raises:
            NotImplementedError: [description]
        """
        for res in multiaz_subnets(
                name_prefix=name_prefix,
                cidr_block=cidr_block,
                region=self.region,
                no_of_subnets=no_of_subnets,
                vpc=self.vpc,
                network_acl=self.internal_nacl,
        ):
            self._r[res.title] = res
            if res.resource["Type"] == "AWS::EC2::Subnet":
                subnet = res
                route_found = False
                for route_table in self.natted_route_tables:
                    if route_table.Metadata["az"] == subnet.Metadata["az"]:
                        self._r[
                            f"{subnet.title}RouteAssociation"] = t_ec2.SubnetRouteTableAssociation(
                                title=f"{subnet.title}RouteAssociation",
                                SubnetId=Ref(subnet),
                                RouteTableId=Ref(route_table),
                            )
                        route_found = True
                        break
                if not route_found:
                    raise NotImplementedError(
                        f"Can't find NAT gateway in {subnet.Metadata['az']}")
Пример #17
0
def configure_vpc(cfn_template, cluster_name):

    vpc = ec2.VPC("DustVPC")
    vpc.CidrBlock = "10.0.0.0/16"
    vpc.Tags = [ec2.Tag("Name:", cluster_name)]
    cfn_template.add_resource(vpc)
    vpc_id = Ref(vpc)

    subnet = ec2.Subnet('dustSubnet')
    subnet.VpcId = vpc_id
    subnet.CidrBlock = "10.0.0.0/24"
    cfn_template.add_resource(subnet)
    vpc_subnet = Ref(subnet)

    net_gateway = ec2.InternetGateway('dustGateway')
    cfn_template.add_resource(net_gateway)

    attach_net_gateway = ec2.VPCGatewayAttachment('dustAttachGateway')
    attach_net_gateway.VpcId = vpc_id
    attach_net_gateway.InternetGatewayId = Ref(net_gateway)
    cfn_template.add_resource(attach_net_gateway)

    route_table = ec2.RouteTable('dustRoutetable')
    route_table.VpcId = vpc_id
    cfn_template.add_resource(route_table)

    route = ec2.Route('dustRoute')
    route.RouteTableId = Ref(route_table)
    route.DestinationCidrBlock = "0.0.0.0/0"
    route.GatewayId = Ref(net_gateway)
    route.DependsOn = "dustAttachGateway"
    cfn_template.add_resource(route)

    attach_route = ec2.SubnetRouteTableAssociation('dustAttachRouteTable')
    attach_route.SubnetId = vpc_subnet
    attach_route.RouteTableId = Ref(route_table)
    cfn_template.add_resource(attach_route)

    return vpc_id, vpc_subnet
Пример #18
0
    def gen_public_subnet_az(self, az_index, cidr_block):
        name = f"PublicSubnet{az_index}"
        subnet = ec2.Subnet(
            name,
            VpcId=Ref(self.vpc),
            CidrBlock=cidr_block,
            AvailabilityZone=Select(str(az_index), GetAZs(Ref("AWS::Region"))),
        )
        self.template.add_resource(subnet)
        self.export_value(Ref(subnet), name)

        route_table_association = ec2.SubnetRouteTableAssociation(
            f"{name}RouteTableAssociation",
            SubnetId=Ref(subnet),
            RouteTableId=Ref(self.public_route_table),
        )
        self.template.add_resource(route_table_association)

        network_acl_association = ec2.SubnetNetworkAclAssociation(
            f"{name}NetworkAclAssociation",
            SubnetId=Ref(subnet),
            NetworkAclId=Ref(self.network_acl),
        )
        self.template.add_resource(network_acl_association)
Пример #19
0
private_route_table = t.add_resource(
    ec2.RouteTable(
        'PrivateRouteTable',
        VpcId=Ref(vpc),
    ))

public_route_table = t.add_resource(
    ec2.RouteTable(
        'PublicRouteTable',
        VpcId=Ref(vpc),
    ))

public_route_association = t.add_resource(
    ec2.SubnetRouteTableAssociation(
        'PublicRouteAssociation',
        SubnetId=Ref(public_net),
        RouteTableId=Ref(public_route_table),
    ))

default_public_route = t.add_resource(
    ec2.Route(
        'PublicDefaultRoute',
        RouteTableId=Ref(public_route_table),
        DestinationCidrBlock='0.0.0.0/0',
        GatewayId=Ref(igw),
    ))

private_route_association = t.add_resource(
    ec2.SubnetRouteTableAssociation(
        'PrivateRouteAssociation',
        SubnetId=Ref(private_net),
Пример #20
0
    def create_network(self):
        t = self.template
        variables = self.get_variables()
        self.create_gateway()
        t.add_resource(ec2.NetworkAcl('DefaultACL', VpcId=VPC_ID))

        self.create_nat_security_groups()
        subnets = {'public': [], 'private': []}
        net_types = subnets.keys()
        zones = []
        for i in range(variables["AZCount"]):
            az = Select(i, GetAZs(""))
            zones.append(az)
            name_suffix = i
            for net_type in net_types:
                name_prefix = net_type.capitalize()
                subnet_name = "%sSubnet%s" % (name_prefix, name_suffix)
                subnets[net_type].append(subnet_name)
                t.add_resource(
                    ec2.Subnet(subnet_name,
                               AvailabilityZone=az,
                               VpcId=VPC_ID,
                               DependsOn=GW_ATTACH,
                               CidrBlock=variables.get("%sSubnets" %
                                                       name_prefix)[i],
                               Tags=Tags(type=net_type)))

                route_table_name = "%sRouteTable%s" % (name_prefix,
                                                       name_suffix)
                t.add_resource(
                    ec2.RouteTable(route_table_name,
                                   VpcId=VPC_ID,
                                   Tags=[ec2.Tag('type', net_type)]))
                t.add_resource(
                    ec2.SubnetRouteTableAssociation(
                        "%sRouteTableAssociation%s" %
                        (name_prefix, name_suffix),
                        SubnetId=Ref(subnet_name),
                        RouteTableId=Ref(route_table_name)))

                route_name = '%sRoute%s' % (name_prefix, name_suffix)
                if net_type == 'public':
                    # the public subnets are where the NAT instances live,
                    # so their default route needs to go to the AWS
                    # Internet Gateway
                    t.add_resource(
                        ec2.Route(route_name,
                                  RouteTableId=Ref(route_table_name),
                                  DestinationCidrBlock="0.0.0.0/0",
                                  GatewayId=Ref(GATEWAY)))
                    self.create_nat_instance(i, subnet_name)
                else:
                    # Private subnets are where actual instances will live
                    # so their gateway needs to be through the nat instances
                    route = ec2.Route(
                        route_name,
                        RouteTableId=Ref(route_table_name),
                        DestinationCidrBlock='0.0.0.0/0',
                    )
                    if variables["UseNatGateway"]:
                        route.NatGatewayId = Ref(NAT_GATEWAY_NAME %
                                                 name_suffix)
                    else:
                        route.InstanceId = Ref(NAT_INSTANCE_NAME % name_suffix)
                    t.add_resource(route)

        for net_type in net_types:
            t.add_output(
                Output("%sSubnets" % net_type.capitalize(),
                       Value=Join(",", [Ref(sn) for sn in subnets[net_type]])))

            for i, sn in enumerate(subnets[net_type]):
                t.add_output(
                    Output("%sSubnet%d" % (net_type.capitalize(), i),
                           Value=Ref(sn)))

        self.template.add_output(
            Output("AvailabilityZones", Value=Join(",", zones)))

        for i, az in enumerate(zones):
            t.add_output(Output("AvailabilityZone%d" % (i), Value=az))
Пример #21
0
    def __init__(self):
        super(VPC, self).__init__()

        self.vpc = ec2.VPC(
            "VPC",
            CidrBlock="172.1.0.0/16",
            InstanceTenancy="default",
            EnableDnsSupport=True,
            EnableDnsHostnames=True,
            Tags=Tags(Name=Ref("AWS::StackName")),
        )

        self.internet_gateway = ec2.InternetGateway(
            "InternetGateway",
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-internet-gateway"]), ),
        )

        self.internet_gateway_attachment = ec2.VPCGatewayAttachment(
            "InternetGatewayAttachment",
            InternetGatewayId=Ref(self.internet_gateway),
            VpcId=Ref(self.vpc),
        )

        self.public_route_table = ec2.RouteTable(
            "PublicRouteTable",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join(
                "-", [Ref("AWS::StackName"), "public-route-table"]), ),
        )

        self.private_route_table = ec2.RouteTable(
            "PrivateRouteTable",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join(
                "-", [Ref("AWS::StackName"), "private-route-table"]), ),
        )

        self.vpc_s3_endpoint = ec2.VPCEndpoint(
            "VPCS3Endpoint",
            ServiceName=Join(
                "",
                ["com.amazonaws.", Ref("AWS::Region"), ".s3"]),
            VpcId=Ref(self.vpc),
            RouteTableIds=[
                Ref(self.public_route_table),
                Ref(self.private_route_table)
            ],
        )

        self.route_to_internet = ec2.Route(
            "RouteToInternet",
            DestinationCidrBlock="0.0.0.0/0",
            GatewayId=Ref(self.internet_gateway),
            RouteTableId=Ref(self.public_route_table),
            DependsOn=self.internet_gateway_attachment.title,
        )

        # private subnets

        self.private_subnet_1 = ec2.Subnet(
            "PrivateSubnet1",
            AvailabilityZone=Select(0, GetAZs()),
            CidrBlock="172.1.1.0/24",
            MapPublicIpOnLaunch=False,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-private-subnet-1"]), ),
            VpcId=Ref(self.vpc),
        )

        self.private_subnet_1_route_table_association = ec2.SubnetRouteTableAssociation(
            "PrivateSubnet1RouteTableAssociation",
            RouteTableId=Ref(self.private_route_table),
            SubnetId=Ref(self.private_subnet_1),
        )

        self.private_subnet_2 = ec2.Subnet(
            "PrivateSubnet2",
            AvailabilityZone=Select(1, GetAZs()),
            CidrBlock="172.1.2.0/24",
            MapPublicIpOnLaunch=False,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-private-subnet-2"]), ),
            VpcId=Ref(self.vpc),
        )

        self.private_subnet_2_route_table_association = ec2.SubnetRouteTableAssociation(
            "PrivateSubnet2RouteTableAssociation",
            RouteTableId=Ref(self.private_route_table),
            SubnetId=Ref(self.private_subnet_2),
        )

        self.private_network_aCL = ec2.NetworkAcl(
            "PrivateNetworkACL",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join("",
                                [Ref("AWS::StackName"), "-private-nacl"]), ),
        )

        self.private_subnet_1_network_acl_association = ec2.SubnetNetworkAclAssociation(
            "PrivateSubnet1NetworkAclAssociation",
            SubnetId=Ref(self.private_subnet_1),
            NetworkAclId=Ref(self.private_network_aCL),
        )

        self.private_subnet_2_network_acl_association = ec2.SubnetNetworkAclAssociation(
            "PrivateSubnet2NetworkAclAssociation",
            SubnetId=Ref(self.private_subnet_2),
            NetworkAclId=Ref(self.private_network_aCL),
        )

        self.private_network_acl_entry_in = ec2.NetworkAclEntry(
            "PrivateNetworkAclEntryIn",
            CidrBlock="172.1.0.0/16",
            Egress=False,
            NetworkAclId=Ref(self.private_network_aCL),
            Protocol=-1,
            RuleAction="allow",
            RuleNumber=200,
        )

        self.private_network_acl_entry_out = ec2.NetworkAclEntry(
            "PrivateNetworkAclEntryOut",
            CidrBlock="172.1.0.0/16",
            Egress=True,
            NetworkAclId=Ref(self.private_network_aCL),
            Protocol=-1,
            RuleAction="allow",
            RuleNumber=200,
        )

        # public subnets
        self.public_subnet_1 = ec2.Subnet(
            "PublicSubnet1",
            AvailabilityZone=Select(0, GetAZs()),
            CidrBlock="172.1.128.0/24",
            MapPublicIpOnLaunch=True,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-public-subnet-1"]), ),
            VpcId=Ref(self.vpc),
        )

        self.public_subnet_1_route_table_association = ec2.SubnetRouteTableAssociation(
            "PublicSubnet1RouteTableAssociation",
            RouteTableId=Ref(self.public_route_table),
            SubnetId=Ref(self.public_subnet_1),
        )

        self.public_subnet_2 = ec2.Subnet(
            "PublicSubnet2",
            AvailabilityZone=Select(1, GetAZs()),
            CidrBlock="172.1.129.0/24",
            MapPublicIpOnLaunch=True,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-public-subnet-2"]), ),
            VpcId=Ref(self.vpc),
        )

        self.public_subnet_2_route_table_association = ec2.SubnetRouteTableAssociation(
            "PublicSubnet2RouteTableAssociation",
            RouteTableId=Ref(self.public_route_table),
            SubnetId=Ref(self.public_subnet_2),
        )
Пример #22
0
def create_vpc_template(template=None):
    if not template:
        template = Template()
        template.add_description(
            'AWS cloud formation script template.at creates a VPC with a NAT Gg'
        )
        template.add_version('2010-09-09')

    vpc_cidr_block = template.add_parameter(
        Parameter(
            'VPCCIDR',
            Default=vpc_config['cidr_block'],
            Description='The IP address space for this VPC, in CIDR notation',
            Type='String',
        ))

    vpc = template.add_resource(
        ec2.VPC('VPC',
                CidrBlock=Ref(vpc_cidr_block),
                Tags=Tags(vpc_config['tags'])))

    igw = template.add_resource(ec2.InternetGateway('InternetGateway', ))

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

    template.add_output(Output('VPCId', Value=Ref(vpc), Description='VPC Id'))

    public_security_group = template.add_resource(
        ec2.SecurityGroup(
            security_group_config['public']['name'],
            GroupDescription='{} public security group'.format(
                vpc_config['name']),
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      ToPort=r['port'],
                                      FromPort=r['port'],
                                      CidrIp=r['cidr_block'])
                for r in security_group_config['public']['ingress_rules']
            ],
            VpcId=Ref(vpc),
            Tags=Tags(
                dict(Name='public {} security group'.format(
                    vpc_config['name']))),
        ))

    template.add_output(
        Output('PublicSecurityGroupId',
               Value=Ref(public_security_group),
               Description='Public Security Group Id'))

    private_security_group = template.add_resource(
        ec2.SecurityGroup(
            security_group_config['private']['name'],
            GroupDescription='{} private security group'.format(
                vpc_config['name']),
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    ToPort=r['port'],
                    FromPort=r['port'],
                    SourceSecurityGroupId=Ref(public_security_group))
                for r in security_group_config['private']['ingress_rules']
            ],
            VpcId=Ref(vpc),
            Tags=Tags(
                dict(Name='private {} security group'.format(
                    vpc_config['name']))),
        ))

    for i, sub_net in enumerate(sub_nets):
        public_subnet = template.add_parameter(
            Parameter(
                'PublicSubnetCidr{}'.format(i),
                Type='String',
                Description='Public Subnet CIDR',
                Default=sub_net['public_cidr'],
            ))

        public_net = template.add_resource(
            ec2.Subnet(
                'PublicSubnet{}'.format(i),
                AvailabilityZone=sub_net['region'],
                CidrBlock=Ref(public_subnet),
                MapPublicIpOnLaunch=False,
                VpcId=Ref(vpc),
                Tags=Tags(dict(Name='Public Subnet {}'.format(i))),
            ))

        public_route_table = template.add_resource(
            ec2.RouteTable(
                'PublicRouteTable{}'.format(i),
                VpcId=Ref(vpc),
            ))

        template.add_resource(
            ec2.SubnetRouteTableAssociation(
                'PublicRouteAssociation{}'.format(i),
                SubnetId=Ref(public_net),
                RouteTableId=Ref(public_route_table),
            ))

        template.add_resource(
            ec2.Route(
                'PublicDefaultRoute{}'.format(i),
                RouteTableId=Ref(public_route_table),
                DestinationCidrBlock='0.0.0.0/0',
                GatewayId=Ref(igw),
            ))

        template.add_output(
            Output('PublicSubnet{}'.format(i),
                   Value=Ref(public_subnet),
                   Description='Subnet Id'))

        if private_sub_net:
            private_subnet = template.add_parameter(
                Parameter(
                    'PrivateSubnetCidr{}'.format(i),
                    Type='String',
                    Description='Private Subnet CIDR',
                    Default=sub_net['private_cidr'],
                ))

            private_net = template.add_resource(
                ec2.Subnet(
                    'PrivateSubnet{}'.format(i),
                    CidrBlock=Ref(private_subnet),
                    MapPublicIpOnLaunch=False,
                    VpcId=Ref(vpc),
                    Tags=Tags(dict(Name='Private Subnet {}'.format(i))),
                ))

            private_route_table = template.add_resource(
                ec2.RouteTable(
                    'PrivateRouteTable{}'.format(i),
                    VpcId=Ref(vpc),
                ))

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PrivateRouteAssociation{}'.format(i),
                    SubnetId=Ref(private_net),
                    RouteTableId=Ref(private_route_table),
                ))

            template.add_output(
                Output('PrivateSubnet{}'.format(i),
                       Value=Ref(private_subnet),
                       Description='Subnet Id'))

        if nat_gateway and private_sub_net:
            nat_eip = template.add_resource(
                ec2.EIP(
                    'NatEip{}'.format(i),
                    Domain="vpc",
                ))

            nat = template.add_resource(
                ec2.NatGateway(
                    'Nat{}'.format(i),
                    AllocationId=GetAtt(nat_eip, 'AllocationId'),
                    SubnetId=Ref(public_net),
                ))

            template.add_resource(
                ec2.Route(
                    'NatRoute{}'.format(i),
                    RouteTableId=Ref(private_route_table),
                    DestinationCidrBlock='0.0.0.0/0',
                    NatGatewayId=Ref(nat),
                ))

            template.add_output(
                Output(
                    'NatEip{}'.format(i),
                    Value=Ref(nat_eip),
                    Description='Nat Elastic IP',
                ))

    write_json_to_file('vpc.json', template)
Пример #23
0
    def add_resources(self):
        """ Add All Cloudformation Resources. This will include vpc, igw, and any other network
        resources """
        self.vpc = self.template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock=Ref(self.VpcCidr),
                EnableDnsSupport=True,
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-VPC"),
            ))

        self.PubSubnet1 = self.template.add_resource(
            ec2.Subnet(
                "PubSubnet1",
                CidrBlock=Ref(self.PubSub1Cidr),
                VpcId=Ref(self.vpc),
                AvailabilityZone="us-east-1a",
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PubSubnet1"),
            ))

        self.PubSubnet2 = self.template.add_resource(
            ec2.Subnet(
                "PubSubnet2",
                VpcId=Ref(self.vpc),
                CidrBlock=Ref(self.PubSub2Cidr),
                AvailabilityZone="us-east-1b",
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PubSubnet2"),
            ))

        self.PrivSubnet1 = self.template.add_resource(
            ec2.Subnet(
                "PrivSubnet1",
                VpcId=Ref(self.vpc),
                CidrBlock=Ref(self.PrivSub1Cidr),
                AvailabilityZone="us-east-1a",
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PrivSubnet1"),
            ))

        self.PrivSubnet2 = self.template.add_resource(
            ec2.Subnet(
                "PrivSubnet2",
                CidrBlock=Ref(self.PrivSub2Cidr),
                VpcId=Ref(self.vpc),
                AvailabilityZone="us-east-1b",
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PrivSubnet2"),
            ))

        self.IGW = self.template.add_resource(
            ec2.InternetGateway(
                "IGW",
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-IGW"),
            ))

        self.IGWAttachment = self.template.add_resource(
            ec2.VPCGatewayAttachment(
                "IGWAttachment",
                VpcId=Ref(self.vpc),
                InternetGatewayId=Ref(self.IGW),
            ))

        self.EIP1 = self.template.add_resource(ec2.EIP(
            "EIP1",
            Domain="vpc",
        ))

        self.EIP2 = self.template.add_resource(ec2.EIP(
            "EIP2",
            Domain="vpc",
        ))

        self.NAT1 = self.template.add_resource(
            ec2.NatGateway(
                "NAT",
                AllocationId=GetAtt(self.EIP1, "AllocationId"),
                SubnetId=Ref(self.PubSubnet1),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-NAT1"),
            ))

        self.NAT2 = self.template.add_resource(
            ec2.NatGateway(
                "NAT2",
                AllocationId=GetAtt(self.EIP2, "AllocationId"),
                SubnetId=Ref(self.PubSubnet2),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-NAT2"),
            ))

        self.PrivRT1 = self.template.add_resource(
            ec2.RouteTable(
                "PrivRT1",
                VpcId=Ref(self.vpc),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PRIVRT1"),
            ))

        self.PrivRT2 = self.template.add_resource(
            ec2.RouteTable(
                "PrivRT2",
                VpcId=Ref(self.vpc),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PRIVRT2"),
            ))

        self.NatRoute = self.template.add_resource(
            ec2.Route(
                "NatRoute",
                RouteTableId=Ref(self.PrivRT1),
                DestinationCidrBlock="0.0.0.0/0",
                NatGatewayId=Ref(self.NAT1),
            ))

        self.Nat2Route = self.template.add_resource(
            ec2.Route(
                "NatRoute2",
                RouteTableId=Ref(self.PrivRT2),
                DestinationCidrBlock="0.0.0.0/0",
                NatGatewayId=Ref(self.NAT2),
            ))

        self.PrivRT1Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PrivRT1Association",
                SubnetId=Ref(self.PrivSubnet1),
                RouteTableId=Ref(self.PrivRT1),
            ))

        self.PrivRT2Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PrivRT2Association",
                SubnetId=Ref(self.PrivSubnet2),
                RouteTableId=Ref(self.PrivRT2),
            ))

        self.PubRT1 = self.template.add_resource(
            ec2.RouteTable(
                "PubRT1",
                VpcId=Ref(self.vpc),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PUBRT1"),
            ))

        self.PubRT2 = self.template.add_resource(
            ec2.RouteTable(
                "PubRT2",
                VpcId=Ref(self.vpc),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-PUBRT2"),
            ))

        self.PubRT1IGWattachment = self.template.add_resource(
            ec2.Route(
                "PubRT1IGWAttachment",
                DependsOn=["IGWAttachment"],
                RouteTableId=Ref(self.PubRT1),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=Ref(self.IGW),
            ))

        self.PubRT2IGWattachment = self.template.add_resource(
            ec2.Route(
                "PubRT2IGWAttachment",
                DependsOn=["IGWAttachment"],
                RouteTableId=Ref(self.PubRT2),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=Ref(self.IGW),
            ))

        self.PubRT1Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubRT1Associate",
                SubnetId=Ref(self.PubSubnet1),
                RouteTableId=Ref(self.PubRT1),
            ))

        self.PubRT2Asocation = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubR2Associate",
                SubnetId=Ref(self.PubSubnet2),
                RouteTableId=Ref(self.PubRT2),
            ))
Пример #24
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)
Пример #25
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)))

    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)
Пример #26
0
    def add_resource(self):
        t = self.template

        self.PublicRouteTable = t.add_resource(ec2.RouteTable(
            "PublicRouteTable",
            VpcId=Ref("VPC"),
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Network="Public",
                Environment=Ref(self.Environment),
                Name=Join("-", ["RT-PU-1", Ref(self.Project)]),
            ),
        ))

        self.GatewayToInternet = t.add_resource(ec2.VPCGatewayAttachment(
            "GatewayToInternet",
            VpcId=Ref("VPC"),
            InternetGatewayId=Ref("InternetGateway"),
        ))

        self.PubSubnet1 = t.add_resource(ec2.Subnet(
            "PubSubnet1",
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Public",
                Name=Join("-", ["NT-PU-1", Ref(self.Project)]),
            ),
            VpcId=Ref("VPC"),
            CidrBlock=Ref(self.PublicSubnet1),
            AvailabilityZone=Ref(self.AvailabilityZone1),
            MapPublicIpOnLaunch=True,
        ))

        self.PubSubnet2 = t.add_resource(ec2.Subnet(
            "PubSubnet2",
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Public",
                Name=Join("-", ["NT-PU-2", Ref(self.Project)]),
            ),
            VpcId=Ref("VPC"),
            CidrBlock=Ref(self.PublicSubnet2),
            AvailabilityZone=Ref(self.AvailabilityZone2),
            MapPublicIpOnLaunch=True,
        ))

        self.PriSubnet2 = t.add_resource(ec2.Subnet(
            "PriSubnet2",
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Private",
                Name=Join("-", ["NT-PR-2", Ref(self.Project)]),
            ),
            VpcId=Ref("VPC"),
            CidrBlock=Ref(self.PrivateSubnet2),
            AvailabilityZone=Ref(self.AvailabilityZone2),
        ))

        self.PriSubnet1 = t.add_resource(ec2.Subnet(
            "PriSubnet1",
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Private",
                Name=Join("-", ["NT-PR-1", Ref(self.Project)]),
            ),
            VpcId=Ref("VPC"),
            CidrBlock=Ref(self.PrivateSubnet1),
            AvailabilityZone=Ref(self.AvailabilityZone1),
        ))

        self.PrivateRouteTable2 = t.add_resource(ec2.RouteTable(
            "PrivateRouteTable2",
            VpcId=Ref("VPC"),
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Private",
                Name=Join("-", ["RT-PR-2", Ref(self.Project)]),
            ),
        ))

        self.PublicRoute = t.add_resource(ec2.Route(
            "PublicRoute",
            GatewayId=Ref("InternetGateway"),
            DestinationCidrBlock="0.0.0.0/0",
            RouteTableId=Ref(self.PublicRouteTable),
        ))

        self.PrivateRouteTable1 = t.add_resource(ec2.RouteTable(
            "PrivateRouteTable1",
            VpcId=Ref("VPC"),
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Private",
                Name=Join("-", ["RT-PR-1", Ref(self.Project)]),
            ),
        ))

        self.PriSubnet2RTAssoc = t.add_resource(ec2.SubnetRouteTableAssociation(
            "PriSubnet2RTAssoc",
            SubnetId=Ref(self.PriSubnet2),
            RouteTableId=Ref(self.PrivateRouteTable2),
        ))

        self.InternetGateway = t.add_resource(ec2.InternetGateway(
            "InternetGateway",
            Tags=Tags(
                Application=Ref("AWS::StackName"),
                Environment=Ref(self.Environment),
                Network="Public",
                Name=Join("-", ["IGW", Ref(self.Project)]),
            ),
        ))

        self.VPC = t.add_resource(ec2.VPC(
            "VPC",
            CidrBlock=Ref(self.VpcCidr),
            EnableDnsSupport=True,
            EnableDnsHostnames=True,
            Tags=Tags(
                Name=Join("-", ["VPC", Ref(self.Project)]),
                Environment=Ref(self.Environment),
                Application=Ref("AWS::StackName"),
            ),
        ))

        self.PubSubnet2RTAssoc = t.add_resource(ec2.SubnetRouteTableAssociation(
            "PubSubnet2RTAssoc",
            SubnetId=Ref(self.PubSubnet2),
            RouteTableId=Ref(self.PublicRouteTable),
        ))

        self.PubSubnet1RTAssoc = t.add_resource(ec2.SubnetRouteTableAssociation(
            "PubSubnet1RTAssoc",
            SubnetId=Ref(self.PubSubnet1),
            RouteTableId=Ref(self.PublicRouteTable),
        ))

        self.PriSubnet1RTAssoc = t.add_resource(ec2.SubnetRouteTableAssociation(
            "PriSubnet1RTAssoc",
            SubnetId=Ref(self.PriSubnet1),
            RouteTableId=Ref(self.PrivateRouteTable1),
        ))
        ),
    ],
    VpcId=Ref(VPC),
))

PublicRoute = t.add_resource(ec2.Route(
    "PublicRoute",
    GatewayId=Ref(InternetGateway),
    DestinationCidrBlock="0.0.0.0/0",
    RouteTableId=Ref(PublicRouteTable),
    DependsOn="AttachGateway",
))

PublicSubnetRouteTableAssociation = t.add_resource(ec2.SubnetRouteTableAssociation(
    "PublicSubnetRouteTableAssociation",
    SubnetId=Ref(PublicSubnet),
    RouteTableId=Ref(PublicRouteTable),
))

AmbariSecurityGroup = t.add_resource(ec2.SecurityGroup(
    "AmbariSecurityGroup",
    SecurityGroupIngress=[
        ec2.SecurityGroupRule(
            ToPort="-1", IpProtocol="icmp", CidrIp=FindInMap("SubnetConfig", "Public", "CIDR"), FromPort="-1"
        ),
        ec2.SecurityGroupRule(
            ToPort="65535", IpProtocol="tcp", CidrIp=FindInMap("SubnetConfig", "Public", "CIDR"), FromPort="0"
        ),
        ec2.SecurityGroupRule(
            ToPort="65535", IpProtocol="tcp", CidrIp=Ref(OpenLocation), FromPort="0"
        ),
Пример #28
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)
        Path="/",
        AssumeRolePolicyDocument={
            "Statement": [{
                "Action": ["sts:AssumeRole"],
                "Effect": "Allow",
                "Principal": {
                    "Service": ["ec2.amazonaws.com"]
                }
            }]
        },
    ))

PublicSubnetRouteTableAssociation = t.add_resource(
    ec2.SubnetRouteTableAssociation(
        "PublicSubnetRouteTableAssociation",
        SubnetId=Ref(PublicSubnet),
        RouteTableId=Ref(PublicRouteTable),
    ))

S3RolePolicies = t.add_resource(
    iam.PolicyType(
        "S3RolePolicies",
        PolicyName="s3access",
        PolicyDocument={
            "Statement": [{
                "Action": "s3:*",
                "Resource": "*",
                "Effect": "Allow"
            }]
        },
        Roles=[Ref(AmbariAccessRole),
Пример #30
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        # Add StackName to outputs (for ease of reference by child stacks)
        template.add_output(
            Output('StackName',
                   Description='Name of this CloudFormation stack',
                   Value=Ref('AWS::StackName')))

        vpc = template.add_resource(
            ec2.VPC('VPC',
                    CidrBlock=variables['VpcCidr'].ref,
                    EnableDnsSupport=True,
                    EnableDnsHostnames=True,
                    InstanceTenancy=variables['VpcInstanceTenancy'].ref,
                    Tags=Tags(Application=Ref('AWS::StackName'),
                              Name=Join('-', [
                                  variables['CustomerName'].ref, 'vpc',
                                  variables['EnvironmentName'].ref
                              ]),
                              Network='Public')))
        template.add_output(
            Output('VPC',
                   Description='VPC',
                   Export=Export(Sub('${AWS::StackName}-VPC')),
                   Value=Ref(vpc)))
        template.add_output(
            Output('CidrBlock',
                   Description='Set of IP addresses for the VPC',
                   Export=Export(Sub('${AWS::StackName}-CidrBlock')),
                   Value=GetAtt(vpc, 'CidrBlock')))

        # Create subnets
        for i in range(AZS):
            for zone in ['Public', 'Private']:
                template.add_resource(
                    ec2.Subnet(
                        '%sSubnet%s' % (zone[:3], str(i + 1)),
                        Condition='%sAZ%i' % (zone, (i + 1)),
                        VpcId=Ref(vpc),
                        AvailabilityZone=Select(str(i + variables['AzOffset']),
                                                GetAZs('')),
                        CidrBlock=Ref('%sSubnet%s' % (zone, str(i + 1))),
                        Tags=Tags(
                            Application=Ref('AWS::StackName'),
                            Name=Join('-', [
                                variables['CustomerName'].ref,
                                zone.lower(), variables['EnvironmentName'].ref,
                                Select(str(i + variables['AzOffset']),
                                       GetAZs(''))
                            ]),
                            Network='%s - %s' % (zone, str(i + 1)))))
                template.add_output(
                    Output('%sSubnet%s' % (zone[:3], str(i + 1)),
                           Condition='%sAZ%s' % (zone, str(i + 1)),
                           Description='%sSubnet%s' % (zone[:3], str(i + 1)),
                           Export=Export(
                               Sub('${AWS::StackName}-'
                                   '%sSubnet%s' % (zone[:3], str(i + 1)))),
                           Value=Ref('%sSubnet%s' % (zone[:3], str(i + 1)))))
                template.add_output(
                    Output(
                        '%sSubnet%sAZ' % (zone[:3], str(i + 1)),
                        Condition='%sAZ%s' % (zone, str(i + 1)),
                        Description='%sSubnet%s Availability Zone' %
                        (zone[:3], str(i + 1)),  # noqa
                        Export=Export(
                            Sub('${AWS::StackName}-'
                                '%sSubnet%sAZ' % (zone[:3], str(i + 1)))),
                        Value=GetAtt('%sSubnet%s' % (zone[:3], str(i + 1)),
                                     'AvailabilityZone')))

        internetgateway = template.add_resource(
            ec2.InternetGateway('InternetGateway',
                                Tags=Tags(
                                    Application=Ref('AWS::StackName'),
                                    Name=Join('-', [
                                        variables['CustomerName'].ref, 'igw',
                                        variables['EnvironmentName'].ref
                                    ]),
                                    Network='Public')))
        template.add_resource(
            ec2.VPCGatewayAttachment(
                'GatewayToInternet',
                InternetGatewayId=Ref(internetgateway),
                VpcId=Ref(vpc),
            ))

        # Elastic IPs
        for i in range(AZS):
            template.add_resource(
                ec2.EIP('NAT%iElasticIP' % (i + 1),
                        Condition='CreateNATGateway%i' % (i + 1),
                        Domain='vpc'))
            template.add_output(
                Output(
                    'NAT%iElasticIP' % (i + 1),
                    Condition='CreateNATGateway%i' % (i + 1),
                    Description='Elastic IP for NATs %i' % (i + 1),
                    Export=Export(
                        Sub('${AWS::StackName}-NAT%iElasticIP' % (i + 1))),
                    Value=Ref('NAT%iElasticIP' % (i + 1)),
                ))

        # NAT Gateways
        for i in range(AZS):
            template.add_resource(
                ec2.NatGateway('NATGateway%i' % (i + 1),
                               Condition='CreateNATGateway%i' % (i + 1),
                               AllocationId=GetAtt('NAT%iElasticIP' % (i + 1),
                                                   'AllocationId'),
                               SubnetId=Ref('PubSubnet%i' % (i + 1))))

        # Route tables
        publicroutetable = template.add_resource(
            ec2.RouteTable(
                'PublicRouteTable',
                VpcId=Ref(vpc),
                Tags=Tags(Application=Ref('AWS::StackName'),
                          Name=Join('-', [
                              variables['CustomerName'].ref, 'public-routes',
                              variables['EnvironmentName'].ref
                          ]),
                          Network='Public')))
        template.add_output(
            Output(publicroutetable.title,
                   Description=publicroutetable.title,
                   Export=Export(
                       Sub('${AWS::StackName}-%s' % publicroutetable.title)),
                   Value=Ref(publicroutetable)))
        for i in range(AZS):
            template.add_resource(
                ec2.RouteTable(
                    'PrivateRouteTable%i' % (i + 1),
                    Condition='PrivateAZ%i' % (i + 1),
                    VpcId=Ref(vpc),
                    Tags=Tags(
                        Application=Ref('AWS::StackName'),
                        Name=Join('-', [
                            variables['CustomerName'].ref, 'private-routes',
                            variables['EnvironmentName'].ref,
                            Select(str(i + variables['AzOffset']), GetAZs(''))
                        ]),
                        Network='Private - %i' % (i + 1))))
            template.add_output(
                Output('PrivateRouteTable%i' % (i + 1),
                       Condition='PrivateAZ%i' % (i + 1),
                       Description='PrivateRouteTable%i' % (i + 1),
                       Export=Export(
                           Sub('${AWS::StackName}-'
                               'PrivateRouteTable%i' % (i + 1))),
                       Value=Ref('PrivateRouteTable%i' % (i + 1))))

        # Routes & Route Table Associations
        template.add_resource(
            ec2.Route('PublicRoute',
                      DestinationCidrBlock='0.0.0.0/0',
                      GatewayId=Ref(internetgateway),
                      RouteTableId=Ref(publicroutetable)))

        for i in range(AZS):
            template.add_resource(
                ec2.Route('PrivateRoute%i' % (i + 1),
                          Condition='CreateNATGateway%i' % (i + 1),
                          DestinationCidrBlock='0.0.0.0/0',
                          NatGatewayId=Ref('NATGateway%i' % (i + 1)),
                          RouteTableId=Ref('PrivateRouteTable%i' % (i + 1))))

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PubSubnet%iRTAssoc' % (i + 1),
                    Condition='PublicAZ%i' % (i + 1),
                    RouteTableId=Ref(publicroutetable),
                    SubnetId=Ref('PubSubnet%i' % (i + 1))))
            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PriSubnet%iRTAssoc' % (i + 1),
                    Condition='PrivateAZ%i' % (i + 1),
                    RouteTableId=Ref('PrivateRouteTable%i' % (i + 1)),
                    SubnetId=Ref('PriSubnet%i' % (i + 1))))