示例#1
0
def main():
    template = Template()
    az_a = 'ap-southeast-2a'
    az_b = 'ap-southeast-2b'
    az_c = 'ap-southeast-2c'

    private_subnets = []
    public_subnets = []

    vpc = Ref(template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16')))
    public_route_table = template.add_resource(
        ec2.RouteTable('MyUnitPublicRouteTable', VpcId=vpc))
    private_route_table = template.add_resource(
        ec2.RouteTable('MyUnitPrivateRouteTable', VpcId=vpc))

    public_subnets.append(
        Subnet(template=template,
               route_table=public_route_table,
               az=az_a,
               cidr='10.0.1.0/24',
               vpc=vpc,
               is_public=True))
    public_subnets.append(
        Subnet(template=template,
               route_table=public_route_table,
               az=az_b,
               cidr='10.0.2.0/24',
               vpc=vpc,
               is_public=True))
    public_subnets.append(
        Subnet(template=template,
               route_table=public_route_table,
               az=az_c,
               cidr='10.0.3.0/24',
               vpc=vpc,
               is_public=True))
    private_subnets.append(
        Subnet(template=template,
               route_table=private_route_table,
               az=az_a,
               cidr='10.0.101.0/24',
               vpc=vpc,
               is_public=False))
    private_subnets.append(
        Subnet(template=template,
               route_table=private_route_table,
               az=az_b,
               cidr='10.0.102.0/24',
               vpc=vpc,
               is_public=False))
    private_subnets.append(
        Subnet(template=template,
               route_table=private_route_table,
               az=az_c,
               cidr='10.0.103.0/24',
               vpc=vpc,
               is_public=False))

    print(template.to_json(indent=2, separators=(',', ': ')))
示例#2
0
def setup_resources():
    """ Sets Up stack resources
    """
    global vpc, template, public_route_table, private_route_table, az, public_subnets, private_subnets
    template = Template()
    private_subnets = []
    public_subnets = []
    vpc = template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16'))
    public_route_table = template.add_resource(
        ec2.RouteTable('MyUnitPublicRouteTable', VpcId=Ref(vpc)))
    private_route_table = template.add_resource(
        ec2.RouteTable('MyUnitPrivateRouteTable', VpcId=Ref(vpc)))
    az = ['ap-southeast-2a', 'ap-southeast-2b', 'ap-southeast-2c']
示例#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
def createCouchbaseRouteTable(t, vpc):
    couchbaseRouteTable = t.add_resource(ec2.RouteTable(
        'ROUTETABLE',
        VpcId=Ref(vpc),
        Tags=Tags(Name=Join('', ['routetable-scalabilty-', Ref('AWS::Region')]))
    ))
    return couchbaseRouteTable
示例#5
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
示例#6
0
 def route_table(self):
     """Return route table to which the route to IGW is added."""
     if self._route_table is None:
         self._route_table = ec2.RouteTable(
             name_to_id(f"{self.name_prefix}-igw-route-table"),
             VpcId=Ref(self.vpc))
     return self._route_table
示例#7
0
    def create_route_table(self):
        t = self.template

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

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

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

        t.add_output(
            Output(
                "SubnetRouteTableAssociationId",
                Value=self.route_table_assoc.Ref()
            )
        )
示例#8
0
def create_route_table(template, name, vpc, **attrs):
    return template.add_resource(ec2.RouteTable(
        name,
        VpcId=Ref(vpc),
        Tags=Tags(Name=name),
        **attrs
    ))
示例#9
0
 def resources(self, stack: Stack) -> list[AWSObject]:
     """Return resources associated with the construct."""
     igw = ec2.InternetGateway(name_to_id(f"{self.name_prefix}-igw"))
     attachement = ec2.VPCGatewayAttachment(
         name_to_id(f"{self.name_prefix}-igw-attachement"),
         InternetGatewayId=Ref(igw),
         VpcId=Ref(self.vpc),
     )
     route_table = ec2.RouteTable(
         name_to_id(f"{self.name_prefix}-igw-route-table"), VpcId=Ref(self.vpc)
     )
     route = ec2.Route(
         name_to_id(f"{self.name_prefix}-igw-route"),
         RouteTableId=Ref(route_table),
         DestinationCidrBlock="0.0.0.0/0",
         GatewayId=Ref(igw),
     )
     route_table_associations = (
         ec2.SubnetRouteTableAssociation(
             name_to_id(f"{self.name_prefix}-{num}"),
             RouteTableId=Ref(route_table),
             SubnetId=Ref(subnet),
         )
         for subnet, num in zip(self.subnets, range(len(self.subnets)))
     )
     return [igw, attachement, route_table, route, *route_table_associations]
示例#10
0
    def create_subnets(self):
        self.default_azs = []
        self.default_private_subnets = []
        self.default_public_subnets = []

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

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

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

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

            self.PRIVATE_ROUTE_TABLES.append(private_route_table)

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

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

            if availability_zone.name in self.get_input('AvailabilityZones'):
                self.create_nat_gateway(availability_zone, public_subnet,
                                        private_route_table)
                self.default_azs.append(availability_zone.name)
                self.default_private_subnets.append(private_subnet)
                self.default_public_subnets.append(public_subnet)
示例#11
0
    def create_subnets(self, public_route_table):
        self.default_azs = []
        self.default_private_subnets = []
        self.default_public_subnets = []

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

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

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

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

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

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

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

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

            if availability_zone.name in self.get_input(
                    'AvailabilityZones').split(','):  # NOQA
                self.create_nat(availability_zone, public_subnet,
                                private_route_table)
                self.default_azs.append(availability_zone.name)
                self.default_private_subnets.append(private_subnet)
                self.default_public_subnets.append(public_subnet)
示例#12
0
 def add_igw_route_table(self):
     name, tags = self._name_tags('igw_route_table')
     self.igw_route_table = self.t.add_resource(
         ec2.RouteTable(
             name,
             VpcId=Ref(self.vpc),
             Tags=Tags(**tags),
         ))
     self.t.add_output(Output(
         "IGWRoute", Value=Ref(self.igw_route_table)
         ))
示例#13
0
def build_public_route_table(vpc):
    public_table = ec2.RouteTable(name="PublicRouteTable")
    public_table.Tags = [{
        "Key": "Network",
        "Value": "Public"
    }, {
        "Key": "Application",
        "Value": Ref("AWS::StackId")
    }]
    public_table.VpcId = Ref(vpc)
    return public_table
示例#14
0
def build_private_route_table(vpc):
    private_table = ec2.RouteTable(name="PrivateRouteTable")
    private_table.Tags = [{
        "Key": "Network",
        "Value": "Private"
    }, {
        "Key": "Application",
        "Value": Ref("AWS::StackId")
    }]
    private_table.VpcId = Ref(vpc)
    return private_table
示例#15
0
    def define_route_table(self, route_table_config, vpc_name):
        route_table = ec2.RouteTable(route_table_config["name"],
                                     DeletionPolicy=self.deletion_policy)
        route_table.VpcId = Ref(self.template.resources[vpc_name])
        route_table.Tags = self._get_tags(route_table_config)

        self._add_resource(route_table)

        for subnet in route_table_config["subnets"]:
            self.assign_subnet_route_table(subnet, route_table)

        return Ref(route_table)
示例#16
0
    def add_route_tables(self):
        t = self.template

        for subnetDict in self.subnets:
            tableName = subnetDict['tier'] + 'RouteTable'
            routeTable = t.add_resource(
                ec2.RouteTable(
                    tableName,
                    VpcId=Ref(self.vpc),
                    Tags=self.defaultTags +
                    [ec2.Tag('Name', Join("", [self.namePrefix, tableName]))]))
            self.routeTables[tableName] = Ref(routeTable)
示例#17
0
 def create_public_route_tables(self):
     # one route table for each public subnet
     t = self.template
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'public':
             route_table_name = '%sRouteTable' % name
             self.subnets[name]['route_table'] = route_table_name
             t.add_resource(
                 ec2.RouteTable(
                     #Tags=[ec2.Tag('type', net_type)],
                     route_table_name,
                     VpcId=VPC_ID,
                 ))
示例#18
0
def build(prefix, template, vpc, subnet):
    title = "%sPublicRouteTable" % prefix
    table = ec2.RouteTable(title)
    table.VpcId = GetAtt(subnet, 'VpcId')
    table.Tags = [tagging.name(title), tagging.env_name()]
    template.add_resource(table)
    template.add_output(
        Output('PublicRouteTable',
               Description="Public Route Table Identifier",
               Value=Ref(table)))
    gw = add_igw(prefix, template, subnet)
    vpc_gw = associate_vpc_igw(prefix, template, subnet, gw)
    add_default_public_route(prefix, template, table, gw, vpc_gw)
    associate_route_table(prefix, template, subnet, table)
示例#19
0
 def create_private_route_tables(self):
     # one route table for each az for private subnets
     t = self.template
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'private':
             self.subnets[name]['route_table'] = list()
             for i in range(len(self.zones)):
                 route_table_name = '%sRouteTable%d' % (name, i)
                 self.subnets[name]['route_table'].append(route_table_name)
                 t.add_resource(
                     ec2.RouteTable(
                         #Tags=[ec2.Tag('type', net_type)],
                         route_table_name,
                         VpcId=VPC_ID,
                     ))
示例#20
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
示例#21
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
示例#22
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'),
        ),
    ]
示例#23
0
        MapPublicIpOnLaunch=False,
        VpcId=Ref(vpc),
    ))

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

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

private_route_table = t.add_resource(
    ec2.RouteTable(
        'PrivateRouteTable',
        VpcId=Ref(vpc),
    ))

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

public_route_association = t.add_resource(
    ec2.SubnetRouteTableAssociation(
        'PublicRouteAssociation',
        SubnetId=Ref(public_net),
        RouteTableId=Ref(public_route_table),
    ))
示例#24
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))
示例#25
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),
        )
示例#26
0
文件: vpc.py 项目: nplutt/contacts
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)
示例#27
0
    def add_resources(self):
        """ Add All Cloudformation Resources. This will include vpc, igw, and any other network
        resources """
        self.vpc = self.template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock=Ref(self.VpcCidr),
                EnableDnsSupport=True,
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-VPC"),
            ))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.PubRT2Asocation = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubR2Associate",
                SubnetId=Ref(self.PubSubnet2),
                RouteTableId=Ref(self.PubRT2),
            ))
示例#28
0
    def sg_subnet_vpc(self, template, provision_refs):
        ref_stack_id = Ref('AWS::StackId')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        provision_refs.vpc = vpc
        provision_refs.security_group_ec2 = use_sg
        provision_refs.security_group_alb = use_alb_sg
        provision_refs.subnets.append(use_subnet)
        provision_refs.subnets.append(use_subnet2)
示例#29
0
def dump_base_yaml(cfn_file):

    template = Template()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
        Output(
            "PrivSubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(priv_subnet),
            Export=Export("PrivSubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
示例#30
0
    def add_resource(self):
        t = self.template

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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