Ejemplo n.º 1
0
    def create_nat_instance(self, zone_id, subnet_name):
        t = self.template
        suffix = zone_id
        nat_instance = t.add_resource(
            ec2.Instance(NAT_INSTANCE_NAME % suffix,
                         Condition="UseNatInstances",
                         ImageId=FindInMap('AmiMap', Ref("AWS::Region"),
                                           Ref("ImageName")),
                         SecurityGroupIds=[Ref(DEFAULT_SG),
                                           Ref(NAT_SG)],
                         SubnetId=Ref(subnet_name),
                         InstanceType=Ref('InstanceType'),
                         SourceDestCheck=False,
                         KeyName=Ref('SshKeyName'),
                         Tags=[ec2.Tag('Name', 'nat-gw%s' % suffix)],
                         DependsOn=GW_ATTACH))

        eip = t.add_resource(
            ec2.EIP('NATExternalIp%s' % suffix,
                    Domain='vpc',
                    InstanceId=If("UseNatInstances", Ref(nat_instance),
                                  Ref("AWS::NoValue")),
                    DependsOn=GW_ATTACH))

        t.add_resource(
            ec2.NatGateway(
                NAT_GATEWAY_NAME % suffix,
                Condition="UseNatGateway",
                AllocationId=GetAtt(eip, 'AllocationId'),
                SubnetId=Ref(subnet_name),
            ))

        return nat_instance
Ejemplo n.º 2
0
 def nat_gateway(self) -> Optional[ec2.NatGateway]:
     """Return a NAT gateway for this subnet."""
     if self.use_nat and self._nat_gateway is None:
         self._nat_gateway = ec2.NatGateway(
             name_to_id(f"{self.name}-nat"),
             AllocationId=GetAtt(self.nat_eip, "AllocationId"),
             SubnetId=Ref(self.subnet),
         )
     return self._nat_gateway
Ejemplo n.º 3
0
    def create_nat_instance(self, zone_id, subnet_name):
        t = self.template
        variables = self.get_variables()
        suffix = zone_id
        eip_name = "NATExternalIp%s" % suffix

        if variables["UseNatGateway"]:
            gateway_name = NAT_GATEWAY_NAME % suffix
            t.add_resource(
                ec2.NatGateway(
                    gateway_name,
                    AllocationId=GetAtt(eip_name, 'AllocationId'),
                    SubnetId=Ref(subnet_name),
                ))

            t.add_output(Output(gateway_name + "Id", Value=Ref(gateway_name)))

            # Using NAT Gateways, leave the EIP unattached - it gets allocated
            # to the NAT Gateway in that resource above
            eip_instance_id = Ref("AWS::NoValue")
        else:
            image_id = FindInMap('AmiMap', Ref("AWS::Region"),
                                 Ref("ImageName"))
            instance_name = NAT_INSTANCE_NAME % suffix
            t.add_resource(
                ec2.Instance(instance_name,
                             Condition="UseNatInstances",
                             ImageId=image_id,
                             SecurityGroupIds=[Ref(DEFAULT_SG),
                                               Ref(NAT_SG)],
                             SubnetId=Ref(subnet_name),
                             InstanceType=variables["InstanceType"],
                             SourceDestCheck=False,
                             KeyName=variables["SshKeyName"],
                             Tags=[ec2.Tag('Name', 'nat-gw%s' % suffix)],
                             DependsOn=GW_ATTACH))
            t.add_output(
                Output(instance_name + "PublicHostname",
                       Value=GetAtt(instance_name, "PublicDnsName")))
            t.add_output(
                Output(instance_name + "InstanceId", Value=Ref(instance_name)))

            # Since we're using NAT instances, go ahead and attach the EIP
            # to the NAT instance
            eip_instance_id = Ref(instance_name)

        t.add_resource(
            ec2.EIP(eip_name,
                    Domain='vpc',
                    InstanceId=eip_instance_id,
                    DependsOn=GW_ATTACH))
Ejemplo n.º 4
0
    def add_natgw(self):
        t = self.template
        natGwSubnetId = None

        for subnetDict in self.subnets:
            if subnetDict['useIgw']:
                natGwSubnetId = subnetDict['ID1']
            if natGwSubnetId != None:
                break

        self.natEip = t.add_resource(ec2.EIP('NatEIP', Domain='vpc'))

        self.natGw = t.add_resource(
            ec2.NatGateway('NatGateway',
                           AllocationId=GetAtt(self.natEip, "AllocationId"),
                           SubnetId=natGwSubnetId))
Ejemplo n.º 5
0
def create_vpc(t, env, env_number, subnet_mapping, subnet_config):
    '''
    Creates the VPC along with the subnets, IGW and RouteTables
    '''
    vpc_objects = {}
    vpc_objects['vpc'] = t.add_resource(
        ec2.VPC("{}VPC".format(env.upper()),
                CidrBlock="10.{}.0.0/16".format(env_number),
                InstanceTenancy="default",
                Tags=Tags(Name="{}VPC".format(env.upper()))))
    vpc_objects['igw'] = t.add_resource(ec2.InternetGateway("InternetGateway"))
    vpc_objects['igw_attachment'] = t.add_resource(
        ec2.VPCGatewayAttachment(
            "IGWAttachment",
            VpcId=Ref(vpc_objects['vpc']),
            InternetGatewayId=Ref(vpc_objects['igw']),
        ))

    # Create Subnets
    vpc_objects['subnets'] = {}
    vpc_objects['nat_eip'] = {}
    for subid in subnet_config:
        vpc_objects['subnets'][subid] = t.add_resource(
            ec2.Subnet(subid,
                       CidrBlock=subnet_config[subid]['subnet'],
                       VpcId=Ref(vpc_objects['vpc']),
                       AvailabilityZone="{}".format(
                           subnet_config[subid]['az_name']),
                       Tags=Tags(Name="{}Subnet".format(subid))))
        # Create NAT Gateways
        if subnet_config[subid]['service'] == 'nat':
            az = subnet_config[subid]['az_number']
            nat_eip_name = '{}{}NatEIP'.format(env.title(), az)
            vpc_objects['nat_eip'][nat_eip_name] = t.add_resource(
                ec2.EIP(nat_eip_name, Domain="vpc"))
            t.add_resource(
                ec2.NatGateway('{}{}NatGW'.format(env.title(), az),
                               AllocationId=GetAtt(
                                   vpc_objects['nat_eip'][nat_eip_name],
                                   'AllocationId'),
                               SubnetId=Ref(vpc_objects['subnets'][subid])))
    return t, vpc_objects
Ejemplo n.º 6
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)))
Ejemplo n.º 7
0
 def create_nat_gateways(self):
     # Nat gateways in public subnets, one per AZ
     t = self.template
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'public':
             if name == 'Public':
                 prefix = ''
             else:
                 prefix = name
             self.subnets[name]['nat_gateways'] = list()
             for i in range(len(self.zones)):
                 nat_gateway = '%sNatGateway%d' % (prefix, i)
                 nat_gateway_eip = '%sNatGatewayEIP%d' % (prefix, i)
                 self.subnets[name]['nat_gateways'].append(nat_gateway)
                 t.add_resource(ec2.EIP(nat_gateway_eip, Domain='vpc'))
                 t.add_resource(
                     ec2.NatGateway(
                         nat_gateway,
                         SubnetId=Ref(self.subnets[name]['az_subnets'][i]),
                         AllocationId=GetAtt(nat_gateway_eip,
                                             'AllocationId')))
Ejemplo n.º 8
0
    def create_nat_gateway(self):
        t = self.template
        variables = self.get_variables()

        if variables["NatGatewayId"] or not variables["CreateNatGateway"]:
            return

        self.nat_gateway_eip = t.add_resource(
            ec2.EIP("NatGatewayEIP", Domain="vpc"))

        t.add_output(Output("NatGatewayEIP", Value=self.nat_gateway_eip.Ref()))
        t.add_output(
            Output("NatGatewayEIPAllocationId",
                   Value=self.nat_gateway_eip.GetAtt("AllocationId")))

        self.nat_gateway = t.add_resource(
            ec2.NatGateway(
                "NatGateway",
                AllocationId=self.nat_gateway_eip.GetAtt("AllocationId"),
                SubnetId=self.subnet.Ref()))

        t.add_output(Output("NatGatewayId", Value=self.nat_gateway.Ref()))
Ejemplo n.º 9
0
def ssm_network():
    template = Template()

    default_route = "0.0.0.0/0"
    vpc_cidr = "192.168.0.0/16"

    template.add_parameter(Parameter(
        "VpcCidr",
        Type="String",
        Description="Cidr block for VPC",
        MinLength="9",
        MaxLength="18",
        Default=vpc_cidr,
        AllowedPattern="(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})/(\\d{1,2})",
        ConstraintDescription="Must match following pattern 'xxx.xxx.xxx.xxx/xx'"
    ))

    template.add_parameter(Parameter(
        "CreateEndpoints",
        Type="String",
        Description="Create VPC Endpoints",
        Default="No",
        AllowedValues=["Yes", "No"],
        ConstraintDescription="'Yes' or 'No' are only options"
    ))

    template.add_parameter(Parameter(
        "CreateNatGateway",
        Type="String",
        Description="Create NAT Gateway",
        Default="No",
        AllowedValues=["Yes", "No"],
        ConstraintDescription="'Yes' or 'No' are only options"
    ))

    conditions = {
        "CreateVpcEndpointsUpperYes": Equals(
            Ref("CreateEndpoints"), "Yes"
        ),
        "CreateVpcEndpointsLowerYes": Equals(
            Ref("CreateEndpoints"), "yes"
        ),
        "CreateVpcEndpoints": Or(
            Condition("CreateVpcEndpointsUpperYes"),
            Condition("CreateVpcEndpointsLowerYes")
        ),
        "CreateNatGatewayUpperYes": Equals(
            Ref("CreateNatGateway"), "Yes"
        ),
        "CreateNatGatewayLowerYes": Equals(
            Ref("CreateNatGateway"), "yes"
        ),
        "CreateNatGateway": Or(
            Condition("CreateNatGatewayUpperYes"),
            Condition("CreateNatGatewayLowerYes")
        )
    }

    ssm_vpc = ec2.VPC(
        'SsmVpc',
        CidrBlock=Ref("VpcCidr"),
        InstanceTenancy="default",
        EnableDnsHostnames=True,
        EnableDnsSupport=True,
        Tags=Tags(
            Name="SSM VPC"
        )
    )

    subnet_blocks = Cidr(GetAtt(ssm_vpc, "CidrBlock"), 256, 8)

    ssm_ig = ec2.InternetGateway(
        'SsmIG',
    )

    ssm_attach_gw = ec2.VPCGatewayAttachment(
        'SsmAttachGateway',
        InternetGatewayId=Ref(ssm_ig),
        VpcId=Ref(ssm_vpc)
    )

    ssm_public_subnet = ec2.Subnet(
        'SsmPublicSubnet',
        DependsOn=ssm_attach_gw,
        AvailabilityZone=Select(0, GetAZs('')),
        CidrBlock=Select(0, subnet_blocks),
        VpcId=Ref(ssm_vpc),
        Tags=Tags(
            Name="Public Subnet"
        )
    )

    ssm_public_route_table = ec2.RouteTable(
        'SsmPublicRouteTable',
        VpcId=Ref(ssm_vpc),
    )

    ssm_public_route = ec2.Route(
        'SsmPublicRoute',
        DestinationCidrBlock=default_route,
        GatewayId=Ref(ssm_ig),
        RouteTableId=Ref(ssm_public_route_table)
    )

    ssm_public_subnet_route_table_association = ec2.SubnetRouteTableAssociation(
        'SsmPublicSubnetRouteTableAssociation',
        RouteTableId=Ref(ssm_public_route_table),
        SubnetId=Ref(ssm_public_subnet)
    )

    ssm_eip_nat_gateway = ec2.EIP(
        'SsmEipNatGateway',
        Condition="CreateNatGateway"
    )

    ssm_nat_gateway = ec2.NatGateway(
        'SsmNatGateway',
        Condition="CreateNatGateway",
        DependsOn=ssm_eip_nat_gateway,
        SubnetId=Ref(ssm_public_subnet),
        AllocationId=GetAtt(ssm_eip_nat_gateway, "AllocationId"),
    )

    ssm_private_subnet = ec2.Subnet(
        'SsmPrivateSubnet',
        DependsOn=ssm_attach_gw,
        AvailabilityZone=Select(0, GetAZs('')),
        CidrBlock=Select(1, subnet_blocks),
        VpcId=Ref(ssm_vpc),
        Tags=Tags(
            Name="Private Subnet"
        )
    )

    ssm_private_route_table = ec2.RouteTable(
        'SsmPrivateRouteTable',
        VpcId=Ref(ssm_vpc),
    )

    ssm_private_route = ec2.Route(
        'SsmPrivateRoute',
        Condition="CreateNatGateway",
        DestinationCidrBlock=default_route,
        NatGatewayId=Ref(ssm_nat_gateway),
        RouteTableId=Ref(ssm_private_route_table)
    )

    ssm_private_subnet_route_table_association = ec2.SubnetRouteTableAssociation(
        'SsmPrivateSubnetRouteTableAssociation',
        RouteTableId=Ref(ssm_private_route_table),
        SubnetId=Ref(ssm_private_subnet)
    )

    ssm_sg_ingress_rules = [
        ec2.SecurityGroupRule(
            ToPort=443,
            FromPort=443,
            IpProtocol="tcp",
            CidrIp=GetAtt(ssm_vpc, "CidrBlock")
        )
    ]

    ssm_security_group = ec2.SecurityGroup(
        'SsmSecurityGroup',
        GroupName="SsmSG",
        GroupDescription="SG for SSM usage",
        VpcId=Ref(ssm_vpc),
        SecurityGroupIngress=ssm_sg_ingress_rules
    )

    ssm_s3e_vpc_endpoint = ec2.VPCEndpoint(
        'SsmS3VpcEndpoint',
        Condition="CreateVpcEndpoints",
        RouteTableIds=[
            Ref(ssm_private_route_table)
        ],
        ServiceName=vpc_endpoint("s3"),
        VpcId=Ref(ssm_vpc),
        VpcEndpointType="Gateway"
    )

    ssm_ssm_vpc_endpoint = ec2.VPCEndpoint(
        'SsmSsmVpcEndpoint',
        Condition="CreateVpcEndpoints",
        SubnetIds=[Ref(ssm_private_subnet)],
        ServiceName=vpc_endpoint("ssm"),
        VpcId=Ref(ssm_vpc),
        VpcEndpointType="Interface",
        SecurityGroupIds=[
            Ref(ssm_security_group)
        ],
        PrivateDnsEnabled=True
    )

    ssm_ssmmessages_vpc_endpoint = ec2.VPCEndpoint(
        'SsmSsmMessagesVpcEndpoint',
        Condition="CreateVpcEndpoints",
        SubnetIds=[Ref(ssm_private_subnet)],
        ServiceName=vpc_endpoint("ssmmessages"),
        VpcId=Ref(ssm_vpc),
        VpcEndpointType="Interface",
        SecurityGroupIds=[
            Ref(ssm_security_group)
        ],
        PrivateDnsEnabled=True
    )

    ssm_ec2messages_vpc_endpoint = ec2.VPCEndpoint(
        'SsmEc2MessagesVpcEndpoint',
        Condition="CreateVpcEndpoints",
        SubnetIds=[Ref(ssm_private_subnet)],
        ServiceName=vpc_endpoint("ec2messages"),
        VpcId=Ref(ssm_vpc),
        VpcEndpointType="Interface",
        SecurityGroupIds=[
            Ref(ssm_security_group)
        ],
        PrivateDnsEnabled=True
    )

    template.add_resource(ssm_vpc)
    template.add_resource(ssm_ig)
    template.add_resource(ssm_attach_gw)
    template.add_resource(ssm_eip_nat_gateway)
    template.add_resource(ssm_public_subnet)
    template.add_resource(ssm_public_route_table)
    template.add_resource(ssm_nat_gateway)
    template.add_resource(ssm_public_route)
    template.add_resource(ssm_public_subnet_route_table_association)
    template.add_resource(ssm_private_subnet)
    template.add_resource(ssm_private_route_table)
    template.add_resource(ssm_private_route)
    template.add_resource(ssm_private_subnet_route_table_association)
    template.add_resource(ssm_security_group)
    template.add_resource(ssm_s3e_vpc_endpoint)
    template.add_resource(ssm_ec2messages_vpc_endpoint)
    template.add_resource(ssm_ssm_vpc_endpoint)
    template.add_resource(ssm_ssmmessages_vpc_endpoint)

    for k in conditions:
        template.add_condition(k, conditions[k])

    template.add_output(Output(
        'SsmVpc',
        Description="VPC for SSM",
        Value=Ref(ssm_vpc),
        Export=Export(Join("", [Ref("AWS::StackName"), "-ssm-vpc"]))
    ))

    template.add_output(Output(
        'SsmSg',
        Description="Security Group for SSM",
        Value=Ref(ssm_security_group),
        Export=Export(Join("", [Ref("AWS::StackName"), "-ssm-sg"]))
    ))

    template.add_output(Output(
        'SsmPrivateSubnet',
        Description="Private Subnet for SSM",
        Value=Ref(ssm_private_subnet),
        Export=Export(Join("", [Ref("AWS::StackName"), "-ssm-private-subnet"]))
    ))

    template.add_output(Output(
        'SsmPrivateRouteTable',
        Description="Private RouteTable for SSM",
        Value=Ref(ssm_private_route_table),
        Export=Export(Join("", [Ref("AWS::StackName"), "-ssm-private-route-table"]))
    ))

    with open(os.path.dirname(os.path.realpath(__file__)) + '/ssm_network.yml', 'w') as cf_file:
        cf_file.write(template.to_yaml())

    return template.to_yaml()
Ejemplo n.º 10
0
    def add_public_subnet_group(
        self,
        name_prefix: str,
        cidr_block: str,
        no_of_subnets: int = 4,
        create_nat_gateways: bool = False,
    ):
        """Create public subnets and, optionally, NAT Gateways

        Args:
            name_prefix (str): Subnet name. AZ will be added at the end.
            cidr_block (str): Range of IP addresses to be split over
                availability zones.
            no_of_subnets (int, optional): How many subnets to set up.
                Defaults to 4.
            create_nat_gateways (bool, optional): If True, it will
                create one NAT gateway in each subnet and a private
                route table for each. Defaults to False.
        """
        for res in multiaz_subnets(
                name_prefix=name_prefix,
                cidr_block=cidr_block,
                region=self.region,
                no_of_subnets=no_of_subnets,
                vpc=self.vpc,
                network_acl=self.public_nacl,
                route_table=self.public_route_table,
        ):
            self._r[res.title] = res
            self.public_subnets.append(res)
            if create_nat_gateways and res.resource[
                    "Type"] == "AWS::EC2::Subnet":
                subnet = res
                az = subnet.Metadata["az"]
                az_index = subnet.Metadata["az_index"]
                suffix = subnet.Metadata["suffix"]
                # Elastic IP for NAT Gateway
                eip = t_ec2.EIP(title=f"EipNatGw{suffix}", Domain="vpc")
                self._r[eip.title] = eip
                # NAT Gateway
                nat_gw = t_ec2.NatGateway(
                    title=f"NatGw{suffix}",
                    AllocationId=GetAtt(eip, "AllocationId"),
                    SubnetId=Ref(subnet),
                    Tags=[{
                        "Key": "Name",
                        "Value": f"Nat Gw {az_index}"
                    }],
                    Metadata={
                        "az": az,
                        "az_index": az_index,
                        "suffix": suffix
                    },
                )
                self._r[nat_gw.title] = nat_gw
                self.nat_gateways.append(nat_gw)
                # Natted route table
                route_table = t_ec2.RouteTable(
                    title=f"PrivRouteTable{suffix}",
                    VpcId=Ref(self.vpc),
                    Tags=[{
                        "Key": "Name",
                        "Value": f"Private {az_index}"
                    }],
                    Metadata={
                        "az": az,
                        "az_index": az_index,
                        "suffix": suffix
                    },
                )
                self.gateway_subnets.append(subnet)
                self.natted_route_tables.append(route_table)
                # NAT route
                self._r[route_table.title] = route_table
                route = t_ec2.Route(
                    title=f"NatRoute{az_index.upper()}",
                    RouteTableId=Ref(route_table),
                    DestinationCidrBlock="0.0.0.0/0",
                    NatGatewayId=Ref(nat_gw),
                )
                self._r[route.title] = route
Ejemplo n.º 11
0
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",
))

nat = t.add_resource(
    ec2.NatGateway(
        "Nat",
        AllocationId=GetAtt(nat_eip, "AllocationId"),
        SubnetId=Ref(public_net),
    ))

t.add_resource(
    ec2.Route(
        "NatRoute",
        RouteTableId=Ref(private_route_table),
        DestinationCidrBlock="0.0.0.0/0",
        NatGatewayId=Ref(nat),
    ))

t.add_output(Output("VPCId", Value=Ref(vpc), Description="VPC Id"))

t.add_output(
    Output(
Ejemplo n.º 12
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)
Ejemplo n.º 13
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)
Ejemplo n.º 14
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

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

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

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

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

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

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

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

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

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

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PubSubnet%iRTAssoc' % (i + 1),
                    Condition='PublicAZ%i' % (i + 1),
                    RouteTableId=Ref(publicroutetable),
                    SubnetId=Ref('PubSubnet%i' % (i + 1))))
            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PriSubnet%iRTAssoc' % (i + 1),
                    Condition='PrivateAZ%i' % (i + 1),
                    RouteTableId=Ref('PrivateRouteTable%i' % (i + 1)),
                    SubnetId=Ref('PriSubnet%i' % (i + 1))))
Ejemplo n.º 15
0
    def __init__(self, key):
        vpc_net = '10.80'
        o_subnetprivate = []
        o_subnetpublic = []

        # Resources
        R_VPC = ec2.VPC('VPC')
        auto_get_props(R_VPC, mapname='')

        R_RouteTablePrivate = EC2RouteTable('RouteTablePrivate')
        R_RouteTablePrivate.Tags = Tags(Name=Sub('${VPCName}-Private'))

        R_RouteTablePublic = EC2RouteTable('RouteTablePublic')
        R_RouteTablePublic.Tags = Tags(Name=Sub('${VPCName}-Public'))

        R_InternetGateway = ec2.InternetGateway('InternetGateway')
        R_InternetGateway.Tags = Tags(Name=Ref('VPCName'))

        R_VPCGatewayAttachment = ec2.VPCGatewayAttachment(
            'VPCGatewayAttachment')
        R_VPCGatewayAttachment.InternetGatewayId = Ref('InternetGateway')
        R_VPCGatewayAttachment.VpcId = Ref('VPC')

        if cfg.NatGateway != 'None':
            # resources
            R_EIPNat = ec2.EIP('EIPNat')
            R_EIPNat.Domain = 'vpc'

            R_NatGateway = ec2.NatGateway('NatGateway')
            R_NatGateway.AllocationId = GetAtt('EIPNat', 'AllocationId')
            R_NatGateway.SubnetId = Ref('SubnetPublicA')

            R_RouteNatGateway = EC2RouteNatGateway('RouteNatGateway')

            # outputs
            O_EIPNat = Output('EIPNat')
            O_EIPNat.Value = Ref('EIPNat')

            add_obj([
                R_NatGateway,
                R_RouteNatGateway,
                R_EIPNat,
                O_EIPNat,
            ])

        R_RouteInternetGateway = EC2RouteInternetGateway(
            'RouteInternetGateway')

        add_obj([
            R_VPC,
            R_RouteTablePrivate,
            R_RouteTablePublic,
            R_InternetGateway,
            R_VPCGatewayAttachment,
            R_RouteInternetGateway,
        ])

        for i in range(cfg.AZones['MAX']):
            zone_name = cfg.AZoneNames[i]
            zone_cond = f'Zone{zone_name}'

            # parameters
            p_SubnetCidrBlockPrivate = Parameter(
                f'SubnetCidrBlockPrivate{zone_name}')
            p_SubnetCidrBlockPrivate.Description = (
                f'Ip Class Range for Private Subnet in Zone {zone_name}')
            p_SubnetCidrBlockPrivate.Default = f'{vpc_net}.{i * 16}.0/20'

            p_SubnetCidrBlockPublic = Parameter(
                f'SubnetCidrBlockPublic{zone_name}')
            p_SubnetCidrBlockPublic.Description = (
                f'Ip Class Range for Public Subnet in zone {zone_name}')
            p_SubnetCidrBlockPublic.Default = f'{vpc_net}.{i + 200}.0/24'

            add_obj([
                p_SubnetCidrBlockPrivate,
                p_SubnetCidrBlockPublic,
            ])

            # conditions
            c_Zone = {
                zone_cond:
                Equals(
                    FindInMap('AvabilityZones', Ref('AWS::Region'),
                              f'Zone{i}'), 'True')
            }

            add_obj(c_Zone)

            # resources

            r_SubnetPrivate = EC2SubnetPrivate(f'SubnetPrivate{zone_name}',
                                               zone=zone_name)
            r_SubnetPrivate.Condition = zone_cond

            r_SubnetPublic = EC2SubnetPublic(f'SubnetPublic{zone_name}',
                                             zone=zone_name)
            r_SubnetPublic.Condition = zone_cond

            r_SubnetRouteTableAssociationPrivate = (
                EC2SubnetRouteTableAssociationPrivate(
                    f'SubnetRouteTableAssociationPrivate{zone_name}',
                    zone=zone_name))
            r_SubnetRouteTableAssociationPrivate.Condition = zone_cond

            r_SubnetRouteTableAssociationPublic = (
                EC2SubnetRouteTableAssociationPublic(
                    f'SubnetRouteTableAssociationPublic{zone_name}',
                    zone=zone_name))
            r_SubnetRouteTableAssociationPublic.Condition = zone_cond

            add_obj([
                r_SubnetPrivate,
                r_SubnetPublic,
                r_SubnetRouteTableAssociationPrivate,
                r_SubnetRouteTableAssociationPublic,
            ])

            # outputs
            o_subnetprivate.append(
                If(zone_cond, Ref(f'SubnetPrivate{zone_name}'),
                   Ref('AWS::NoValue')))

            o_subnetpublic.append(
                If(zone_cond, Ref(f'SubnetPublic{zone_name}'),
                   Ref('AWS::NoValue')))

        # Outputs
        O_SubnetsPrivate = Output('SubnetsPrivate')
        O_SubnetsPrivate.Value = Join(',', o_subnetprivate)
        O_SubnetsPrivate.Export = Export('SubnetsPrivate')

        O_SubnetsPublic = Output('SubnetsPublic')
        O_SubnetsPublic.Value = Join(',', o_subnetpublic)
        O_SubnetsPublic.Export = Export('SubnetsPublic')

        add_obj([
            O_SubnetsPrivate,
            O_SubnetsPublic,
        ])
# Nat Gateway EIP
natGatewayEIP = t.add_resource(ec2.EIP("NatGatewayEIP", Domain="vpc"))

# Public Subnet
publicSubnet = t.add_resource(
    Subnet("PublicSubnet",
           VpcId=Ref(vpc),
           AvailabilityZone=Join("", [Ref("AWS::Region"), "a"]),
           CidrBlock="10.0.1.0/24",
           MapPublicIpOnLaunch=True,
           Tags=Tags(Name="10.0.1.0-Public")))

# Nat Gateway
natGateway = t.add_resource(
    ec2.NatGateway("NatGateway",
                   AllocationId=GetAtt(natGatewayEIP, 'AllocationId'),
                   SubnetId=Ref(publicSubnet)))

# Public Route Table
publicRouteTable = t.add_resource(
    RouteTable("PublicRouteTable",
               VpcId=Ref(vpc),
               Tags=Tags(Name="Demo-Public-Route")))

# Default Public Route
t.add_resource(
    Route("DefaultPublicRoute",
          DependsOn=gatewayAttachment.title,
          RouteTableId=Ref(publicRouteTable),
          DestinationCidrBlock="0.0.0.0/0",
          GatewayId=Ref(internetGateway)))
Ejemplo n.º 17
0
    def configure(self):
        self.vpc_metadata = constants.ENVIRONMENTS[self.env]['vpc']
        self.set_description('VPC, Routes, Base Security Groups, and NATs')

        common_vpc_tags = [ec2.Tag('Name', self.env)
                           ] + self.get_tags(service_override='VPC')

        _vpc = self.add_resource(
            ec2.VPC('VPC',
                    CidrBlock=self.vpc_metadata['cidrblock'],
                    EnableDnsSupport=True,
                    EnableDnsHostnames=True,
                    Tags=common_vpc_tags))

        _dhcp_options = self.add_resource(
            ec2.DHCPOptions('DHCPOptions',
                            DomainName="node.{}.{}".format(
                                self.env, constants.TAG),
                            DomainNameServers=['AmazonProvidedDNS'],
                            Tags=common_vpc_tags))

        self.add_resource(
            ec2.VPCDHCPOptionsAssociation('VPCDHCPOptionsAssociation',
                                          DhcpOptionsId=Ref(_dhcp_options),
                                          VpcId=Ref(_vpc)))

        _internet_gateway = self.add_resource(
            ec2.InternetGateway('InternetGateway',
                                Tags=self.get_tags(
                                    service_override='InternetGateway',
                                    role_override='InternetGateway')))
        self.add_resource(
            ec2.VPCGatewayAttachment('AttachInternetGateway',
                                     VpcId=Ref(_vpc),
                                     InternetGatewayId=Ref(_internet_gateway)))
        # route_tables stores all ec2.RouteTables generated and adds them to
        # a private vpc s3 endpoint
        route_tables = []
        _public_route_table = self.add_resource(
            ec2.RouteTable('PublicRouteTable',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PublicRouteTable',
                               role_override='PublicRouteTable')))
        route_tables.append(_public_route_table)
        # Public Subnet Routes and ACLs
        self.add_resource(
            ec2.Route('PublicRoute',
                      RouteTableId=Ref(_public_route_table),
                      DestinationCidrBlock='0.0.0.0/0',
                      GatewayId=Ref(_internet_gateway)))
        _public_network_acl = self.add_resource(
            ec2.NetworkAcl('PublicNetworkAcl',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PublicNetworkAcl',
                               role_override='PublicNetworkAcl')))
        self.add_resource(
            ec2.NetworkAclEntry('IngressPublicNetworkAclEntry',
                                NetworkAclId=Ref(_public_network_acl),
                                RuleNumber=100,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=False,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        self.add_resource(
            ec2.NetworkAclEntry('EgressPublicNetworkAclEntry',
                                NetworkAclId=Ref(_public_network_acl),
                                RuleNumber=101,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=True,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        # Private Network ACLs
        _private_network_acl = self.add_resource(
            ec2.NetworkAcl('PrivateNetworkAcl',
                           VpcId=Ref(_vpc),
                           Tags=self.get_tags(
                               service_override='PrivateNetworkAcl',
                               role_override='PrivateNetworkAcl')))
        self.add_resource(
            ec2.NetworkAclEntry('IngressPrivateNetworkAclEntry',
                                NetworkAclId=Ref(_private_network_acl),
                                RuleNumber=100,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=False,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))
        self.add_resource(
            ec2.NetworkAclEntry('EgressPrivateNetworkAclEntry',
                                NetworkAclId=Ref(_private_network_acl),
                                RuleNumber=101,
                                Protocol='-1',
                                RuleAction='allow',
                                Egress=True,
                                CidrBlock='0.0.0.0/0',
                                PortRange=ec2.PortRange(From=1, To=65535)))

        # Default security groups - referenced by name by constants/default-security-groups
        # _nat_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'NATSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Security Group for NAT Instances',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': '-1', 'FromPort': 1, 'ToPort': 65535, 'CidrIp': self.vpc_metadata['cidrblock']},
        #             {'IpProtocol': '-1', 'FromPort': 1, 'ToPort': 65535, 'CidrIp': '10.0.0.0/8'}
        #         ],
        #         Tags=self.get_tags(service_override='NAT', role_override='NAT-SecurityGroup')
        #     )
        # )
        # _consul_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'ConsulSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Security Group for Consul access',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': 'tcp', 'FromPort': 8300, 'ToPort': 8302, 'CidrIp': '10.0.0.0/8'},  # consul server rpc/serf
        #             {'IpProtocol': 'udp', 'FromPort': 8300, 'ToPort': 8302, 'CidrIp': '10.0.0.0/8'},  # consul server rpc/serf
        #             {'IpProtocol': 'tcp', 'FromPort': 8400, 'ToPort': 8400, 'CidrIp': '10.0.0.0/8'},  # consul client rpc
        #             {'IpProtocol': 'tcp', 'FromPort': 8500, 'ToPort': 8500, 'CidrIp': '10.0.0.0/8'},  # consul http
        #             {'IpProtocol': 'tcp', 'FromPort': 8600, 'ToPort': 8600, 'CidrIp': '10.0.0.0/8'},  # consul dns
        #             {'IpProtocol': 'udp', 'FromPort': 8600, 'ToPort': 8600, 'CidrIp': '10.0.0.0/8'}   # consul dns
        #         ],
        #         Tags=[
        #             ec2.Tag('ivy:team', self.TEAM['email']),
        #             ec2.Tag('ivy:environment', self.env),
        #             ec2.Tag('ivy:service', 'Consul'),
        #             ec2.Tag('ivy:role', 'Consul-SecurityGroup')
        #         ]
        #     )
        # )
        # _ssh_security_group = self.add_resource(
        #     ec2.SecurityGroup(
        #         'InternalSecurityGroup',
        #         VpcId=Ref(_vpc),
        #         GroupDescription='Internal Rules',
        #         SecurityGroupIngress=[
        #             {'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'CidrIp': '10.0.0.0/8'},
        #             {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'CidrIp': '10.0.0.0/8'}
        #         ],
        #         SecurityGroupEgress=[
        #             {'IpProtocol': '-1', 'FromPort': 0, 'ToPort': 65535, 'CidrIp': '0.0.0.0/0'}
        #         ],
        #         Tags=[
        #             ec2.Tag('ivy:team', self.TEAM['email']),
        #             ec2.Tag('ivy:environment', self.env),
        #             ec2.Tag('ivy:service', 'infrastructure'),
        #             ec2.Tag('ivy:role', 'internal')
        #         ]
        #     )
        # )
        #
        # self.add_security_group(Ref(_nat_security_group), Ref(_consul_security_group), Ref(_ssh_security_group))

        ## This sets up all private and public AZs
        for index, zone in enumerate(self.vpc_metadata['zones'], 1):
            _public_subnet = self.add_resource(
                ec2.Subnet(
                    'PublicSubnet{}'.format(index),
                    VpcId=Ref(_vpc),
                    CidrBlock=zone['public-cidrblock'],
                    AvailabilityZone=zone['availability-zone'],
                    MapPublicIpOnLaunch=True,
                    Tags=self.get_tags(
                        service_override='PublicSubnet',
                        role_override='PublicSubnet{}'.format(index)) +
                    [
                        ec2.Tag('Name', '{}-PublicSubnet{}'.format(
                            self.env, index))
                    ]))
            self.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PublicSubnetRouteTableAssociation{}'.format(index),
                    SubnetId=Ref(_public_subnet),
                    RouteTableId=Ref(_public_route_table)))
            self.add_resource(
                ec2.SubnetNetworkAclAssociation(
                    'PublicSubnetNetworkAclAssociation{}'.format(index),
                    SubnetId=Ref(_public_subnet),
                    NetworkAclId=Ref(_public_network_acl)))

            # Allow VPCs with no private subnets (save money on NAT instances for VPCs with only public instances)
            if zone.get('private-cidrblock'):
                _private_subnet = self.add_resource(
                    ec2.Subnet(
                        'PrivateSubnet{}'.format(index),
                        VpcId=Ref(_vpc),
                        CidrBlock=zone['private-cidrblock'],
                        AvailabilityZone=zone['availability-zone'],
                        Tags=self.get_tags(
                            service_override='PrivateSubnet',
                            role_override='PrivateSubnet{}'.format(index)) + [
                                ec2.Tag(
                                    'Name', '{}-PrivateSubnet{}'.format(
                                        self.env, index))
                            ]))
                # Private subnets get their own route table for AZ-specific NATs
                _private_route_table = self.add_resource(
                    ec2.RouteTable(
                        'PrivateRouteTable{}'.format(index),
                        VpcId=Ref(_vpc),
                        Tags=self.get_tags(
                            service_override='PrivateRouteTable',
                            role_override='PrivateRouteTable{}'.format(
                                index))))
                route_tables.append(_private_route_table)

                # Create an EIP to be used with the NAT instance or gateway
                _nat_eip = self.add_resource(
                    ec2.EIP('NATInstanceEIP{}'.format(index), Domain='vpc'))

                # Use VPC NAT Gateway
                _nat_gw = self.add_resource(
                    ec2.NatGateway('NATGateway{}'.format(index),
                                   AllocationId=GetAtt(_nat_eip,
                                                       "AllocationId"),
                                   SubnetId=Ref(_public_subnet)))
                # Create a route via the NAT GW for the private route table
                self.add_resource(
                    ec2.Route('PrivateRoute{}'.format(index),
                              RouteTableId=Ref(_private_route_table),
                              DestinationCidrBlock='0.0.0.0/0',
                              NatGatewayId=Ref(_nat_gw)))

                self.add_resource(
                    ec2.SubnetRouteTableAssociation(
                        'PrivateSubnetRouteTableAssociation{}'.format(index),
                        SubnetId=Ref(_private_subnet),
                        RouteTableId=Ref(_private_route_table)))
                self.add_resource(
                    ec2.SubnetNetworkAclAssociation(
                        'PrivateSubnetNetworkAclAssociation{}'.format(index),
                        SubnetId=Ref(_private_subnet),
                        NetworkAclId=Ref(_private_network_acl)))

        # use route_table to create a VPC S3 endpoint
        self.add_resource(
            ec2.VPCEndpoint('S3VPCEndpoint',
                            RouteTableIds=[Ref(rt) for rt in route_tables],
                            ServiceName='com.amazonaws.{}.s3'.format(
                                self.region),
                            VpcId=Ref(_vpc)))
Ejemplo n.º 18
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"] +
                     "-VPC"),
            ))

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

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

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

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

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

        self.RESTIGWAttachment = self.template.add_resource(
            ec2.VPCGatewayAttachment(
                "RESTIGWAttachment",
                VpcId=Ref(self.vpc),
                InternetGatewayId=Ref(self.RESTIGW),
            ))

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

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

        self.RESTNAT1 = self.template.add_resource(
            ec2.NatGateway(
                "NAT",
                AllocationId=GetAtt(self.RESTEIP1, "AllocationId"),
                SubnetId=Ref(self.RESTPubSubnet1),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-RESTNAT1"),
            ))

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

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

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

        self.RESTNatRoute = self.template.add_resource(
            ec2.Route(
                "RESTNatRoute",
                RouteTableId=Ref(self.RESTPrivRT1),
                DestinationCidrBlock="0.0.0.0/0",
                NatGatewayId=Ref(self.RESTNAT1),
            ))

        self.RESTNat2Route = self.template.add_resource(
            ec2.Route(
                "RESTNatRoute2",
                RouteTableId=Ref(self.RESTPrivRT2),
                DestinationCidrBlock="0.0.0.0/0",
                NatGatewayId=Ref(self.RESTNAT2),
            ))

        self.RESTPrivRT1Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "RESTPrivRT1Association",
                SubnetId=Ref(self.RESTPrivSubnet1),
                RouteTableId=Ref(self.RESTPrivRT1),
            ))

        self.RESTPrivRT2Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "RESTPrivRT2Association",
                SubnetId=Ref(self.RESTPrivSubnet2),
                RouteTableId=Ref(self.RESTPrivRT2),
            ))

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

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

        self.RESTPubRT1IGWattachment = self.template.add_resource(
            ec2.Route(
                "RESTPubRT1IGWAttachment",
                DependsOn=["RESTIGWAttachment"],
                RouteTableId=Ref(self.RESTPubRT1),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=Ref(self.RESTIGW),
            ))

        self.RESTPubRT2IGWattachment = self.template.add_resource(
            ec2.Route(
                "RESTPubRT2IGWAttachment",
                DependsOn=["RESTIGWAttachment"],
                RouteTableId=Ref(self.RESTPubRT2),
                DestinationCidrBlock="0.0.0.0/0",
                GatewayId=Ref(self.RESTIGW),
            ))

        self.RESTPubRT1Association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "RESTPubRT1Associate",
                SubnetId=Ref(self.RESTPubSubnet1),
                RouteTableId=Ref(self.RESTPubRT1),
            ))

        self.RESTPubRT2Asocation = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "RESTPubR2Associate",
                SubnetId=Ref(self.RESTPubSubnet2),
                RouteTableId=Ref(self.RESTPubRT2),
            ))

        self.VPCPeeringBetweenSharedVPCAndClientVPC = self.template.add_resource(
            ec2.VPCPeeringConnection(
                "VPCPeeringBetweenSharedVPCAndClientVPC",
                DependsOn=["RESTPrivRT1", "RESTPrivRT2"],
                VpcId=Ref(self.SharedServicesVpcId),
                PeerVpcId=Ref(self.vpc),
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SSTOCLIENTVPCPEER"),
            ))

        self.PeeringRouteForClientVPCPriv1 = self.template.add_resource(
            ec2.Route(
                "PeeringRouteForClientVPCPriv1",
                DependsOn=["VPCPeeringBetweenSharedVPCAndClientVPC"],
                RouteTableId=Ref(self.RESTPrivRT1),
                DestinationCidrBlock=Ref(self.SharedServicesVpcCidrBlock),
                VpcPeeringConnectionId=Ref(
                    self.VPCPeeringBetweenSharedVPCAndClientVPC),
            ))

        self.PeeringRouteForClientVPCPriv2 = self.template.add_resource(
            ec2.Route(
                "PeeringRouteForClientVPCPriv2",
                DependsOn=["VPCPeeringBetweenSharedVPCAndClientVPC"],
                RouteTableId=Ref(self.RESTPrivRT2),
                DestinationCidrBlock=Ref(self.SharedServicesVpcCidrBlock),
                VpcPeeringConnectionId=Ref(
                    self.VPCPeeringBetweenSharedVPCAndClientVPC),
            ))

        self.PeeringRouteForSharedServicesVPCPriv1 = self.template.add_resource(
            ec2.Route(
                "PeeringRouteForSharedServicesVPCPriv1",
                DependsOn=["VPCPeeringBetweenSharedVPCAndClientVPC"],
                RouteTableId=Ref(self.SharedServicesPrivateRouteTable1),
                DestinationCidrBlock=Ref(self.VpcCidr),
                VpcPeeringConnectionId=Ref(
                    self.VPCPeeringBetweenSharedVPCAndClientVPC),
            ))

        self.PeeringRouteForSharedServicesVPCPriv2 = self.template.add_resource(
            ec2.Route(
                "PeeringRouteForSharedServicesVPCPriv2",
                DependsOn=["VPCPeeringBetweenSharedVPCAndClientVPC"],
                RouteTableId=Ref(self.SharedServicesPrivateRouteTable2),
                DestinationCidrBlock=Ref(self.VpcCidr),
                VpcPeeringConnectionId=Ref(
                    self.VPCPeeringBetweenSharedVPCAndClientVPC),
            ))

        self.EnvironmentArtifactsBucket = self.template.add_resource(
            Bucket(
                "EnvironmentArtifactsBucket",
                BucketName=(
                    self.environment_parameters["ClientEnvironmentKey"] +
                    "-environment-artifacts").lower(),
                AccessControl="BucketOwnerRead",
                VersioningConfiguration=VersioningConfiguration(
                    Status="Enabled", ),
            ))

        self.BootstrapRepositorySSMParameter = self.template.add_resource(
            SSMParameter(
                "BootstrapRepositorySSMParameter",
                Description="The Bootstrap Repository",
                Name=self.environment_parameters["ClientEnvironmentKey"] +
                "-bootstrapRepository",
                Type="String",
                Value=(self.environment_parameters["ClientEnvironmentKey"] +
                       "-environment-artifacts").lower(),
            ))
Ejemplo n.º 19
0
))


#  Internet gateway and NAT instances
igw = t.add_resource(ec2.InternetGateway('InternetGateway',))
t.add_resource(ec2.VPCGatewayAttachment("GWAttachmnent",
                                        VpcId=Ref(stack_vpc),
                                        InternetGatewayId=Ref(igw)))
nat_eip = t.add_resource(ec2.EIP(
    'NatEip',
    Domain="vpc",
))

nat = t.add_resource(ec2.NatGateway(
    'Nat',
    AllocationId=GetAtt(nat_eip, 'AllocationId'),
    SubnetId=Ref(subnet_public),
))


# route tables
rt_public = t.add_resource(ec2.RouteTable(
    "RouteTablePublic",
    VpcId=Ref(stack_vpc),
    Tags=Tags(Name='PublicRoutes')
))

rt_private = t.add_resource(ec2.RouteTable(
    'RouteTablePrivate',
    VpcId=Ref(stack_vpc),
    Tags=Tags(Name='PrivateRoutes')
Ejemplo n.º 20
0
def add_resources(template, environment, purpose, name_region_attribute_map,
                  param_pem_key_name):
    # IP address for Seattle, Palmerston North, and Auckland offices. (Airport codes used as keys.)
    home_network_cidr_dict = dict(
        (('Akl', '121.98.118.142/32'), ('Pmr', '121.99.230.178/32'),
         ('Sea', '67.131.4.94/30')))

    # PostgresSQL database port
    database_port_number = 5432

    # Create the VPC.
    cidr_block_vpc = '10.0.0.0/16'
    name_vpc = 'Vpc%s%s' % (purpose, environment)
    resource_vpc = ec2.VPC(
        name_vpc,
        CidrBlock=cidr_block_vpc,
        EnableDnsHostnames=True,
        Tags=Tags(Name=name_vpc, Purpose=purpose, Environment=environment),
    )
    template.add_resource(resource_vpc)
    template.add_output(
        Output('VPC',
               Description='VPC created for purpose: %s, environment: %s' %
               (purpose, environment),
               Value=Ref(resource_vpc)))
    # Report the CIDR block of the VPC as an output.
    template.add_output(
        Output('VpcCidrBlock',
               Description='CIDR block of VPC',
               Value=cidr_block_vpc))

    # Create the security group for the VPC.
    name_security_group_vpc = 'VpcSecurityGroup%s%s' % (purpose, environment)
    resource_security_group_vpc = ec2.SecurityGroup(
        name_security_group_vpc,
        GroupDescription=Join(' ',
                              ['Security group for VPC',
                               Ref(resource_vpc)]),
        Tags=Tags(Name=name_security_group_vpc,
                  Purpose=purpose,
                  Environment=environment),
        VpcId=Ref(resource_vpc))
    template.add_resource(resource_security_group_vpc)
    template.add_output(
        Output('SecurityGroup',
               Description='Security group created for VPC.',
               Value=Ref(resource_security_group_vpc)))

    # Add security group ingress rules.
    # ICMP from home networks.
    for site in home_network_cidr_dict.keys():
        template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressIcmp%s%s%s' %
                                     (purpose, environment, site),
                                     IpProtocol='icmp',
                                     FromPort='-1',
                                     ToPort='-1',
                                     CidrIp=home_network_cidr_dict[site],
                                     GroupId=Ref(resource_security_group_vpc)))

    # ICMP from within the VPC.
    template.add_resource(
        ec2.SecurityGroupIngress('SecurityGroupIngressVpcIcmp%s%s' %
                                 (purpose, environment),
                                 IpProtocol='icmp',
                                 FromPort='-1',
                                 ToPort='-1',
                                 CidrIp=cidr_block_vpc,
                                 GroupId=Ref(resource_security_group_vpc)))

    # SSH from home networks
    for site in home_network_cidr_dict.keys():
        template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressSsh%s%s%s' %
                                     (purpose, environment, site),
                                     IpProtocol='tcp',
                                     FromPort='22',
                                     ToPort='22',
                                     CidrIp=home_network_cidr_dict[site],
                                     GroupId=Ref(resource_security_group_vpc)))

    # SSH from within the VPC.
    template.add_resource(
        ec2.SecurityGroupIngress('SecurityGroupIngressVpcSsh%s%s' %
                                 (purpose, environment),
                                 IpProtocol='tcp',
                                 FromPort='22',
                                 ToPort='22',
                                 CidrIp=cidr_block_vpc,
                                 GroupId=Ref(resource_security_group_vpc)))

    # For dev environments, restrict http(s) to home networks.
    if environment.lower() == 'dev':
        # HTTP from home networks.
        for site in home_network_cidr_dict.keys():
            template.add_resource((ec2.SecurityGroupIngress(
                'SecurityGroupIngressHttp%s%s%s' %
                (purpose, environment, site),
                IpProtocol='tcp',
                FromPort='80',
                ToPort='80',
                CidrIp=home_network_cidr_dict[site],
                GroupId=Ref(resource_security_group_vpc))))

        # HTTPS from home networks.
        for site in home_network_cidr_dict.keys():
            template.add_resource((ec2.SecurityGroupIngress(
                'SecurityGroupIngressHttps%s%s%s' %
                (purpose, environment, site),
                IpProtocol='tcp',
                FromPort='443',
                ToPort='443',
                CidrIp=home_network_cidr_dict[site],
                GroupId=Ref(resource_security_group_vpc))))

    # For non-dev environments, open HTTP(s) to the internet.
    else:
        # HTTP from anywhere.
        template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressHttp%s%s' %
                                     (purpose, environment),
                                     IpProtocol='tcp',
                                     FromPort='80',
                                     ToPort='80',
                                     CidrIp='0.0.0.0/0',
                                     GroupId=Ref(resource_security_group_vpc)))

        # HTTPS from anywhere.
        template.add_resource(
            ec2.SecurityGroupIngress('SecurityGroupIngressHttps%s%s' %
                                     (purpose, environment),
                                     IpProtocol='tcp',
                                     FromPort='443',
                                     ToPort='443',
                                     CidrIp='0.0.0.0/0',
                                     GroupId=Ref(resource_security_group_vpc)))

    # Add security group egress rules. (TBD)
    template.add_resource(
        ec2.SecurityGroupEgress('SecurityGroupEgress%s%s' %
                                (purpose, environment),
                                IpProtocol='-1',
                                FromPort='-1',
                                ToPort='-1',
                                CidrIp='0.0.0.0/0',
                                GroupId=Ref(resource_security_group_vpc)))

    # Create an internet gateway.
    name_internet_gateway = 'InternetGateway%s%s' % (purpose, environment)
    resource_internet_gateway = ec2.InternetGateway(
        name_internet_gateway,
        Tags=Tags(Name=name_internet_gateway,
                  Purpose=purpose,
                  Environment=environment),
    )
    template.add_resource(resource_internet_gateway)

    # Attach the internet gateway to the VPC.
    name_vpc_internet_gateway_attachment = 'VpcGatewayAttachment%s%s' % (
        purpose, environment)
    resource_internet_gateway_attachment = ec2.VPCGatewayAttachment(
        name_vpc_internet_gateway_attachment,
        VpcId=Ref(resource_vpc),
        InternetGatewayId=Ref(resource_internet_gateway))
    template.add_resource(resource_internet_gateway_attachment)

    # Create a public and private subnet in two availability zones
    # for a total of four subnets.
    # TODO:  Get the subnet CIDR blocks correct, i.e.,
    # appropriately sized to anticipate future growth.
    # What is here now is just a SWAG.
    public_subnet_cidr_dict = dict(A='10.0.0.0/24', B='10.0.1.0/24')
    private_subnet_cidr_dict = dict(A1='10.0.10.0/24', B1='10.0.11.0/24')

    # Create public subnet A.
    name_subnet = 'SubnetPublicA%s%s' % (purpose, environment)
    resource_subnet_public_a = ec2.Subnet(
        name_subnet,
        AvailabilityZone=Select('0', GetAZs('')),
        CidrBlock=public_subnet_cidr_dict['A'],
        Tags=Tags(Name=name_subnet, Purpose=purpose, Environment=environment),
        VpcId=Ref(resource_vpc))
    template.add_resource(resource_subnet_public_a)
    template.add_output(
        Output(name_subnet,
               Description='Public Subnet A',
               Value=Ref(resource_subnet_public_a)))

    # Create public subnet B.
    name_subnet = 'SubnetPublicB%s%s' % (purpose, environment)
    resource_subnet_public_b = ec2.Subnet(
        name_subnet,
        AvailabilityZone=Select('1', GetAZs('')),
        CidrBlock=public_subnet_cidr_dict['B'],
        Tags=Tags(Name=name_subnet, Purpose=purpose, Environment=environment),
        VpcId=Ref(resource_vpc))
    template.add_resource(resource_subnet_public_b)
    template.add_output(
        Output(name_subnet,
               Description='Public subnet B',
               Value=Ref(resource_subnet_public_b)))

    # Create the private subnet A1.
    name_subnet = 'SubnetPrivateA1%s%s' % (purpose, environment)
    resource_subnet_private_a1 = ec2.Subnet(
        name_subnet,
        AvailabilityZone=Select('0', GetAZs('')),
        CidrBlock=private_subnet_cidr_dict['A1'],
        Tags=Tags(Name=name_subnet, Purpose=purpose, Environment=environment),
        VpcId=Ref(resource_vpc))
    template.add_resource(resource_subnet_private_a1)
    template.add_output(
        Output(name_subnet,
               Description='Private subnet A1',
               Value=Ref(resource_subnet_private_a1)))

    # Create the private subnet B1.
    name_subnet = 'SubnetPrivateB1%s%s' % (purpose, environment)
    resource_subnet_private_b1 = ec2.Subnet(
        name_subnet,
        AvailabilityZone=Select('1', GetAZs('')),
        CidrBlock=private_subnet_cidr_dict['B1'],
        Tags=Tags(Name=name_subnet, Purpose=purpose, Environment=environment),
        VpcId=Ref(resource_vpc))
    template.add_resource(resource_subnet_private_b1)
    template.add_output(
        Output(name_subnet,
               Description='Private subnet B1',
               Value=Ref(resource_subnet_private_b1)))

    # Subnets are created at this point.  Create dictionaries for iteration.
    public_subnet_resource_dict = dict(A=resource_subnet_public_a,
                                       B=resource_subnet_public_b)
    private_subnet_resource_dict = dict(A1=resource_subnet_private_a1,
                                        B1=resource_subnet_private_b1)

    # Create an Elastic IP for the NAT gateway.
    name_nat_eip = 'NatEip%s%s' % (purpose, environment)
    resource_nat_eip = ec2.EIP(name_nat_eip, Domain=name_vpc)
    template.add_resource(resource_nat_eip)

    # Create the NAT gateway in public subnet B.
    name_nat_gateway = 'NatGateway%s%s' % (purpose, environment)
    resource_nat_gateway = ec2.NatGateway(
        name_nat_gateway,
        AllocationId=GetAtt(name_nat_eip, 'AllocationId'),
        DependsOn=name_vpc_internet_gateway_attachment,
        SubnetId=Ref(resource_subnet_public_b),
    )
    template.add_resource(resource_nat_gateway)

    # Create the public subnet route table.
    name_route_table = 'RouteTablePublic%s%s' % (purpose, environment)
    resource_route_table_public = ec2.RouteTable(name_route_table,
                                                 Tags=Tags(
                                                     Name=name_route_table,
                                                     Purpose=purpose,
                                                     Environment=environment),
                                                 VpcId=Ref(resource_vpc))
    template.add_resource(resource_route_table_public)

    # Add a route from the public subnets to the internet.
    template.add_resource(
        ec2.Route(
            'RouteToInternetPublicSubnets%s%s' % (purpose, environment),
            DependsOn=name_vpc_internet_gateway_attachment,
            DestinationCidrBlock='0.0.0.0/0',
            GatewayId=Ref(resource_internet_gateway),
            RouteTableId=Ref(resource_route_table_public),
        ))

    # Associate the route table with the AZ-A, AZ-B subnets.
    for subnet in public_subnet_resource_dict.keys():
        template.add_resource(
            ec2.SubnetRouteTableAssociation(
                'RouteTableAssocPublicSubnet%s%s%s' %
                (subnet, purpose, environment),
                RouteTableId=Ref(resource_route_table_public),
                SubnetId=Ref(public_subnet_resource_dict[subnet])))

    # Create the private subnet route table.
    name_route_table = 'RouteTablePrivate%s%s' % (purpose, environment)
    resource_route_table_private = ec2.RouteTable(name_route_table,
                                                  Tags=Tags(
                                                      Name=name_route_table,
                                                      Purpose=purpose,
                                                      Environment=environment),
                                                  VpcId=Ref(resource_vpc))
    template.add_resource(resource_route_table_private)

    # Add route to internet via NAT.
    template.add_resource(
        ec2.Route('RouteToInternetPrivateSubnet%s%s' % (purpose, environment),
                  DependsOn=name_vpc_internet_gateway_attachment,
                  DestinationCidrBlock='0.0.0.0/0',
                  NatGatewayId=Ref(resource_nat_gateway),
                  RouteTableId=Ref(resource_route_table_private)))

    # Associate the route table with the AZ-A1, AZ-B1 subnets.
    for subnet in private_subnet_resource_dict.keys():
        template.add_resource(
            ec2.SubnetRouteTableAssociation(
                'RouteTableAssocPrivateSubnet%s%s%s' %
                (subnet, purpose, environment),
                RouteTableId=Ref(resource_route_table_private),
                SubnetId=Ref(private_subnet_resource_dict[subnet])))

    # Create the bastion host.
    name_bastion_host = 'BastionHost%s%s' % (purpose, environment)
    resource_bastion_host = ec2.Instance(
        name_bastion_host,
        DependsOn=name_vpc_internet_gateway_attachment,
        ImageId=FindInMap(name_region_attribute_map, Ref('AWS::Region'),
                          'BastionHostAmi'),
        InstanceType='t2.micro',
        KeyName=Ref(param_pem_key_name),
        NetworkInterfaces=[
            ec2.NetworkInterfaceProperty(
                AssociatePublicIpAddress=str(True),
                DeleteOnTermination=str(True),
                Description='Bastion host network interface for %s%s' %
                (purpose, environment),
                DeviceIndex=str(0),
                GroupSet=[Ref(resource_security_group_vpc)],
                SubnetId=Ref(resource_subnet_public_a),
            )
        ],
        Tags=Tags(Name=name_bastion_host,
                  Purpose=purpose,
                  Environment=environment),
        UserData=Base64('80'))
    template.add_resource(resource_bastion_host)
    template.add_output(
        Output(name_bastion_host,
               Description='Bastion Host Public IP address',
               Value=GetAtt(resource_bastion_host, 'PublicIp')))
Ejemplo n.º 21
0
def dump_base_yaml(cfn_file):

    template = Template()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    first_network_acl = template.add_resource(
        ec2.NetworkAcl(
            "MyFirstNetAcl",
            Tags=resource_tags,
            VpcId=Ref(vpc),
        ))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry(
            "MyPrivOutNetAclEntry",
            NetworkAclId=Ref(first_network_acl),
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            Egress=True,
            RuleAction="allow",
            RuleNumber=100,
        ))

    network_inbound_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyInNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="74.77.86.69/32",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=100,
                            PortRange=ec2.PortRange(From=22, To=22)))

    private_to_public_client_ports_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubClientPortsNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="10.10.1.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=101,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_internet_client_ports_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPub2DefaultClientPortsNetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="0.0.0.0/0",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=102,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_private_icmpv4_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPubIcmpv4NetAclEntry",
                            NetworkAclId=Ref(first_network_acl),
                            CidrBlock="10.10.1.0/24",
                            Protocol=1,
                            Icmp=ec2.ICMP(Code=-1, Type=-1),
                            RuleAction="allow",
                            RuleNumber=103))

    second_network_acl = template.add_resource(
        ec2.NetworkAcl(
            "MySecondNetAcl",
            Tags=resource_tags,
            VpcId=Ref(vpc),
        ))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPriv2InternetClientPortsNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="0.0.0.0/0",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=100,
                            PortRange=ec2.PortRange(From=1024, To=65535)))

    public_to_private_ssh_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivSshNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=101,
                            PortRange=ec2.PortRange(From=22, To=22)))

    public_to_private_http_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivHttpNetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=6,
                            RuleAction="allow",
                            RuleNumber=102,
                            PortRange=ec2.PortRange(From=80, To=80)))

    private_to_public_icmpv4_acl_entry = template.add_resource(
        ec2.NetworkAclEntry("MyPrivIcmpv4NetAclEntry",
                            NetworkAclId=Ref(second_network_acl),
                            CidrBlock="10.10.0.0/24",
                            Protocol=1,
                            Icmp=ec2.ICMP(Code=-1, Type=-1),
                            RuleAction="allow",
                            RuleNumber=103))

    network_out_second_acl_entry = template.add_resource(
        ec2.NetworkAclEntry(
            "MyPubOutNetAclEntry",
            NetworkAclId=Ref(second_network_acl),
            CidrBlock="0.0.0.0/0",
            Protocol=-1,
            Egress=True,
            RuleAction="allow",
            RuleNumber=100,
        ))

    subnet_nacl_asociation = template.add_resource(
        ec2.SubnetNetworkAclAssociation("subNaclAsoc",
                                        NetworkAclId=Ref(first_network_acl),
                                        SubnetId=Ref(subnet)))

    priv_subnet_nacl_asociation = template.add_resource(
        ec2.SubnetNetworkAclAssociation("privSubNaclAsoc",
                                        NetworkAclId=Ref(second_network_acl),
                                        SubnetId=Ref(priv_subnet)))

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
        Output(
            "PrivSubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(priv_subnet),
            Export=Export("PrivSubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
))
private_route_association_2 = t.add_resource(ec2.SubnetRouteTableAssociation(
    'PrivateSubnet2RouteTableAssociation',
    SubnetId=Ref(private_net_2),
    RouteTableId=Ref(private_route_table_2),
))

# Nat Gateway EIP 1
nat_eip = t.add_resource(ec2.EIP(
    'NatGateway1EIP',
    Domain="vpc",
))

nat = t.add_resource(ec2.NatGateway(
    'NatGateway',
    AllocationId=GetAtt(nat_eip, 'AllocationId'),
    SubnetId=Ref(public_net_1),
))

t.add_resource(ec2.Route(
    'NatRoute',
    RouteTableId=Ref(private_route_table),
    DestinationCidrBlock='0.0.0.0/0',
    NatGatewayId=Ref(nat),
))

# Nat Gateway 2
nat_eip_2 = t.add_resource(ec2.EIP(
    'NatGateway2EIP',
    Domain="vpc",
))
Ejemplo n.º 23
0
    def add_resources(self):
        """ Add All Cloudformation Resources. This will include vpc, igw, and any other network
        resources """
        self.vpc = self.template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock=Ref(self.VpcCidr),
                EnableDnsSupport=True,
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-VPC"),
            ))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.PubRT2Asocation = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubR2Associate",
                SubnetId=Ref(self.PubSubnet2),
                RouteTableId=Ref(self.PubRT2),
            ))
Ejemplo n.º 24
0
        AvailabilityZone=Ref("AvailabilityZone1"),
        CidrBlock=Ref("CIDRPrivateSubnet1A"),
        Tags=Tags(IoCluster=Ref("AWS::StackName"),
                  Name=Join("-", [Ref("AWS::StackName"), "PrivateSubnet1A"]))),

    # Create NAT Elastic IP
    "NAT1EIP":
    ec2.EIP("NAT1EIP",
            Condition="NAT1EIPCondition",
            DependsOn="IGWAttachVPC",
            Domain="vpc"),
    # Create NAt Gateway
    "NATGateway1":
    ec2.NatGateway("NATGateway1",
                   Condition="NAT1EIPCondition",
                   DependsOn="IGWAttachVPC",
                   SubnetId=Ref("PublicSubnet1"),
                   AllocationId=GetAtt("NAT1EIP", "AllocationId")),
    # Private Subnet 1A route Table
    "PrivateSubnet1ARouteTable":
    ec2.RouteTable(
        "PrivateSubnet1ARouteTable",
        Condition="CreatePrivateSubnet1ACondition",
        VpcId=Ref("VPC"),
        Tags=Tags(
            IoCluster=Ref("AWS::StackName"),
            Name=Join("-",
                      [Ref("AWS::StackName"), "PrivateSubnet1ARouteTable"]))),
    # Create route in PrivateSubnet1A Route Table
    "PrivateSubnet1ARoute":
    ec2.Route("PrivateSubnet1ARoute",
Ejemplo n.º 25
0
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",
))

nat = t.add_resource(
    ec2.NatGateway(
        'Nat',
        AllocationId=GetAtt(nat_eip, 'AllocationId'),
        SubnetId=Ref(public_net),
    ))

t.add_resource(
    ec2.Route(
        'NatRoute',
        RouteTableId=Ref(private_route_table),
        DestinationCidrBlock='0.0.0.0/0',
        NatGatewayId=Ref(nat),
    ))

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

t.add_output(
    Output(
Ejemplo n.º 26
0
    def add_resources(self):
        self.vpc = self.template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock=Ref(self.VpcCidr),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-VPC"),
            ))

        self.public_subneta = self.template.add_resource(
            ec2.Subnet(
                "PublicSubnet",
                CidrBlock=Ref(self.PublicSubnetA),
                VpcId=Ref(self.vpc),
                AvailabilityZone=Ref(self.AvailabilityZoneA),
                MapPublicIpOnLaunch=True,
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PUBSUBA"),
            ))

        self.private_subneta = self.template.add_resource(
            ec2.Subnet(
                "PrivateSubnet",
                CidrBlock=Ref(self.PrivateSubnetA),
                VpcId=Ref(self.vpc),
                AvailabilityZone=Ref(self.AvailabilityZoneA),
                MapPublicIpOnLaunch=True,
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PRIVSUBA"),
            ))

        self.public_subnetb = self.template.add_resource(
            ec2.Subnet(
                "PublicSubnet2",
                CidrBlock=Ref(self.PublicSubnetB),
                VpcId=Ref(self.vpc),
                AvailabilityZone=Ref(self.AvailabilityZoneB),
                MapPublicIpOnLaunch=True,
                Tags=self.default_tags +
                Tags(name=self.environment_name + "-PUBSUBB"),
            ))

        self.private_subnetb = self.template.add_resource(
            ec2.Subnet(
                "PrivateSubnet2",
                CidrBlock=Ref(self.PrivateSubnetB),
                VpcId=Ref(self.vpc),
                AvailabilityZone=Ref(self.AvailabilityZoneB),
                MapPublicIpOnLaunch=True,
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PRIVSUBB"),
            ))

        self.private_route_table = self.template.add_resource(
            ec2.RouteTable(
                "PrivateRouteTable",
                VpcId=Ref(self.vpc),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PRIVRTBL"),
            ))

        self.public_route_table = self.template.add_resource(
            ec2.RouteTable(
                "PublicRouteTable",
                VpcId=Ref(self.vpc),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PUBRTBL"),
            ))

        self.igw = self.template.add_resource(
            ec2.InternetGateway(
                "InternetGateway",
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-IGW"),
            ))

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

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

        self.nat = self.template.add_resource(
            ec2.NatGateway(
                "Nat",
                AllocationId=GetAtt(self.nat_eip, 'AllocationId'),
                SubnetId=Ref(self.public_subneta),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-NAT"),
            ))

        self.nat_route = self.template.add_resource(
            ec2.Route(
                "PublicRoute",
                RouteTableId=Ref(self.private_route_table),
                DestinationCidrBlock='0.0.0.0/0',
                NatGatewayId=Ref(self.nat),
            ))

        self.igw_route = self.template.add_resource(
            ec2.Route(
                "InternetGatewayRoute",
                RouteTableId=Ref(self.public_route_table),
                DestinationCidrBlock='0.0.0.0/0',
                GatewayId=Ref(self.igw),
            ))

        self.private_subnet_association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PriSubnetAssociation",
                SubnetId=Ref(self.private_subneta),
                RouteTableId=Ref(self.private_route_table),
            ))

        self.public_subnet_association = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubSubnetAssociation",
                SubnetId=Ref(self.public_subneta),
                RouteTableId=Ref(self.public_route_table),
            ))
        """Start Block for Second group of Subnets"""

        self.private_route_tableb = self.template.add_resource(
            ec2.RouteTable(
                "PrivateRouteTableB",
                VpcId=Ref(self.vpc),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PRIVRTBLB"),
            ))

        self.public_route_tableb = self.template.add_resource(
            ec2.RouteTable(
                "PublicRouteTableB",
                VpcId=Ref(self.vpc),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-PUBRTBLB"),
            ))

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

        self.natb = self.template.add_resource(
            ec2.NatGateway(
                "NatB",
                AllocationId=GetAtt(self.nat_eipb, 'AllocationId'),
                SubnetId=Ref(self.public_subnetb),
                Tags=self.default_tags +
                Tags(Name=self.environment_name + "-NATB"),
            ))

        self.nat_routeb = self.template.add_resource(
            ec2.Route(
                "PublicRouteB",
                RouteTableId=Ref(self.private_route_tableb),
                DestinationCidrBlock='0.0.0.0/0',
                NatGatewayId=Ref(self.natb),
            ))

        self.private_subnet_associationb = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PriSubnetAssociationB",
                SubnetId=Ref(self.private_subnetb),
                RouteTableId=Ref(self.private_route_tableb),
            ))

        self.public_subnet_associationb = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubSubnetAssociationB",
                SubnetId=Ref(self.public_subnetb),
                RouteTableId=Ref(self.public_route_tableb),
            ))