Exemplo n.º 1
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]
Exemplo n.º 2
0
    def create_nat(self, availability_zone, public_subnet,
                   private_route_table):  # NOQA
        nat_device_name = '{}NATDevice'.format(availability_zone.cfn_name)

        nat_device = self.create_resource(
            ec2.Instance(nat_device_name,
                         InstanceType=Ref(self.nat_instance_type),
                         KeyName=Ref(self.keyname),
                         SourceDestCheck=False,
                         ImageId=Ref(self.nat_instance_ami),
                         NetworkInterfaces=[
                             ec2.NetworkInterfaceProperty(
                                 Description='ENI for NATDevice',
                                 GroupSet=[Ref(self.nat_security_group)],
                                 SubnetId=Ref(public_subnet),
                                 AssociatePublicIpAddress=True,
                                 DeviceIndex=0,
                                 DeleteOnTermination=True,
                             )
                         ],
                         Tags=self.get_tags(Name=nat_device_name)))

        self.create_resource(
            ec2.Route('{}PrivateRoute'.format(availability_zone.cfn_name),
                      RouteTableId=Ref(private_route_table),
                      DestinationCidrBlock=ALLOW_ALL_CIDR,
                      InstanceId=Ref(nat_device)))
Exemplo n.º 3
0
    def create_routing_resources(self):
        """Create VPC routing resource

        Handles the creation of VPC resources that need to be used throughout
        the stack and include the following:
         - internet gateway
         - vpc gateway attachment
         - public route table
         - public route
        """
        gateway = self.create_resource(
            ec2.InternetGateway('InternetGateway', Tags=self.get_tags()))

        gateway_attachment = self.create_resource(
            ec2.VPCGatewayAttachment('VPCGatewayAttachment',
                                     VpcId=Ref(self.vpc),
                                     InternetGatewayId=Ref(gateway)))

        public_route_table = self.create_resource(
            ec2.RouteTable('PublicRouteTable', VpcId=Ref(self.vpc)))

        self.create_resource(
            ec2.Route('PublicRoute',
                      RouteTableId=Ref(public_route_table),
                      DestinationCidrBlock=ALLOW_ALL_CIDR,
                      DependsOn=gateway_attachment.title,
                      GatewayId=Ref(gateway)))

        return public_route_table
Exemplo n.º 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
Exemplo n.º 5
0
def createCouchbaseRoute(t, gateway, routetable):
    couchbaseRoute = t.add_resource(
        ec2.Route('ROUTE',
                  DestinationCidrBlock='0.0.0.0/0',
                  GatewayId=Ref(gateway),
                  RouteTableId=Ref(routetable)))
    return couchbaseRoute
Exemplo n.º 6
0
 def internet_route(self):
     return ec2.Route(
         'Route',
         DependsOn='AttachGateway',
         GatewayId=Ref(self.gateway),
         DestinationCidrBlock='0.0.0.0/0',
         RouteTableId=Ref(self.route_table))
Exemplo n.º 7
0
    def create_routing_resources(self):
        gateway = self.create_resource(
            ec2.InternetGateway(
                'InternetGateway',
                Tags=self.get_tags()
            )
        )

        gateway_attachment = self.create_resource(
            ec2.VPCGatewayAttachment(
                'VPCGatewayAttachment',
                VpcId=Ref(self.vpc),
                InternetGatewayId=Ref(gateway)
            )
        )

        public_route_table = self.create_resource(
            ec2.RouteTable(
                'PublicRouteTable',
                VpcId=Ref(self.vpc))
        )

        self.create_resource(
            ec2.Route(
                'PublicRoute',
                RouteTableId=Ref(public_route_table),
                DestinationCidrBlock=ALLOW_ALL_CIDR,
                DependsOn=gateway_attachment.title,
                GatewayId=Ref(gateway)
            )
        )

        return public_route_table
Exemplo n.º 8
0
    def create_nat(self, availability_zone, public_subnet,
                   private_route_table):
        """Create a NAT instance and attach it to a private subnet with a private route

        Args:
          availabilty_zone (AvailabilityZone): where to place the NAT device
          public_subnet (ec2.Subnet): subnet to place the NAT device
          private_route_table (ec2.RouteTable): RouteTable to attach NAT device
        """
        nat_device_name = '{}NATDevice'.format(availability_zone.cfn_name)
        nat_device = self.create_resource(
            ec2.Instance(nat_device_name,
                         InstanceType=Ref(self.nat_instance_type_parameter),
                         KeyName=Ref(self.keyname_parameter),
                         SourceDestCheck=False,
                         ImageId=Ref(self.nat_instance_ami_parameter),
                         NetworkInterfaces=[
                             ec2.NetworkInterfaceProperty(
                                 Description='ENI for NATDevice',
                                 GroupSet=[Ref(self.nat_security_group)],
                                 SubnetId=Ref(public_subnet),
                                 AssociatePublicIpAddress=True,
                                 DeviceIndex=0,
                                 DeleteOnTermination=True,
                             )
                         ],
                         Tags=self.get_tags(Name=nat_device_name)))

        self.create_resource(
            ec2.Route('{}PrivateRoute'.format(availability_zone.cfn_name),
                      RouteTableId=Ref(private_route_table),
                      DestinationCidrBlock=ALLOW_ALL_CIDR,
                      InstanceId=Ref(nat_device)))
Exemplo n.º 9
0
def add_default_public_route(prefix, template, route_table, igw, vpc_gw):
    title = "%sDefaultPublicRoute" % prefix
    r = ec2.Route(title)
    r.RouteTableId = Ref(route_table)
    r.GatewayId = Ref(igw)
    r.DestinationCidrBlock = '0.0.0.0/0'
    r.DependsOn = vpc_gw.title
    template.add_resource(r)
Exemplo n.º 10
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
Exemplo n.º 11
0
def create_route(template, name, route_table, cidr_block=None, **attrs):
    cidr_block = cidr_block or WILDCARD_CIDR
    return template.add_resource(ec2.Route(
        name,
        RouteTableId=Ref(route_table),
        DestinationCidrBlock=cidr_block,
        **attrs
    ))
Exemplo n.º 12
0
 def gen_public_route(self):
     self.public_route = ec2.Route(
         "PublicRoute",
         RouteTableId=Ref(self.public_route_table),
         DestinationCidrBlock="0.0.0.0/0",
         GatewayId=Ref(self.internet_gateway),
         DependsOn=self.internet_gateway_attachment,
     )
     self.template.add_resource(self.public_route)
Exemplo n.º 13
0
 def add_routes(self):
     t = self.template
     for subnetDict in self.subnets:
         # Add route to Internet Gateway
         if subnetDict['useIgw']:
             igwRoute = t.add_resource(
                 ec2.Route(
                     'IGWRouteFor{}RouteTable'.format(subnetDict['tier']),
                     RouteTableId=Ref(subnetDict['tier'] + 'RouteTable'),
                     DestinationCidrBlock='0.0.0.0/0',
                     GatewayId=Ref(self.igw)))
         # Add route to NAT Gateway
         if subnetDict['useNat']:
             natGwRoute = t.add_resource(
                 ec2.Route(
                     'NatGwRouteFor{}RouteTable'.format(subnetDict['tier']),
                     RouteTableId=Ref(subnetDict['tier'] + 'RouteTable'),
                     DestinationCidrBlock='0.0.0.0/0',
                     NatGatewayId=Ref(self.natGw)))
Exemplo n.º 14
0
 def create_default_routes_for_public_subnets(self):
     # Add route through Internet Gateway to route tables for public subnets
     t = self.template
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'public':
             t.add_resource(
                 ec2.Route('%sSubnetDefaultRoute' % name,
                           RouteTableId=Ref(
                               self.subnets[name]['route_table']),
                           DestinationCidrBlock='0.0.0.0/0',
                           GatewayId=Ref(GATEWAY)))
Exemplo n.º 15
0
 def add_igw_default_route(self):
     name, tags = self._name_tags('igw_default_route')
     self.igw_default_route = self.t.add_resource(
         ec2.Route(
             name,
             DependsOn=self.igw_attachment.name,  # above
             GatewayId=Ref(self.igw_gateway),
             DestinationCidrBlock="0.0.0.0/0",
             RouteTableId=Ref(self.igw_route_table),
             # Doesn't support: Tags=Tags(**tags),
         ))
Exemplo n.º 16
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        for route, settings in variables['Routes'].iteritems():
            template.add_resource(
                ec2.Route(
                    'Route{}'.format(sub('[/.-]', '', route)),
                    **settings
                )
            )
Exemplo n.º 17
0
 def add_vpc_peering_to_public_table(
     self,
     peer_cidrs: list = [],
     vpc_peering_id: str = None,
 ):
     for cidr in peer_cidrs:
         route_title = f"{self.public_route_table.title}Peer{alphanum(cidr)}Route"
         self._r[route_title] = t_ec2.Route(
             title=route_title,
             RouteTableId=Ref(self.public_route_table),
             DestinationCidrBlock=cidr,
             VpcPeeringConnectionId=vpc_peering_id,
         )
Exemplo n.º 18
0
    def define_route(self, route_config, route_table):
        route = ec2.Route(route_config["name"],
                          DependsOn=route_config["target_id"],
                          DeletionPolicy=self.deletion_policy)
        route.RouteTableId = Ref(route_table)
        route.DestinationCidrBlock = route_config["dest_cidr"]
        target = route_config["target_type"]
        if target == "Gateway":
            route.GatewayId = Ref(route_config["target_id"])
            #route.DependsOn = "target_id"
        elif target == "Instance":
            route.InstanceId = Ref(route_config["target_id"])
        elif target == "NetworkInterfaceId":
            route.NetworkInterfaceId = Ref(route_config["target_id"])
        else:
            raise Exception("%s is not a valid target_type", target)

        self._add_resource(route)
Exemplo n.º 19
0
    def create_default_route(self):
        t = self.template

        if (self.internet_gateway_id is NoValue
                and self.nat_gateway_id is NoValue):
            # Don't create a default route if no gateway is provided
            # this is a totally private, unreachable network.
            return

        self.default_route = t.add_resource(
            ec2.Route(
                "DefaultRoute",
                RouteTableId=self.route_table.Ref(),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=self.internet_gateway_id,
                NatGatewayId=self.nat_gateway_id,
            ))

        t.add_output(Output("DefaultRouteId", Value=self.default_route.Ref()))
Exemplo n.º 20
0
    def create_nat_gateway(self, availability_zone, public_subnet,
                           private_route_table):
        nat_eip = self.create_resource(
            ec2.EIP(
                '{}NATIP'.format(availability_zone.cfn_name),
                Domain="vpc",
            ))

        nat_gateway = self.create_resource(
            ec2.NatGateway(
                '{}NATGateway'.format(availability_zone.cfn_name),
                AllocationId=GetAtt(nat_eip, 'AllocationId'),
                SubnetId=Ref(public_subnet),
            ))

        self.create_resource(
            ec2.Route('{}PrivateRoute'.format(availability_zone.cfn_name),
                      RouteTableId=Ref(private_route_table),
                      DestinationCidrBlock=ALLOW_ALL_CIDR,
                      NatGatewayId=Ref(nat_gateway)))
Exemplo n.º 21
0
    def resources(self, stack: Stack) -> list[AWSObject]:
        """Return resources associated with the Subnet construct."""
        result = [self.subnet, self.route_table, self.route_table_assoc]
        if self.is_public:
            result.extend(
                InternetGateway(name_prefix=self.name,
                                vpc=self.vpc,
                                route_table=self.route_table).resources(stack))
            if self.use_nat:
                result.extend([self.nat_gateway, self.nat_eip])

        if self.nat_to:
            result.append(
                ec2.Route(
                    name_to_id(f"{self.name}-nat-route"),
                    RouteTableId=Ref(self.route_table),
                    DestinationCidrBlock="0.0.0.0/0",
                    NatGatewayId=Ref(self.nat_to),
                ))

        return result
 def create_subnet_egress(self, index, route_table, igw_title, subnet_type):
     """
     Create an egress route for the a subnet with the given index and type
     Override to create egress routes for other subnet types
     """
     if subnet_type == 'public':
         self.template.add_resource(
             ec2.Route(subnet_type + 'Subnet' + str(index) + 'EgressRoute',
                       DependsOn=[igw_title],
                       DestinationCidrBlock='0.0.0.0/0',
                       GatewayId=Ref(self.template.igw),
                       RouteTableId=Ref(route_table)))
     elif subnet_type == 'private':
         nat_instance_type = self.config['nat']['instance_type']
         nat_enable_ntp = self.config['nat']['enable_ntp']
         extra_user_data = self.config['nat'].get('extra_user_data')
         self.template.merge(
             self.create_nat(index,
                             nat_instance_type,
                             nat_enable_ntp,
                             name='HaNat%s' % str(index),
                             extra_user_data=extra_user_data))
Exemplo n.º 23
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
    def create_subnet_egress(self, subnet_az, route_table, igw_title,
                             subnet_type, subnet_layer, nat_config):
        """
        Create an egress route for the subnet with the given subnet_az and type
        Override to create egress routes for other subnet types
        Creates the NAT instances in the public subnets
        """

        # For public subnets, create the route to the IGW
        if subnet_type == 'public':
            self.add_resource(
                ec2.Route(subnet_layer + 'AZ' + str(subnet_az) + 'EgressRoute',
                          DependsOn=[igw_title],
                          DestinationCidrBlock='0.0.0.0/0',
                          GatewayId=self.igw,
                          RouteTableId=Ref(route_table)))

        # For private subnets, create a NAT instance in a public subnet in the same AZ
        elif subnet_type == 'private':

            # If we have already created a NAT in this AZ, skip it
            if self.az_nat_mapping.get(subnet_az):
                return

            nat_instance_type = nat_config['instance_type']
            nat_enable_ntp = nat_config['enable_ntp']
            extra_user_data = nat_config.get('extra_user_data')
            ha_nat = self.create_nat(subnet_az,
                                     nat_instance_type,
                                     nat_enable_ntp,
                                     name='HaNat' + str(subnet_az),
                                     extra_user_data=extra_user_data)

            # We merge the NAT template into the root template
            self.merge(ha_nat)

            # Save the reference to the HA NAT, so we don't recreate it if we hit another private subnet in this AZ
            self.az_nat_mapping[subnet_az] = ha_nat
Exemplo n.º 25
0
def create_routing():
    return [
        ec2.InternetGateway(
            'internetGateway',
            Tags=_tags(),
        ),
        ec2.VPCGatewayAttachment(
            'vpcToInternetGateway',
            InternetGatewayId=Ref('internetGateway'),
            VpcId=Ref('vpc'),
        ),
        ec2.RouteTable(
            'routeTable',
            VpcId=Ref('vpc'),
            Tags=_tags(),
        ),
        ec2.Route(
            'routeToInternetGateway',
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=Ref('internetGateway'),
            RouteTableId=Ref('routeTable'),
        ),
    ]
Exemplo n.º 26
0
 def create_default_routes_for_private_subnets(self):
     # Default routes for private subnets through nat gateways in each az.
     # Use the nat gateways defined in the 'gateway_subnet' for eash subnet.
     t = self.template
     public_subnets = [
         subnet for subnet, attributes in self.subnets.items()
         if attributes['net_type'] == 'public'
     ]
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'private':
             for i in range(len(self.zones)):
                 gateway_subnet = self.subnets[name]['gateway_subnet']
                 nat_gateway = self.subnets[gateway_subnet]['nat_gateways'][
                     i]
                 if gateway_subnet not in public_subnets:
                     raise ValueError(
                         "'%s' is not a valid 'gateway_subnet' name in "
                         "subnet '%s'" % (gateway_subnet, subnet))
                 t.add_resource(
                     ec2.Route('%sSubnetDefaultRoute%d' % (name, i),
                               RouteTableId=Ref(
                                   self.subnets[name]['route_table'][i]),
                               DestinationCidrBlock='0.0.0.0/0',
                               NatGatewayId=Ref(nat_gateway)))
Exemplo n.º 27
0
    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),
        RouteTableId=Ref(private_route_table),
    ))

nat_eip = t.add_resource(ec2.EIP(
    'NatEip',
    Domain="vpc",
))
Exemplo n.º 28
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))
Exemplo n.º 29
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),
        )
Exemplo n.º 30
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)