def create_peering(self):

        template = Template()
        template.add_version('2010-09-09')

        source_vpc_name_formatted = ''.join(
            e for e in self.source_vpc_name if e.isalnum()).capitalize()

        target_vpc_name_formatted = ''.join(
            e for e in self.target_vpc_name if e.isalnum()).capitalize()

        vpc_peering_connection = template.add_resource(
            VPCPeeringConnection(
                '{}{}{}VpcPeering'.format(self.stage,source_vpc_name_formatted,target_vpc_name_formatted),
                VpcId=ImportValue("{}{}VpcId".format(self.stage,source_vpc_name_formatted)),
                PeerVpcId=ImportValue("{}{}VpcId".format(self.stage,target_vpc_name_formatted)),
                Tags=Tags(
                    Name="{}_{}_{}_peering".format(self.stage,source_vpc_name_formatted,target_vpc_name_formatted)
                )
            )
        )

        template.add_resource(
            Route(
                '{}{}PublicRoutePeeringRule'.format(self.stage,source_vpc_name_formatted),                
                VpcPeeringConnectionId=Ref(vpc_peering_connection),
                DestinationCidrBlock=self.target_cidr_block,
                RouteTableId=ImportValue("{}{}PublicRouteTableId".format(self.stage,source_vpc_name_formatted))
            )
        )

        template.add_resource(
            Route(
                '{}{}PrivateRoutePeeringRule'.format(self.stage,source_vpc_name_formatted),
                VpcPeeringConnectionId=Ref(vpc_peering_connection),
                DestinationCidrBlock=self.target_cidr_block,
                RouteTableId=ImportValue("{}{}PrivateRouteTableId".format(self.stage,source_vpc_name_formatted))
            )
        )

        template.add_resource(
            Route(
                '{}{}PublicRoutePeeringRule'.format(self.stage,target_vpc_name_formatted),
                VpcPeeringConnectionId=Ref(vpc_peering_connection),
                DestinationCidrBlock=self.source_cidr_block,
                RouteTableId=ImportValue("{}{}PublicRouteTableId".format(self.stage,target_vpc_name_formatted))
            )
        )

        template.add_resource(
            Route(
                '{}{}PrivateRoutePeeringRule'.format(self.stage,target_vpc_name_formatted),
                VpcPeeringConnectionId=Ref(vpc_peering_connection),
                DestinationCidrBlock=self.source_cidr_block,
                RouteTableId=ImportValue("{}{}PrivateRouteTableId".format(self.stage,target_vpc_name_formatted))
            )
        )

        f = open("modules/template_peer_vpcs.yaml", 'w')
        print(template.to_yaml(), file=f)
Example #2
0
def populate_routes(stack, routes):
    """Add VPC Routes Resources."""
    tables = {
        'private': stack.private_route_table,
        'public': stack.public_route_table
    }
    gateways = {'igw': stack.internet_gateway, 'nat': stack.nat_gateway}

    for route in routes:
        if route['route'] == 'igw':
            stack.stack.add_resource(
                Route('{0}'.format(route['route']),
                      GatewayId=Ref(gateways[route['route']]),
                      DestinationCidrBlock='{0}'.format(route['cidrblock']),
                      RouteTableId=Ref(tables[route['routetable']])))
        elif route['route'] == 'nat':
            stack.stack.add_resource(
                Route('{0}'.format(route['route']),
                      NatGatewayId=Ref(gateways[route['route']]),
                      DestinationCidrBlock='{0}'.format(route['cidrblock']),
                      RouteTableId=Ref(tables[route['routetable']])))
        elif 'vpc_peer' in route.keys():
            create_peer_route(
                stack, '{0}{1}'.format(route['route'], route['routetable']),
                route['vpc_peer'], '{0}'.format(route['cidrblock']),
                Ref(tables[route['routetable']]))
Example #3
0
 def __init__(self, title, template, *args, **kwargs):
     self.props['PeerCidrBlock'] = (str, True)
     super().__init__(title, template, *args, **kwargs)
     for index in list(template.resources):
         resource = template.resources[index]
         if isinstance(resource, RouteTable):
             Route(index + 'to' + title + 'route',
                   template,
                   DestinationCidrBlock=kwargs['PeerCidrBlock'],
                   RouteTableId=Ref(resource),
                   VpcPeeringConnectionId=Ref(self))
     SecurityGroup(title + "securitygroup",
                   template,
                   GroupDescription="Allow SSH & ICMP from " + title,
                   VpcId=kwargs['VpcId'])
     SecurityGroupIngress(title + "sshingress",
                          template,
                          GroupId=Ref(title + "securitygroup"),
                          CidrIp=kwargs['PeerCidrBlock'],
                          IpProtocol="tcp",
                          FromPort="22",
                          ToPort="22")
     SecurityGroupIngress(title + "icmpingress",
                          template,
                          GroupId=Ref(title + "securitygroup"),
                          CidrIp=kwargs['PeerCidrBlock'],
                          IpProtocol="icmp",
                          FromPort="-1",
                          ToPort="-1")
     self.props.pop('PeerCidrBlock')
     self.properties.pop('PeerCidrBlock')
Example #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)))
Example #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
Example #6
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
Example #7
0
 def add_default_public_route(self):
     self.default_public_route = self.template.add_resource(Route(
         'PublicDefaultRoute',
         RouteTableId=Ref(self.public_route_table),
         DestinationCidrBlock='0.0.0.0/0',
         GatewayId=Ref(self.internet_gateway),
     ))
Example #8
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)))
Example #9
0
    def create_route(_title, igw=None, dest_cidr=None, route_table_id=None):

        _route = Route(title=_title,
                       DestinationCidrBlock=dest_cidr,
                       GatewayId=igw,
                       RouteTableId=route_table_id)

        return _route
Example #10
0
 def add_nat_gateway_route(self):
     self.nat_gateway_route = self.template.add_resource(
         Route(
             'NatRoute',
             RouteTableId=Ref(self.private_route_table),
             DestinationCidrBlock='0.0.0.0/0',
             NatGatewayId=Ref(self.nat),
         ))
Example #11
0
 def add_pub_route(self):
     self.PublicRoute = self.template.add_resource(
         Route(
             "PublicRoute",
             GatewayId=self.igw_id,
             DestinationCidrBlock="0.0.0.0/0",
             RouteTableId=Ref(self.PublicRouteTable),
         ))
Example #12
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
Example #13
0
def addRouteToRouteTableNAT(template, routeTable, Gateway,
                            DestinationCidrBlock, name):
    #name = "PrivateRouteToNatGateway"
    return template.add_resource(
        Route(name,
              DestinationCidrBlock=DestinationCidrBlock,
              NatGatewayId=Ref(Gateway),
              RouteTableId=Ref(routeTable)))
Example #14
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),
             )
         )
Example #15
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())
    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
Example #17
0
 def test_no_validation_method(self):
     route = Route(
         "Route66",
         DestinationCidrBlock="0.0.0.0/0",
         RouteTableId=Ref("RouteTable66"),
         InstanceId=If("UseNat", Ref("AWS::NoValue"), Ref("UseNat")),
         NatGatewayId=If("UseNat", Ref("UseNat"), Ref("AWS::NoValue")),
     ).no_validation()
     t = Template()
     t.add_resource(route)
     t.to_json()
Example #18
0
 def test_no_validation_method(self):
     route = Route('Route66',
                   DestinationCidrBlock='0.0.0.0/0',
                   RouteTableId=Ref('RouteTable66'),
                   InstanceId=If('UseNat', Ref('AWS::NoValue'),
                                 Ref('UseNat')),
                   NatGatewayId=If('UseNat', Ref('UseNat'),
                                   Ref('AWS::NoValue'))).no_validation()
     t = Template()
     t.add_resource(route)
     t.to_json()
Example #19
0
 def test_validation(self):
     route = Route(
         "Route66",
         DestinationCidrBlock="0.0.0.0/0",
         RouteTableId=Ref("RouteTable66"),
         InstanceId=If("UseNat", Ref("AWS::NoValue"), Ref("UseNat")),
         NatGatewayId=If("UseNat", Ref("UseNat"), Ref("AWS::NoValue")),
     )
     t = Template()
     t.add_resource(route)
     with self.assertRaises(ValueError):
         t.to_json()
Example #20
0
 def add_private_route(self):
     '''
     Add a private route with nat gateway
     '''
     self.cfn_template.add_resource(
         Route(
             title=constants.PRIV_ROUTE,
             RouteTableId=Ref(constants.PRIV_RT),
             DestinationCidrBlock='0.0.0.0/0',
             NatGatewayId=Ref(constants.NAT),
         ))
     return self.cfn_template
Example #21
0
 def add_public_route(self):
     '''
     Add a public route with internet gateway
     '''
     self.cfn_template.add_resource(
         Route(
             title=constants.PUB_ROUTE,
             RouteTableId=Ref(constants.PUB_RT),
             DestinationCidrBlock='0.0.0.0/0',
             GatewayId=Ref(constants.IGW),
         ))
     return self.cfn_template
Example #22
0
 def test_validation(self):
     route = Route('Route66',
                   DestinationCidrBlock='0.0.0.0/0',
                   RouteTableId=Ref('RouteTable66'),
                   InstanceId=If('UseNat', Ref('AWS::NoValue'),
                                 Ref('UseNat')),
                   NatGatewayId=If('UseNat', Ref('UseNat'),
                                   Ref('AWS::NoValue')))
     t = Template()
     t.add_resource(route)
     with self.assertRaises(ValueError):
         t.to_json()
Example #23
0
 def add_routes(self):
     t = self.template
     for subnet_dict in self.sceptre_user_data['subnets']:
         # Add route to Internet Gateway
         if subnet_dict['use_igw']:
             igw_route = t.add_resource(
                 Route(
                     '{}RtIgwRoute'.format(subnet_dict['tier']),
                     RouteTableId=self.route_table_ids[subnet_dict['tier']],
                     DestinationCidrBlock='0.0.0.0/0',
                     GatewayId=Ref(self.igw)))
     return 0
Example #24
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),
             ))
Example #25
0
    def add_nat_gateway_route(self, name, dest_cidr_block, route_table_id,
                              nat_gateway_id):
        """
        Add route to NAT gateway

        :param name: Name to assign to the route
        :param dest_cidr_block: Destination CIDR (probably '0.0.0.0/0')
        :param route_table_id: ID of the route table to assign the rule to
        :param nat_gateway_id: ID of the NAT gateway
        """
        self.template.add_resource(
            Route(
                name,
                DestinationCidrBlock=dest_cidr_block,
                RouteTableId=route_table_id,
                NatGatewayId=nat_gateway_id,
            ))
Example #26
0
File: stack.py Project: 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)))
Example #27
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))
Example #28
0
    def __add_route_table(self, route_table_name):

        self.template.add_resource(
            RouteTable(route_table_name, VpcId=Ref(self.vpc)))
        route = self.template.add_resource(
            Route(
                route_table_name + str(random.randint(1, 999)),
                RouteTableId=Ref(route_table_name),
                DestinationCidrBlock='0.0.0.0/0',
            ))
        # assumption of a naming convention and a pretty simple use case here.
        if "Priv" in route_table_name:
            gateway = self.nat_gateway
            route.NatGatewayId = Ref(gateway)
            route.DependsOn = 'Nat'
        else:
            gateway = self.igw
            route.GatewayId = Ref(gateway)
            route.DependsOn = 'AttachGateway'
Example #29
0
    def add_internet_gateway(self, name, routing_table_name, vpc_name):
        """
        Create Internet Gateway

        :param name: Name to assign the gateway
        :param routing_table_name: Name of routing table
        :param vpc_name: Name of VPC
        """
        self.template.add_resource(InternetGateway(name, ))

        self.template.add_resource(
            VPCGatewayAttachment('AttachGateway',
                                 VpcId=Ref(vpc_name),
                                 InternetGatewayId=Ref(name)))

        self.template.add_resource(
            Route(
                "{}IGRoute".format(vpc_name),
                DependsOn='AttachGateway',
                GatewayId=Ref(name),
                DestinationCidrBlock='0.0.0.0/0',
                RouteTableId=Ref(routing_table_name),
            ))
Example #30
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)
Example #31
0
gateway_attachment = VPCGatewayAttachment('GatewayAttachment')
gateway_attachment.VpcId = Ref(vpc)
gateway_attachment.InternetGatewayId = Ref('InternetGateway')
t.add_resource(gateway_attachment)

# route table
route_table = RouteTable(config['name'] + 'RouteTable')
route_table.VpcId = Ref(config['name'] + 'Vpc')
route_table.Tags=Tags(
        Application = Ref('AWS::StackName'),
        Name = config['name'] + '-route-table'
        )
t.add_resource(route_table)

# route to igw
route_igw = Route(config['name'] + 'Igw')
route_igw.DestinationCidrBlock = '0.0.0.0/0'
route_igw.GatewayId = Ref(internet_gateway)
route_igw.RouteTableId = Ref(route_table)
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)