Esempio n. 1
0
def create_vpc_template():
    template = Template()

    vpc_cidr = template.add_parameter(parameter=Parameter(
        title='VpcCidr', Type='String', Default='192.168.0.0/16'))

    subnet_cidr_a = template.add_parameter(parameter=Parameter(
        title='SubnetCidr1', Type='String', Default='192.168.1.0/24'))

    subnet_cidr_b = template.add_parameter(parameter=Parameter(
        title='SubnetCidr2', Type='String', Default='192.168.2.0/24'))

    vpc = template.add_resource(resource=VPC(
        title='SampleVpc', CidrBlock=Ref(vpc_cidr), EnableDnsHostnames=True))

    igw = template.add_resource(resource=InternetGateway(title='SampleIgw'))

    template.add_resource(resource=VPCGatewayAttachment(
        title='SampleAttachment', VpcId=Ref(vpc), InternetGatewayId=Ref(igw)))

    subnet_a = template.add_resource(
        resource=Subnet(title='SampleSubnetA',
                        AvailabilityZone='us-east-1a',
                        CidrBlock=Ref(subnet_cidr_a),
                        MapPublicIpOnLaunch=True,
                        VpcId=Ref(vpc)))

    subnet_b = template.add_resource(
        resource=Subnet(title='SampleSubnetB',
                        AvailabilityZone='us-east-1b',
                        CidrBlock=Ref(subnet_cidr_b),
                        MapPublicIpOnLaunch=True,
                        VpcId=Ref(vpc)))

    route_table = template.add_resource(
        resource=RouteTable(title='SampleRoteTable', VpcId=Ref(vpc)))

    template.add_resource(resource=SubnetRouteTableAssociation(
        title='SampleRoteTableAssociationA',
        RouteTableId=Ref(route_table),
        SubnetId=Ref(subnet_a)))

    template.add_resource(resource=SubnetRouteTableAssociation(
        title='SampleRoteTableAssociationB',
        RouteTableId=Ref(route_table),
        SubnetId=Ref(subnet_b)))

    template.add_resource(resource=Route(title='SampleRoute',
                                         DestinationCidrBlock='0.0.0.0/0',
                                         GatewayId=Ref(igw),
                                         RouteTableId=Ref(route_table)))

    with open('./vpc.yml', mode='w') as file:
        file.write(template.to_yaml())
Esempio n. 2
0
 def add_private_route_association(self):
     self.private_route_association = self.template.add_resource(
         SubnetRouteTableAssociation(
             'PrivateRouteAssociation',
             SubnetId=Ref(self.private_net),
             RouteTableId=Ref(self.private_route_table),
         ))
    def buildTemplate(self):
        self.buildParams()
        
        for c in self.conditions:
            self.t.add_condition(c, self.conditions[c])

        mysubnet=self.t.add_resource(ec2Subnet(
            "Subnet",
            CidrBlock=Ref(self.paramCIDRBLock),
            MapPublicIpOnLaunch=Ref(self.paramMapPublicIP),
            VpcId=Ref(self.paramVPCID),
        ))

        self.t.add_resource(SubnetRouteTableAssociation(
            "SubnetAssociation",
            RouteTableId=Ref(self.paramRouteTable),
            SubnetId=Ref(mysubnet),
            ))
        
        self.t.add_output([
            Output(
                "SubnetId",
                Description="SubnetId of the created Subnet",
                Value=Ref(mysubnet)
                )
            ])
Esempio n. 4
0
def __create_dmz_subnet(template: Template, vpc, public_subnet):
    dmz_subnet_cidr = template.add_parameter(parameter=Parameter(
        title='DmzSubnetCidr', Type='String', Default='192.168.3.0/24'))

    dmz_subnet = template.add_resource(
        resource=Subnet(title='SampleDmzSubnet',
                        CidrBlock=Ref(dmz_subnet_cidr),
                        VpcId=Ref(vpc)))

    dmz_route_table = template.add_resource(
        resource=RouteTable(title='SampleDmzRoteTable', VpcId=Ref(vpc)))

    template.add_resource(resource=SubnetRouteTableAssociation(
        title='SampleDmzRoteTableAssociation',
        RouteTableId=Ref(dmz_route_table),
        SubnetId=Ref(dmz_subnet)))

    eip = template.add_resource(resource=EIP(title='SampleEip', ))

    ngw = template.add_resource(
        resource=NatGateway(title='SampleNatGateway',
                            AllocationId=GetAtt(eip, "AllocationId"),
                            SubnetId=Ref(public_subnet)))

    template.add_resource(resource=Route(title='SampleDmzRoute',
                                         DestinationCidrBlock='0.0.0.0/0',
                                         NatGatewayId=Ref(ngw),
                                         RouteTableId=Ref(dmz_route_table)))
Esempio n. 5
0
def __create_public_subnet(template: Template, vpc) -> Subnet:
    public_subnet_cidr = template.add_parameter(parameter=Parameter(
        title='PublicSubnetCidr', Type='String', Default='192.168.1.0/24'))

    igw = template.add_resource(resource=InternetGateway(title='SampleIgw'))

    template.add_resource(resource=VPCGatewayAttachment(
        title='SampleAttachment', VpcId=Ref(vpc), InternetGatewayId=Ref(igw)))

    public_subnet = template.add_resource(
        resource=Subnet(title='SamplePublicSubnet',
                        CidrBlock=Ref(public_subnet_cidr),
                        MapPublicIpOnLaunch=True,
                        VpcId=Ref(vpc)))

    public_route_table = template.add_resource(
        resource=RouteTable(title='SamplePublicRoteTable', VpcId=Ref(vpc)))

    template.add_resource(resource=SubnetRouteTableAssociation(
        title='SamplePublicRoteTableAssociation',
        RouteTableId=Ref(public_route_table),
        SubnetId=Ref(public_subnet)))

    template.add_resource(resource=Route(title='SamplePublicRoute',
                                         DestinationCidrBlock='0.0.0.0/0',
                                         GatewayId=Ref(igw),
                                         RouteTableId=Ref(public_route_table)))

    return public_subnet
Esempio n. 6
0
def addSubnetRouteTableAssociation(template, subnet, routeTable):
    return template.add_resource(
        SubnetRouteTableAssociation(
            subnet.title + routeTable.title,
            SubnetId=Ref(subnet),
            RouteTableId=Ref(routeTable),
        ))
Esempio n. 7
0
    def add_subnet(self, name, availability_zone, cidr_block,
                   routing_table_name, vpc_name):
        """
        Create a subnet

        :param name: Name fo the subnet
        :param availability_zone: AZ to deploy into
        :param cidr_block: CIDR block
        :param routing_table_name: Name of routing table
        :param vpc_name: Name of VPC
        """
        if isinstance(vpc_name, Ref):
            vpc = vpc_name
        else:
            vpc = Ref(vpc_name)

        self.template.add_resource(
            Subnet(
                name,
                AvailabilityZone=availability_zone,
                CidrBlock=cidr_block,
                VpcId=vpc,
            ))

        self.template.add_resource(
            SubnetRouteTableAssociation(
                "SubnetRouteTableAssociation{}".format(name),
                SubnetId=Ref(name),
                RouteTableId=Ref(routing_table_name),
            ))
Esempio n. 8
0
 def add_SubnetRouteTableAssociation(self):
     # print self.sceptre_user_data
     self.SubnetRouteTableAssociation = self.template.add_resource(
         SubnetRouteTableAssociation("PubSubnetAssoc",
                                     SubnetId=Ref(self.Subnet),
                                     RouteTableId=Ref(
                                         self.PublicRouteTable)))
Esempio n. 9
0
    def _add_subnet_to_az(self, az, cidr, suffix):
        subnet = self.add_resource(Subnet(
            "%sSubnet%s" % (self.name, suffix),
            VpcId=self.vpc_id,
            AvailabilityZone=az,
            CidrBlock=cidr,
            Tags=Tags(
                Name=Join("", [Ref("AWS::StackName"), "-public"]),
            )
        ))

        route_tbl = self.add_resource(RouteTable(
            "%sRouteTable%s" % (self.name, suffix),
            VpcId=self.vpc_id,
            Tags=Tags(Name=Join("", [Ref("AWS::StackName"), "-public"]))
        ))

        route = self.add_resource(Route(
            "%sRoute%s" % (self.name, suffix),
            GatewayId=self.igw,
            DestinationCidrBlock="0.0.0.0/0",
            RouteTableId=Ref(route_tbl),
        ))

        subnet_route_tbl_assoc = self.add_resource(SubnetRouteTableAssociation(
            "%sSubnetRouteAssoc%s" % (self.name, suffix),
            SubnetId=Ref(subnet),
            RouteTableId=Ref(route_tbl),
        ))

        return subnet
Esempio n. 10
0
 def route_table_subnet_association(self, t, tier, subnet_id,
                                    route_table_id):
     association = t.add_resource(
         SubnetRouteTableAssociation(tier + 'RouteTableAssociation',
                                     SubnetId=subnet_id,
                                     RouteTableId=route_table_id))
     return 0
Esempio n. 11
0
 def create_subnet_route_association(self, subnet_name, route_table_name):
     association_name = subnet_name + "RouteAssociation"
     t = self.template
     t.add_resource(
         SubnetRouteTableAssociation(association_name,
                                     SubnetId=Ref(subnet_name),
                                     RouteTableId=Ref(route_table_name)))
Esempio n. 12
0
    def create_private_subnet(self, zone, ip_network):
        """Create private subnet and associated resources"""
        if not 'Public' in self.network['Subnets'][zone]:
            raise Exception(("Public subnet in {} does not exist to "
                             "create private subnet!").format(zone))
        elif not 'NatGateway' in self.network['Subnets'][zone]['Public']:
            raise Exception(
                ("No NAT Gateway in public subnet {} to associate "
                 "default route with in private subnet!").format(zone))
        zone_title = self.data['Title'] + TITLE_CLEANUP_RE.subn('', zone)[0]
        tag = Tag(Key='Name',
                  Value='{} {} Private'.format(self.data['Name'], zone))
        subnet = Subnet(title=zone_title + 'Private',
                        template=self.data['Template'],
                        AvailabilityZone=zone,
                        CidrBlock=ip_network,
                        MapPublicIpOnLaunch=False,
                        Tags=[tag] + self.data['Tags'],
                        VpcId=Ref(self.network['VPC']))
        tag = Tag(Key='Name',
                  Value='{} {} Private Route Table'.format(
                      self.data['Name'], zone))
        routetable = RouteTable(title=zone_title + 'PrivateRouteTable',
                                template=self.data['Template'],
                                VpcId=Ref(self.network['VPC']),
                                Tags=[tag] + self.data['Tags'])
        nat_gateway_id = Ref(
            self.network['Subnets'][zone]['Public']['NatGateway'])
        route = Route(title=zone_title + 'PrivateDefaultRoute',
                      template=self.data['Template'],
                      DestinationCidrBlock='0.0.0.0/0',
                      NatGatewayId=nat_gateway_id,
                      RouteTableId=Ref(routetable))
        subnetroutetableassociation = SubnetRouteTableAssociation(
            title=zone_title + 'PrivateSubnetRouteTableAssociation',
            template=self.data['Template'],
            RouteTableId=Ref(routetable),
            SubnetId=Ref(subnet))
        self.network['Subnets'][zone]['Private'] = {}
        self.network['Subnets'][zone]['Private']['Subnet'] = subnet
        self.network['Subnets'][zone]['Private']['RouteTable'] = routetable
        self.network['Subnets'][zone]['Private']['DefaultRoute'] = route
        self.network['Subnets'][zone]['Private'][
            'SubnetRouteTableAssociation'] = subnetroutetableassociation

        # Export Private Subnet ID
        self.add_output(
            title=self.data['Title'] + zone_title + 'PrivateSubnet',
            description="Private Subnet ID of {} in {}".format(
                self.data['Name'], zone),
            value=Ref(subnet),
            export=Sub('${{AWS::StackName}}{}PrivateSubnet'.format(zone)))
        # Export Private Route Table ID
        self.add_output(
            title=self.data['Title'] + zone_title + 'PrivateRouteTable',
            description="Private Route Table ID of {} in {}".format(
                self.data['Name'], zone),
            value=Ref(routetable),
            export=Sub('${{AWS::StackName}}{}PrivateRouteTable'.format(zone)))
Esempio n. 13
0
def add_route_table_association( template, key, route_table, subnet ):
    return template.add_resource(
            SubnetRouteTableAssociation(
                key,
                RouteTableId = Ref( route_table ),
                SubnetId = Ref( subnet )
                )
            )
Esempio n. 14
0
def attach_route_table(template, vpc, subnet, gateway):
    routetable = RouteTable("sgdemoroutetable", VpcId = Ref(vpc))
    template.add_resource(routetable)
    route = Route("sgdemoroute1", RouteTableId = Ref(routetable), DestinationCidrBlock = "0.0.0.0/0", GatewayId = Ref(gateway))
    template.add_resource(route)
    routetableassoc = SubnetRouteTableAssociation("sgdemosubnetroute1", RouteTableId = Ref(routetable), SubnetId = Ref(subnet))
    template.add_resource(routetableassoc)
    return routetable
Esempio n. 15
0
    def create_subnet_route_table_association(sn_rt_title,
                                              routetableid=None,
                                              subnetid=None):

        _subnet_routetable_association = SubnetRouteTableAssociation(
            title=sn_rt_title, RouteTableId=routetableid, SubnetId=subnetid)

        return _subnet_routetable_association
Esempio n. 16
0
def associate_routes(stack, subnet_list=()):
    """Add Route Association Resources."""

    for association in subnet_list:
        stack.stack.add_resource(
            SubnetRouteTableAssociation(
                '{0}RouteAssociation'.format(association['name']),
                SubnetId=Ref(association['subnet']),
                RouteTableId=Ref(association['route_table'])))
    def _create_public_network(self, subnet_configs):
        public_route_table = RouteTable(
            camelcase("{self.env}Public".format(**locals())),
            VpcId=Ref(self.vpc),
            Tags=[
                {
                    'Key': 'Name',
                    'Value': "{self.env}-public".format(**locals())
                },
                {'Key': 'environment', 'Value': self.env}
            ],
            DependsOn=self.vpc.title)
        self.template.add_resource(public_route_table)
        subnet_count = 0

        existing_subnet_ids, existing_subnet_azs, az_balance = self._get_existing_subnet_info("PublicSubnet")
        for subnet_title, subnet_config in subnet_configs.items():
            subnet_count += 1
            if f"PublicSubnet{subnet_count}" in existing_subnet_ids:
                availability_zone = existing_subnet_azs[existing_subnet_ids[f"PublicSubnet{subnet_count}"]]
            else:
                availability_zone = min(az_balance, key=az_balance.get)

            subnet_title = camelcase("{self.env}Public".format(**locals())) + \
                pascalcase(re.sub('[^a-zA-Z0-9*]', '', subnet_title))
            subnet_name = "{self.env}-public-{subnet_count}".format(**locals())
            subnet = Subnet(
                subnet_title,
                AvailabilityZone=availability_zone,
                CidrBlock=subnet_config['cidr'],
                VpcId=Ref(self.vpc),
                MapPublicIpOnLaunch=True,
                Tags=[
                    {'Key': 'Name', 'Value': subnet_name},
                    {'Key': 'environment', 'Value': self.env}
                ]
            )
            self.public_subnets.append(subnet)
            self.template.add_resource(subnet)
            subnet_route_table_association = SubnetRouteTableAssociation(
                camelcase("{self.env}PublicSubnet{subnet_count}Assoc".format(**locals())),
                RouteTableId=Ref(public_route_table),
                SubnetId=Ref(subnet)
            )
            self.template.add_resource(subnet_route_table_association)

        internet_gateway_route = Route(
            camelcase("{self.env}IgRoute".format(**locals())),
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=Ref(self.internet_gateway),
            RouteTableId=Ref(public_route_table)
        )
        self.template.add_resource(internet_gateway_route)
        return None
Esempio n. 18
0
 def add_public_subnet_routetable_association1(self):
     '''
     Add a public subnet route-table association
     to public subnet 1
     '''
     self.cfn_template.add_resource(
         SubnetRouteTableAssociation(
             title=constants.PUB_RT_ASS1,
             SubnetId=Ref(constants.PUB_SUBNET1),
             RouteTableId=Ref(constants.PUB_RT),
         ))
     return self.cfn_template
Esempio n. 19
0
 def add_private_subnet_routetable_association2(self):
     '''
     Add a private subnet route-table association
     to private subnet 2
     '''
     self.cfn_template.add_resource(
         SubnetRouteTableAssociation(
             title=constants.PRIV_RT_ASS2,
             SubnetId=Ref(constants.PRIV_SUBNET2),
             RouteTableId=Ref(constants.PRIV_RT),
         ))
     return self.cfn_template
Esempio n. 20
0
def add_storage_subnets(template, vpc, az_index, layers):
    """
    Function to add storage subnets inside the VPC

    :param layers: VPC layers
    :type layers: dict
    :param template: VPC Template()
    :type template: troposphere.Template
    :param vpc: Vpc() for Ref()
    :type vpc: troposphere.ec2.Vpc
    :param az_index: List of AZ Index (a,b,c..)
    :type az_index: list

    :returns: tuple() list of rtb, list of subnets
    """
    rtb = RouteTable(
        "StorageRtb",
        template=template,
        VpcId=Ref(vpc),
        Tags=Tags(Name="StorageRtb") + Tags({f"vpc{DELIM}usage": "storage"}),
        Metadata=metadata,
    )

    subnets = []
    for index, subnet_cidr in zip(az_index, layers["stor"]):
        subnet = Subnet(
            f"StorageSubnet{index.upper()}",
            template=template,
            CidrBlock=subnet_cidr,
            VpcId=Ref(vpc),
            AvailabilityZone=Sub(f"${{AWS::Region}}{index}"),
            Tags=Tags(
                Name=If(
                    USE_STACK_NAME_CON_T,
                    Sub(f"${{AWS::StackName}}-Storage-{index}"),
                    Sub(f"${{{ROOT_STACK_NAME_T}}}-Storage-{index}"),
                ),
            )
            + Tags({f"vpc{DELIM}usage": "storage", f"vpc{DELIM}vpc-id": Ref(vpc)}),
            Metadata=metadata,
        )
        SubnetRouteTableAssociation(
            f"StorageSubnetAssoc{index.upper()}",
            template=template,
            SubnetId=Ref(subnet),
            RouteTableId=Ref(rtb),
            Metadata=metadata,
        )
        subnets.append(subnet)
    return [rtb], subnets
def add_public_subnet_assoc(availability_zones, prefix):
    subnet = {}
    for availability_zone in availability_zones:
        subnet[availability_zone] = {}
        subnet[availability_zone]["public"] = {}

        items = {}
        for subnet_name in get_subnet_names("public"):
            items[subnet_name] = t.add_resource(
                SubnetRouteTableAssociation(
                    prefix + availability_zone.replace("-", "") + subnet_name.upper(),
                    RouteTableId=Ref(public_routing_tables[availability_zone]["public"][subnet_name]),
                    SubnetId=Ref(public_subnets[availability_zone]["public"][subnet_name]),
                ))
        subnet[availability_zone]["public"] = items
    return subnet
Esempio n. 22
0
def __create_private_subnet(template: Template, vpc):
    private_subnet_cidr = template.add_parameter(parameter=Parameter(
        title='PrivateSubnetCidr', Type='String', Default='192.168.2.0/24'))

    private_subnet = template.add_resource(
        resource=Subnet(title='SamplePrivateSubnet',
                        CidrBlock=Ref(private_subnet_cidr),
                        VpcId=Ref(vpc)))

    private_route_table = template.add_resource(
        resource=RouteTable(title='SamplePrivateRoteTable', VpcId=Ref(vpc)))

    template.add_resource(resource=SubnetRouteTableAssociation(
        title='SamplePrivateRoteTableAssociation',
        RouteTableId=Ref(private_route_table),
        SubnetId=Ref(private_subnet)))
Esempio n. 23
0
File: stack.py Progetto: jpza/ekscli
    def _create_vpc(self):
        if self.vpc:
            self.tpl.add_output(Output(self.OUTPUT_VPC, Value=self.vpc))
            self.tpl.add_output(Output(self.OUTPUT_SUBNETS, Value=','.join(self.subnets)))
            return

        vpc = VPC(self.RESOURCE_EKS_VPC.name, CidrBlock=self.vpc_cidr, Tags=Tags(Name=self.tag_name))
        self.tpl.add_resource(vpc)
        gateway = self.tpl.add_resource(InternetGateway(self.RESOURCE_VPC_INTERNET_GATEWAY.name))
        self.tpl.add_resource(VPCGatewayAttachment(
            self.RESOURCE_VPC_GATEWAY_ATTACHMENT.name, VpcId=Ref(vpc), InternetGatewayId=Ref(gateway),
            DependsOn=gateway,
        ))
        rt = self.tpl.add_resource(RouteTable(
            self.RESOURCE_VPC_ROUTE_TABLE.name, VpcId=Ref(vpc), DependsOn=gateway,
            Tags=Tags(Name='public subnet', Network='public'),
        ))
        self.tpl.add_resource(Route(
            self.RESOURCE_VPC_ROUTE.name, RouteTableId=Ref(rt), DestinationCidrBlock='0.0.0.0/0',
            GatewayId=Ref(gateway),
        ))
        self.resources.extend(deepcopy([self.RESOURCE_EKS_VPC, self.RESOURCE_VPC_INTERNET_GATEWAY,
                                        self.RESOURCE_VPC_GATEWAY_ATTACHMENT, self.RESOURCE_VPC_ROUTE_TABLE,
                                        self.RESOURCE_VPC_ROUTE]))

        subnets = []
        vpc_network = IPNetwork(self.vpc_cidr)
        prefixlen = IPNetwork(self.vpc_cidr).prefixlen + (len(self.zones) - 1).bit_length()
        cidrs = list(vpc_network.subnet(prefixlen))
        for i, zone in enumerate(self.zones):
            sname = self.RESOURCE_FORMAT_SUBNET.format(i + 1)
            staname = self.RESOURCE_FORMAT_SUBNET_RTA.format(i + 1)
            subnet = self.tpl.add_resource(Subnet(
                sname, AvailabilityZone=zone, VpcId=Ref(vpc), CidrBlock=str(cidrs[i].cidr),
                Tags=Tags(Name='{}-{}'.format(self.name, str(i + 1)))
            ))
            self.resources.append(Resource(sname, 'EKS VPC {}'.format(sname), Status.not_exist))
            self.tpl.add_resource(SubnetRouteTableAssociation(
                staname, SubnetId=Ref(subnet), RouteTableId=Ref(rt)
            ))
            self.resources.append(Resource(staname, 'EKS VPC {}'.format(staname), Status.not_exist))
            subnets.append(subnet)

        self.subnet_refs = [Ref(s) for s in subnets]
        self.tpl.add_output(Output(self.OUTPUT_VPC, Value=Ref(vpc)))
        self.tpl.add_output(Output(self.OUTPUT_SUBNETS, Value=Join(',', self.subnet_refs)))
Esempio n. 24
0
 def __build_route_table(
     self, subnet_config: SubnetConfig, subnet_ref: Subnet, vpc: VPC, internet_gateway, nat_gateway: NatGateway
 ):
     internet_gateway = If(self.__create_ig, internet_gateway, self.__gateway_id)
     route_table = self.__template.add_resource(
         RouteTable(
             "RouteTable" + subnet_config.name,
             VpcId=Ref(vpc),
             Tags=Tags(Name=TAGS_PREFIX + "RouteTable" + subnet_config.name, Stack=Ref("AWS::StackId")),
         )
     )
     self.__template.add_resource(
         SubnetRouteTableAssociation(
             "RouteAssociation" + subnet_config.name, SubnetId=Ref(subnet_ref), RouteTableId=Ref(route_table)
         )
     )
     if subnet_config.default_gateway == Gateways.INTERNET_GATEWAY:
         self.__template.add_resource(
             Route(
                 "DefaultRouteDependsOn" + subnet_config.name,
                 RouteTableId=Ref(route_table),
                 DestinationCidrBlock="0.0.0.0/0",
                 GatewayId=internet_gateway,
                 DependsOn="VPCGatewayAttachment",
                 Condition=self.__create_ig,
             )
         )
         self.__template.add_resource(
             Route(
                 "DefaultRouteNoDependsOn" + subnet_config.name,
                 RouteTableId=Ref(route_table),
                 DestinationCidrBlock="0.0.0.0/0",
                 GatewayId=internet_gateway,
                 Condition=self.__existing_ig,  # cant use Not()
             )
         )
     elif subnet_config.default_gateway == Gateways.NAT_GATEWAY:
         self.__template.add_resource(
             Route(
                 "NatRoute" + subnet_config.name,
                 RouteTableId=Ref(route_table),
                 DestinationCidrBlock="0.0.0.0/0",
                 NatGatewayId=Ref(nat_gateway),
             )
         )
Esempio n. 25
0
    def subnet_adder(self, subnet_list, name_ref, route_table_name):

        for index, cidr in enumerate(subnet_list):
            self.template.add_resource(
                Subnet(
                    name_ref + str(index),
                    CidrBlock=str(cidr),
                    VpcId=Ref(self.vpc),
                    # not a fan of the below line, but will do for now. This basically exists to ensure that subnets are
                    # distributed between availability zones. However, since we are always creating 3 pub/priv subnets
                    # this will fail if there are less than 3 AZs in a given region. Ideally the subnet count &
                    # distribution would happen dynamically based on how many zones are available.
                    AvailabilityZone=Select(index, self.azs)))
            self.template.add_resource(
                SubnetRouteTableAssociation(
                    route_table_name + str(index),
                    SubnetId=Ref(name_ref + str(index)),
                    RouteTableId=Ref(route_table_name)))
Esempio n. 26
0
 def __init__(self, title, template, *args, **kwargs):
     super().__init__(title, template, *args, **kwargs)
     RouteTable(title + 'routetable',
                template,
                VpcId=self.properties['VpcId'],
                Tags=kwargs['Tags'])
     Route(title + 'route',
           template,
           DestinationCidrBlock='0.0.0.0/0',
           NatGatewayId=Ref(
               'public' +
               self.properties['AvailabilityZone'].replace('-', '') +
               'natgateway'),
           RouteTableId=Ref(self.name + 'routetable'))
     SubnetRouteTableAssociation(title + 'subnetroutetableassociation',
                                 template,
                                 RouteTableId=Ref(self.name + 'routetable'),
                                 SubnetId=Ref(self))
Esempio n. 27
0
 def __build_route_table(
     self,
     subnet_config: SubnetConfig,
     subnet_ref: Subnet,
     vpc: VPC,
     internet_gateway: InternetGateway,
     internet_gateway_attachment: VPCGatewayAttachment,
     nat_gateway: NatGateway,
 ):
     route_table = self.__template.add_resource(
         RouteTable(
             "RouteTable" + subnet_config.name,
             VpcId=Ref(vpc),
             Tags=Tags(Name=Sub("${AWS::StackName}_route_table_" +
                                subnet_config.name),
                       Stack=Ref("AWS::StackId")),
         ))
     self.__template.add_resource(
         SubnetRouteTableAssociation("RouteAssociation" +
                                     subnet_config.name,
                                     SubnetId=Ref(subnet_ref),
                                     RouteTableId=Ref(route_table)))
     if subnet_config.default_gateway == Gateways.INTERNET_GATEWAY:
         self.__template.add_resource(
             Route(
                 "DefaultRoute" + subnet_config.name,
                 RouteTableId=Ref(route_table),
                 DestinationCidrBlock="0.0.0.0/0",
                 GatewayId=Ref(internet_gateway),
                 DependsOn=internet_gateway_attachment,
             ))
     elif subnet_config.default_gateway == Gateways.NAT_GATEWAY:
         self.__template.add_resource(
             Route(
                 "NatRoute" + subnet_config.name,
                 RouteTableId=Ref(route_table),
                 DestinationCidrBlock="0.0.0.0/0",
                 NatGatewayId=Ref(nat_gateway),
             ))
Esempio n. 28
0
def __create_private_subnet(template: Template, vpc):

    private_route_table = template.add_resource(
        resource=RouteTable(title='SamplePrivateRoteTable', VpcId=Ref(vpc)))

    for suffix in ['A', 'B']:
        private_subnet_cidr = template.add_parameter(
            parameter=Parameter(title='PrivateSubnetCidr' + suffix,
                                Type='String',
                                Default=__get_subnet_cidr()))

        private_subnet = template.add_resource(
            resource=Subnet(title='SamplePrivateSubnet' + suffix,
                            AvailabilityZone=Sub('${AWS::Region}' +
                                                 suffix.lower()),
                            CidrBlock=Ref(private_subnet_cidr),
                            VpcId=Ref(vpc)))
        add_export(template, private_subnet.title + 'Id', Ref(private_subnet))

        template.add_resource(resource=SubnetRouteTableAssociation(
            title='SamplePrivateRoteTableAssociation' + suffix,
            RouteTableId=Ref(private_route_table),
            SubnetId=Ref(private_subnet)))
Esempio n. 29
0
    def _add_route_tables(self):
        self.routeTable = RouteTable(
            'RouteTable',
            VpcId=Ref(self.parameters['VpcId']),
            Tags=Tags(Name=Join(
                '-', [Ref(self.parameters['StackPrefix']), "public"])),
        )
        self.template.add_resource(self.routeTable)

        self.public_route = Route(
            'Route',
            GatewayId=Ref(self.parameters['IgwId']),
            DestinationCidrBlock='0.0.0.0/0',
            RouteTableId=Ref(self.routeTable),
        )
        self.template.add_resource(self.public_route)

        self.subnetRouteTableAssociation1 = SubnetRouteTableAssociation(
            'PubSubnetRouteTableAssociation1',
            SubnetId=Ref(self.public_subnets['PubSubnet1']),
            RouteTableId=Ref(self.routeTable),
        )
        self.template.add_resource(self.subnetRouteTableAssociation1)
Esempio n. 30
0
 def __init__(self, title, template, *args, **kwargs):
     super().__init__(title, template, *args, **kwargs)
     EIP(title + 'eip',
         template,
         Domain='vpc',
         DependsOn='vpcgatewayattachment')
     NatGateway(title + 'natgateway',
                template,
                AllocationId=GetAtt(title + 'eip', 'AllocationId'),
                SubnetId=Ref(self),
                DependsOn=title + 'eip')
     RouteTable(title + 'routetable',
                template,
                VpcId=self.properties['VpcId'],
                Tags=kwargs['Tags'])
     Route(title + 'route',
           template,
           DestinationCidrBlock='0.0.0.0/0',
           GatewayId=Ref('internetgateway'),
           RouteTableId=Ref(title + 'routetable'))
     SubnetRouteTableAssociation(title + 'subnetroutetableassociation',
                                 template,
                                 RouteTableId=Ref(title + 'routetable'),
                                 SubnetId=Ref(self))
Esempio n. 31
0
t.add_resource(route_igw)

# subnets
app_subnets = []
route_table_associations = []
for subnet in config['vpc']['app_subnets']:
    sub = Subnet('PublicSubnet' + subnet[0])
    sub.VpcId = Ref(vpc)
    sub.CidrBlock = subnet[1]
    sub.AvailabilityZone = subnet[2]
    sub.Tags = Tags(Application = Ref('AWS::StackName'))
    t.add_resource(sub)
    app_subnets.append(sub)

    # route table associations need to be handled per subnet
    rta = SubnetRouteTableAssociation(config['name'] + 'Rta' + subnet[0])
    rta.RouteTableId = Ref(route_table)
    rta.SubnetId = Ref(sub)
    t.add_resource(rta)
    route_table_associations.append(rta)

# security group addresses
# list of tuples
# [('cidr block', 'cloudformation resource name')]
home_egress_ips = [
    ('68.193.66.133/32', 'home')
        ]

# security groups
home_ssh = SecurityGroup(config['name'] + 'homeSsh')
home_ssh.GroupDescription = 'home SSH in'