Exemple #1
0
    def define_subnet_network_acl(self, subnet, acl):
        name = "%s%s" % (subnet, acl.name)
        a = ec2.SubnetNetworkAclAssociation(
            name, DeletionPolicy=self.deletion_policy)
        a.SubnetId = Ref(subnet)
        a.NetworkAclId = Ref(acl)

        self._add_resource(a)
Exemple #2
0
    def gen_public_subnet_az(self, az_index, cidr_block):
        name = f"PublicSubnet{az_index}"
        subnet = ec2.Subnet(
            name,
            VpcId=Ref(self.vpc),
            CidrBlock=cidr_block,
            AvailabilityZone=Select(str(az_index), GetAZs(Ref("AWS::Region"))),
        )
        self.template.add_resource(subnet)
        self.export_value(Ref(subnet), name)

        route_table_association = ec2.SubnetRouteTableAssociation(
            f"{name}RouteTableAssociation",
            SubnetId=Ref(subnet),
            RouteTableId=Ref(self.public_route_table),
        )
        self.template.add_resource(route_table_association)

        network_acl_association = ec2.SubnetNetworkAclAssociation(
            f"{name}NetworkAclAssociation",
            SubnetId=Ref(subnet),
            NetworkAclId=Ref(self.network_acl),
        )
        self.template.add_resource(network_acl_association)
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)
Exemple #4
0
def configure_vpc(config, template):
    stack = config['stack']
    region = config['region']
    public_subnets = []
    private_subnets = []

    vpcs_file = read_yaml_file('configuration/vpcs.yaml')
    vpcs = vpcs_file['vpcs']
    connections = vpcs_file['connections']
    eips = read_yaml_file('configuration/eips.yaml')

    if stack not in vpcs:
        sys.stderr.write('%s: not found in vpcs\n' % stack)
        sys.exit(1)

    if stack not in eips:
        sys.stderr.write('%s: not found in eips; execute "bin/manage-eips"\n' %
                         stack)
        sys.exit(1)

    vpc = template.add_resource(
        ec2.VPC(
            'VPC',
            CidrBlock=vpcs[stack]['cidr'],
            InstanceTenancy='default',
            Tags=Tags(Name=config['description'], ),
        ))

    internet_gateway = template.add_resource(
        ec2.InternetGateway(
            'InternetGateway',
            Tags=Tags(Name=config['description'], ),
        ))

    internet_gateway_attachment = template.add_resource(
        ec2.VPCGatewayAttachment(
            'InternetGatewayAttachment',
            VpcId=Ref(vpc),
            InternetGatewayId=Ref(internet_gateway),
            # DeletionPolicy='Retain',
        ))

    public_route_table = template.add_resource(
        ec2.RouteTable(
            'PublicRouteTable',
            VpcId=Ref(vpc),
            Tags=Tags(Name='%s - Public Routing Table' % stack, ),
        ))

    private_route_table = template.add_resource(
        ec2.RouteTable(
            'PrivateRouteTable',
            VpcId=Ref(vpc),
            Tags=Tags(Name='%s - Private Routing Table' % stack, ),
        ))

    # default public subnet route is through the Internet Gateway
    default_public_route = template.add_resource(
        ec2.Route(
            'DefaultPublicRoute',
            GatewayId=Ref(internet_gateway),
            DestinationCidrBlock='0.0.0.0/0',
            RouteTableId=Ref(public_route_table),
            DependsOn=Name(internet_gateway_attachment),
        ))

    network_acl = template.add_resource(
        ec2.NetworkAcl(
            'NetworkAcl',
            VpcId=Ref(vpc),
            Tags=Tags(Name=config['description'], ),
        ))

    # It's standard practice to leave Network ACL's completely permissive
    # (not to be confused with SecurityGroups)
    template.add_resource(
        ec2.NetworkAclEntry(
            'NetworkAclEntryIngressFromVpc',
            Protocol='-1',
            RuleNumber='100',
            CidrBlock='0.0.0.0/0',
            Egress=False,
            RuleAction='allow',
            NetworkAclId=Ref(network_acl),
        ))

    template.add_resource(
        ec2.NetworkAclEntry(
            'NetworkAclEntryEgress',
            Protocol='-1',
            RuleNumber='100',
            CidrBlock='0.0.0.0/0',
            Egress=True,
            RuleAction='allow',
            NetworkAclId=Ref(network_acl),
        ))

    for subnet_config in config['subnets']:
        if subnet_config['public']:
            subnet_list = public_subnets
            subnet_route_table = public_route_table
            label = 'PublicSubnet'
        else:
            subnet_list = private_subnets
            subnet_route_table = private_route_table
            label = 'PrivateSubnet'

        label += subnet_config['zone'].upper()

        subnet = template.add_resource(
            ec2.Subnet(
                label,
                VpcId=Ref(vpc),
                AvailabilityZone=region + subnet_config['zone'],
                CidrBlock=subnet_config['cidr'],
                Tags=Tags(
                    Name='%s %s' % (config['description'], label),
                    IsPublic=subnet_config['public'],
                ),
            ))

        subnet_list.append({
            'label': label,
            'object': subnet,
            'config': subnet_config,
        })

        template.add_resource(
            ec2.SubnetRouteTableAssociation(
                'SubnetRouteTableAssociation%s' % label,
                SubnetId=Ref(subnet),
                RouteTableId=Ref(subnet_route_table),
            ))

        template.add_resource(
            ec2.SubnetNetworkAclAssociation(
                'SubnetAclAssociation%s' % label,
                SubnetId=Ref(subnet),
                NetworkAclId=Ref(network_acl),
            ))

    if 'create_s3_endpoint' in config and config['create_s3_endpoint']:
        s3_endpoint = template.add_resource(
            ec2.VPCEndpoint(
                'S3Endpoint',
                RouteTableIds=[Ref(private_route_table)],
                PolicyDocument={
                    'Version':
                    '2012-10-17',
                    'Statement': [{
                        'Action': '*',
                        'Effect': 'Allow',
                        'Resource': '*',
                        'Principal': '*'
                    }]
                },
                VpcId=Ref(vpc),
                ServiceName='com.amazonaws.' + region + '.s3',
            ))
Exemple #5
0
                        CidrBlock=GetAtt(hyp3_vpc, "CidrBlock"),
                        Protocol=-1,
                        RuleAction="allow",
                        RuleNumber=200,
                        Egress=False))

local_acl_entry = t.add_resource(
    ec2.NetworkAclEntry('LocalAclEntry',
                        NetworkAclId=Ref(local_network_acl),
                        CidrBlock=Ref(local_cidr_range),
                        Protocol=-1,
                        RuleAction="allow",
                        RuleNumber=100,
                        Egress=False))

all_traffic_out_entry = t.add_resource(
    ec2.NetworkAclEntry('OutputBoundTrafficEntry',
                        NetworkAclId=Ref(local_network_acl),
                        CidrBlock='0.0.0.0/0',
                        Protocol=-1,
                        RuleAction="allow",
                        RuleNumber=100,
                        Egress=True))

restricted_subnet_acl_association = t.add_resource(
    ec2.SubnetNetworkAclAssociation("RestrictedSubnetAclAssociation",
                                    SubnetId=Ref(restricted_subnet),
                                    NetworkAclId=Ref(local_network_acl)))

t.add_output(Output('VPCId', Value=Ref(hyp3_vpc), Description='VPC Id'))
Exemple #6
0
def multiaz_subnets(
    name_prefix: str,
    cidr_block: str,
    region: str,
    vpc: object = None,
    vpc_id: str = None,
    no_of_subnets: int = 4,
    network_acl: object = None,
    network_acl_id: str = None,
    route_table: object = None,
    route_table_id: str = None,
) -> list:
    """Split given CIDR block into subnets over multiple AZs

    Either `vpc` or both `vpc_id` and `region`  are required.

    If a network ACL or route table are passed as parameters, they
    will be associated with the subnets.

    `vpc`, `network_acl` and `route_table` are expected to be
    Troposphere resource objects which can be passed to Ref and GetAtt
    functions. As an alternative, `vpc_id`, `region`, `network_acl_id`
    `route_table_id` can be passed directly. If both resource and *_id
    are specified, the *_id will take precedence.

    Returns a list of Troposphere resources that describes the subnets
    and can be attached to a Template object.

    Returned subnet objects have the following keys set in their
    Metadata attribute:
        az: full availability zone name ("eu-west-1a")
        az_index: uppercase AZ, without the region part ("A")
        suffix: the suffix that was added to the name to form a unique
            resource title. Probably a single digit.

    Args:
        name_prefix (str): Prefix each resource with this string. Use to
            assure unique name for the resource in the calling Template
        cidr_block (str): IP range to split into subnets
        region (str): AWS region
        vpc (object, optional): VPC Troposphere resource. One of vpc or
            vpc_id is required. Defaults to None.
        vpc_id (str, optional): VPC ID. One of vpc or vpc_id is
            required. Defaults to None.
        no_of_subnets (int, optional): Create this many subnets. must
            be a power of 2. Defaults to 4.
        network_acl (object, optional): Network ACL Troposphere
            resource. Defaults to None.
        network_acl_id (str, optional): Network ACL ID. Defaults to
            None.
        route_table (object, optional): Route table resource.
            Defaults to None.
        route_table_id (str, optional): Route table ID. Defaults to
            None.

    Raises:
        ValueError: If neither vpc nor vpc_id were specified.

    Returns:
        list: Troposphere resources to be added to Template.

    """
    if vpc is None and vpc_id is None:
        raise ValueError("One of vpc or vpc_id must be specified")
    if vpc_id is None:
        vpc_id = Ref(vpc)
    # Resource names only accept alphanumeric
    prefix = alphanum(name_prefix).lower().capitalize()
    net_split = split_net_across_zones(cidr_block, region, no_of_subnets)
    resources = list()
    for index, net_segment in enumerate(net_split):
        # set subnet
        az_index = net_segment["az"][-1:].upper()
        subnet = t_ec2.Subnet(
            title=f"{prefix}{index+1}",
            AvailabilityZone=net_segment["az"],
            CidrBlock=net_segment["cidr"],
            VpcId=vpc_id,
            Tags=[{
                "Key": "Name",
                "Value": f"{name_prefix} {az_index}"
            }],
        )
        subnet.Metadata = {}
        subnet.Metadata["az"] = net_segment["az"].lower()
        subnet.Metadata["az_index"] = az_index
        subnet.Metadata["suffix"] = index + 1
        resources.append(subnet)
        # associate network ACL with subnet
        if network_acl_id is None and network_acl is not None:
            network_acl_id = Ref(network_acl)
        if network_acl_id is not None:
            resources.append(
                t_ec2.SubnetNetworkAclAssociation(
                    title=f"{subnet.title}NaclAssociation",
                    SubnetId=Ref(subnet),
                    NetworkAclId=network_acl_id,
                ))
        if route_table_id is None and route_table is not None:
            route_table_id = Ref(route_table)
        if route_table_id is not None:
            resources.append(
                t_ec2.SubnetRouteTableAssociation(
                    title=f"{subnet.title}RouteAssociation",
                    SubnetId=Ref(subnet),
                    RouteTableId=route_table_id,
                ))
    return resources
Exemple #7
0
def west_vpc_stack(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",
        ))

    east_peer_cidr_param = template.add_parameter(
        Parameter(
            "eastPeerCidrParam",
            Type="String",
        ))

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

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

    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)))

    # stage 3: delete me and update to remove peering stack
    # peer_route=template.add_resource(
    #     ec2.Route(
    #         "peerRoute",
    #         DestinationCidrBlock=Ref(east_peer_cidr_param),
    #         VpcPeeringConnectionId="pcx-0d27f0252e6c8ac93",
    #         RouteTableId=Ref(route_tbl)
    #     )
    # )

    # /stage3

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

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

    template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock=Ref(east_peer_cidr_param),
                            Protocol=-1,
                            RuleAction="allow",
                            RuleNumber=101))

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

    # # stage 4: vpc endpoint connection
    #     s3_bucket=template.add_resource(
    #         s3.Bucket(
    #             "MyBucketForServiceConnection",
    #             BucketName="bucket-for-service-connection-lab-4-2-3-jdix"
    #         )
    #     )

    #     vpc_endpoint=template.add_resource(
    #         ec2.VPCEndpoint(
    #             "MyVpcS3Endpoint",
    #             VpcId=Ref(vpc),
    #             ServiceName="com.amazonaws.us-west-2.s3",
    #             RouteTableIds=[Ref(route_tbl)],
    #             PolicyDocument={
    #                 "Statement": [
    #                     {
    #                         "Principal": "*",
    #                         "Action": "*",
    #                         "Effect": "Allow",
    #                         "Resource": [
    #                             Join("", ["arn:aws:s3:::", Ref(s3_bucket)]),
    #                             Join("", ["arn:aws:s3:::", Ref(s3_bucket), '/*'])
    #                         ],
    #                     }
    #                 ]
    #             }
    #         )
    #     )

    # endpoint acls
    # template.add_resource(
    #     ec2.NetworkAclEntry(
    #         "MyS3ClientPortsNetAclEntry1",
    #         NetworkAclId=Ref(my_net_acl),
    #         CidrBlock="3.5.76.0/22",
    #         Protocol=6,
    #         RuleAction="allow",
    #         RuleNumber=102,
    #         PortRange=ec2.PortRange(From=1024, To=65535)
    #     )
    # )
    # template.add_resource(
    #     ec2.NetworkAclEntry(
    #         "MyS3ClientPortsNetAclEntry2",
    #         NetworkAclId=Ref(my_net_acl),
    #         CidrBlock="3.5.80.0/21",
    #         Protocol=6,
    #         RuleAction="allow",
    #         RuleNumber=103,
    #         PortRange=ec2.PortRange(From=1024, To=65535)
    #     )
    # )
    # template.add_resource(
    #     ec2.NetworkAclEntry(
    #         "MyS3ClientPortsNetAclEntry3",
    #         NetworkAclId=Ref(my_net_acl),
    #         CidrBlock="52.218.128.0/17",
    #         Protocol=6,
    #         RuleAction="allow",
    #         RuleNumber=104,
    #         PortRange=ec2.PortRange(From=1024, To=65535)
    #     )
    # )
    # template.add_resource(
    #     ec2.NetworkAclEntry(
    #         "MyS3ClientPortsNetAclEntry4",
    #         NetworkAclId=Ref(my_net_acl),
    #         CidrBlock="52.92.128.0/17",
    #         Protocol=6,
    #         RuleAction="allow",
    #         RuleNumber=105,
    #         PortRange=ec2.PortRange(From=1024, To=65535)
    #     )
    # )

    # bucket policy
    # template.add_resource(
    #     s3.BucketPolicy(
    #         "bucketPolicyForVpcEndpoint",
    #         Bucket=Ref(s3_bucket),
    #         PolicyDocument={
    #             "Version": "2012-10-17",
    #             "Statement": [
    #                 {
    #                     "Action": "*",
    #                     "Principal": "*",
    #                     "Resource": [
    #                         Join("", ["arn:aws:s3:::", Ref(s3_bucket)]),
    #                         Join("", ["arn:aws:s3:::", Ref(s3_bucket), '/*'])
    #                     ],
    #                     "Effect": "Allow",
    #                     "Condition": {
    #                         "StringEquals": {
    #                             "aws:SourceVpce": Ref(vpc_endpoint)
    #                         },
    #                         "StringEquals": {
    #                             "aws:SourceVpc": Ref(vpc)
    #                         }
    #                     }
    #                 }
    #             ]
    #         }
    #     )
    # )

    # endpoint policy

    # /stage4

    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"),
        ),
    ])
    template_out_yaml(cfn_file, template)
Exemple #8
0
def east_vpc_stack(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",
        ))

    west_peer_cidr_param = template.add_parameter(
        Parameter(
            "westPeerCidrParam",
            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)))

    # stage 3: delete me and update to remove peering stack
    # peer_route=template.add_resource(
    #     ec2.Route(
    #         "peerRoute",
    #         DestinationCidrBlock=Ref(west_peer_cidr_param),
    #         VpcPeeringConnectionId="pcx-0d27f0252e6c8ac93",
    #         RouteTableId=Ref(route_tbl)
    #     )
    # )
    # /stage3

    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)))

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

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

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

    template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock=Ref(west_peer_cidr_param),
                            Protocol=-1,
                            RuleAction="allow",
                            RuleNumber=101))

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

    template.add_resource(
        ec2.SubnetNetworkAclAssociation("subNaclAsoc",
                                        NetworkAclId=Ref(my_net_acl),
                                        SubnetId=Ref(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"),
        ),
    ])
    template_out_yaml(cfn_file, template)
                        Protocol='-1',
                        RuleAction='allow',
                        RuleNumber='100'))

public_subnet_acl_outbound = t.add_resource(
    ec2.NetworkAclEntry('PublicSubnetACLEgress',
                        CidrBlock='0.0.0.0/0',
                        Egress='true',
                        NetworkAclId=Ref(public_subnet_acl),
                        Protocol='-1',
                        RuleAction='allow',
                        RuleNumber='100'))

public_subnet_1_acl_association = t.add_resource(
    ec2.SubnetNetworkAclAssociation('PublicSubnet1ACLAssociation',
                                    SubnetId=Ref(public_subnet_1),
                                    NetworkAclId=Ref(public_subnet_acl)))

public_subnet_2_acl_association = t.add_resource(
    ec2.SubnetNetworkAclAssociation('PublicSubnet2ACLAssociation',
                                    SubnetId=Ref(public_subnet_2),
                                    NetworkAclId=Ref(public_subnet_acl)))

public_subnet_3_acl_association = t.add_resource(
    ec2.SubnetNetworkAclAssociation('PublicSubnet3ACLAssociation',
                                    Condition='3AZCondition',
                                    SubnetId=Ref(public_subnet_3),
                                    NetworkAclId=Ref(public_subnet_acl)))

public_subnet_4_acl_association = t.add_resource(
    ec2.SubnetNetworkAclAssociation('PublicSubnet4ACLAssociation',
Exemple #10
0
    # Create Inbound rules for NACL connected to Private Subnet 1B
    "PrivateSubnet1BNetworkAclEntryInbound":
    ec2.NetworkAclEntry("PrivateSubnet1BNetworkAclEntryInbound",
                        Condition="CreatePrivateSubnet1BCondition",
                        CidrBlock="10.0.0.0/16",
                        Egress="true",
                        NetworkAclId=Ref("PrivateSubnet1BNetworkAcl"),
                        Protocol="-1",
                        RuleAction="allow",
                        RuleNumber="100"),

    # Associate the created NACL with the Private Subnet 1B
    "PrivateSubnet1BNetworkAclAssociation":
    ec2.SubnetNetworkAclAssociation(
        "PrivateSubnet1BNetworkAclAssociation",
        Condition="CreatePrivateSubnet1BCondition",
        SubnetId=Ref("PrivateSubnet1B"),
        NetworkAclId=Ref("PrivateSubnet1BNetworkAcl")),

    #Create Public Subnet 2 in AZ2
    "PublicSubnet2":
    ec2.Subnet("PublicSubnet2",
               Condition="CreatePublicSubnet2Condition",
               CidrBlock=Ref("CIDRPublicSubnet2"),
               VpcId=Ref("VPC"),
               AvailabilityZone=Ref("AvailabilityZone2"),
               MapPublicIpOnLaunch="True",
               Tags=Tags(IoCluster=Ref("AWS::StackName"),
                         Name=Join("-",
                                   [Ref("AWS::StackName"), "PublicSubnet2"]))),
Exemple #11
0
        vpc,
        '10.0.%s.0/24' % index,
        Join('', [Ref('AWS::Region'),
                  Select(index, Ref(availability_zones))]),
    )

    # Public Subnet Associations
    t.add_resource(
        ec2.SubnetRouteTableAssociation('%sPublicRouteTableAssociation' %
                                        public_subnet.title,
                                        SubnetId=Ref(public_subnet),
                                        RouteTableId=Ref(public_route_table)))

    t.add_resource(
        ec2.SubnetNetworkAclAssociation('%sPublicSubnetNetworkAclAssociation' %
                                        public_subnet.title,
                                        SubnetId=Ref(public_subnet),
                                        NetworkAclId=Ref(public_network_acl)))

    # NAT Device(s) are placed in the public subnet(s)
    name = 'NATDevice%s' % (index + 1)
    nat_device = t.add_resource(
        ec2.Instance(name,
                     InstanceType=Ref(nat_instance_type_param),
                     KeyName=Ref(keyname_param),
                     SourceDestCheck=False,
                     ImageId=FindInMap('AWSNATAMI', Ref('AWS::Region'), 'AMI'),
                     NetworkInterfaces=[
                         ec2.NetworkInterfaceProperty(
                             Description='ENI for NAT device',
                             GroupSet=[Ref(nat_security_group)],
                             SubnetId=Ref(public_subnet),
Exemple #12
0
            CidrIp='0.0.0.0/0')
    ],
    VpcId=Ref(stack_vpc),
    Tags=Tags(Name='PublicSecurityGroup')
))

# network acls
public_subnet_acl = t.add_resource(ec2.NetworkAcl(
    'PublicACL',
    VpcId=Ref(stack_vpc),
    Tags=Tags(Name='PublicACL')
))

subnetNetworkAclAssociation = t.add_resource(ec2.SubnetNetworkAclAssociation(
    'SubnetNetworkAclAssociation',
    SubnetId=Ref(subnet_public),
    NetworkAclId=Ref(public_subnet_acl),
))

# outbound acls for Public network
t.add_resource(ec2.NetworkAclEntry(
        'sshOutbound',
        NetworkAclId=Ref(public_subnet_acl),
        RuleNumber='90',
        Protocol='6',
        PortRange=ec2.PortRange(To='22', From='22'),
        Egress='true',
        RuleAction='allow',
        CidrBlock='0.0.0.0/0',
))
t.add_resource(ec2.NetworkAclEntry(
Exemple #13
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)))
def west_vpc_stack(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",
        ))

    east_peer_cidr_param = template.add_parameter(
        Parameter(
            "eastPeerCidrParam",
            Type="String",
        ))

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

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

    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)))

    # delete me and update to remove peering stack
    peer_route = template.add_resource(
        ec2.Route("peerRoute",
                  DestinationCidrBlock=Ref(east_peer_cidr_param),
                  VpcPeeringConnectionId="pcx-0d27f0252e6c8ac93",
                  RouteTableId=Ref(route_tbl)))

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

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

    template.add_resource(
        ec2.NetworkAclEntry("MyPriv2PubNetAclEntry",
                            NetworkAclId=Ref(my_net_acl),
                            CidrBlock=Ref(east_peer_cidr_param),
                            Protocol=-1,
                            RuleAction="allow",
                            RuleNumber=101))

    template.add_resource(
        ec2.SubnetNetworkAclAssociation("subNaclAsoc",
                                        NetworkAclId=Ref(my_net_acl),
                                        SubnetId=Ref(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"),
        ),
    ])
    template_out_yaml(cfn_file, template)
Exemple #15
0
    def sg_subnet_vpc(self, template, provision_refs):
        ref_stack_id = Ref('AWS::StackId')

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        provision_refs.vpc = vpc
        provision_refs.security_group_ec2 = use_sg
        provision_refs.security_group_alb = use_alb_sg
        provision_refs.subnets.append(use_subnet)
        provision_refs.subnets.append(use_subnet2)
Exemple #16
0
                CidrBlock=f"10.0.{i}.0/24",
                MapPublicIpOnLaunch=True,
                VpcId=Ref(vpc),
                Tags=Tags(Name=f"10.0.{i}.0/24-PUBLIC"),
            )
        )

        subnetRouteTable = t.add_resource(
            ec2.SubnetRouteTableAssociation(
                f"Subnet{i}RT", RouteTableId=Ref(routeTable), SubnetId=Ref(subnet)
            )
        )

        subnetNACL = t.add_resource(
            ec2.SubnetNetworkAclAssociation(
                f"Subnet{i}NACL", NetworkAclId=Ref(nacl), SubnetId=Ref(subnet)
            )
        )

    # Private subnets
    for i in range(4, 7):
        privateSubnet = t.add_resource(
            ec2.Subnet(
                f"Subnet{i}",
                AvailabilityZone=Select(i - 4, GetAZs(Ref("AWS::Region"))),
                CidrBlock=f"10.0.{i}.0/24",
                MapPublicIpOnLaunch=False,
                VpcId=Ref(vpc),
                Tags=Tags(Name=f"10.0.{i}.0/24-PRIVATE"),
            )
        )
    def __init__(self):
        super(VPC, self).__init__()

        self.vpc = ec2.VPC(
            "VPC",
            CidrBlock="172.1.0.0/16",
            InstanceTenancy="default",
            EnableDnsSupport=True,
            EnableDnsHostnames=True,
            Tags=Tags(Name=Ref("AWS::StackName")),
        )

        self.internet_gateway = ec2.InternetGateway(
            "InternetGateway",
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-internet-gateway"]), ),
        )

        self.internet_gateway_attachment = ec2.VPCGatewayAttachment(
            "InternetGatewayAttachment",
            InternetGatewayId=Ref(self.internet_gateway),
            VpcId=Ref(self.vpc),
        )

        self.public_route_table = ec2.RouteTable(
            "PublicRouteTable",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join(
                "-", [Ref("AWS::StackName"), "public-route-table"]), ),
        )

        self.private_route_table = ec2.RouteTable(
            "PrivateRouteTable",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join(
                "-", [Ref("AWS::StackName"), "private-route-table"]), ),
        )

        self.vpc_s3_endpoint = ec2.VPCEndpoint(
            "VPCS3Endpoint",
            ServiceName=Join(
                "",
                ["com.amazonaws.", Ref("AWS::Region"), ".s3"]),
            VpcId=Ref(self.vpc),
            RouteTableIds=[
                Ref(self.public_route_table),
                Ref(self.private_route_table)
            ],
        )

        self.route_to_internet = ec2.Route(
            "RouteToInternet",
            DestinationCidrBlock="0.0.0.0/0",
            GatewayId=Ref(self.internet_gateway),
            RouteTableId=Ref(self.public_route_table),
            DependsOn=self.internet_gateway_attachment.title,
        )

        # private subnets

        self.private_subnet_1 = ec2.Subnet(
            "PrivateSubnet1",
            AvailabilityZone=Select(0, GetAZs()),
            CidrBlock="172.1.1.0/24",
            MapPublicIpOnLaunch=False,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-private-subnet-1"]), ),
            VpcId=Ref(self.vpc),
        )

        self.private_subnet_1_route_table_association = ec2.SubnetRouteTableAssociation(
            "PrivateSubnet1RouteTableAssociation",
            RouteTableId=Ref(self.private_route_table),
            SubnetId=Ref(self.private_subnet_1),
        )

        self.private_subnet_2 = ec2.Subnet(
            "PrivateSubnet2",
            AvailabilityZone=Select(1, GetAZs()),
            CidrBlock="172.1.2.0/24",
            MapPublicIpOnLaunch=False,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-private-subnet-2"]), ),
            VpcId=Ref(self.vpc),
        )

        self.private_subnet_2_route_table_association = ec2.SubnetRouteTableAssociation(
            "PrivateSubnet2RouteTableAssociation",
            RouteTableId=Ref(self.private_route_table),
            SubnetId=Ref(self.private_subnet_2),
        )

        self.private_network_aCL = ec2.NetworkAcl(
            "PrivateNetworkACL",
            VpcId=Ref(self.vpc),
            Tags=Tags(Name=Join("",
                                [Ref("AWS::StackName"), "-private-nacl"]), ),
        )

        self.private_subnet_1_network_acl_association = ec2.SubnetNetworkAclAssociation(
            "PrivateSubnet1NetworkAclAssociation",
            SubnetId=Ref(self.private_subnet_1),
            NetworkAclId=Ref(self.private_network_aCL),
        )

        self.private_subnet_2_network_acl_association = ec2.SubnetNetworkAclAssociation(
            "PrivateSubnet2NetworkAclAssociation",
            SubnetId=Ref(self.private_subnet_2),
            NetworkAclId=Ref(self.private_network_aCL),
        )

        self.private_network_acl_entry_in = ec2.NetworkAclEntry(
            "PrivateNetworkAclEntryIn",
            CidrBlock="172.1.0.0/16",
            Egress=False,
            NetworkAclId=Ref(self.private_network_aCL),
            Protocol=-1,
            RuleAction="allow",
            RuleNumber=200,
        )

        self.private_network_acl_entry_out = ec2.NetworkAclEntry(
            "PrivateNetworkAclEntryOut",
            CidrBlock="172.1.0.0/16",
            Egress=True,
            NetworkAclId=Ref(self.private_network_aCL),
            Protocol=-1,
            RuleAction="allow",
            RuleNumber=200,
        )

        # public subnets
        self.public_subnet_1 = ec2.Subnet(
            "PublicSubnet1",
            AvailabilityZone=Select(0, GetAZs()),
            CidrBlock="172.1.128.0/24",
            MapPublicIpOnLaunch=True,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-public-subnet-1"]), ),
            VpcId=Ref(self.vpc),
        )

        self.public_subnet_1_route_table_association = ec2.SubnetRouteTableAssociation(
            "PublicSubnet1RouteTableAssociation",
            RouteTableId=Ref(self.public_route_table),
            SubnetId=Ref(self.public_subnet_1),
        )

        self.public_subnet_2 = ec2.Subnet(
            "PublicSubnet2",
            AvailabilityZone=Select(1, GetAZs()),
            CidrBlock="172.1.129.0/24",
            MapPublicIpOnLaunch=True,
            Tags=Tags(Name=Join(
                "", [Ref("AWS::StackName"), "-public-subnet-2"]), ),
            VpcId=Ref(self.vpc),
        )

        self.public_subnet_2_route_table_association = ec2.SubnetRouteTableAssociation(
            "PublicSubnet2RouteTableAssociation",
            RouteTableId=Ref(self.public_route_table),
            SubnetId=Ref(self.public_subnet_2),
        )
outBoundResponsePortsNetworkAclEntry = t.add_resource(
    ec2.NetworkAclEntry(
        'OutBoundResponsePortsNetworkAclEntry',
        NetworkAclId=Ref(networkAcl),
        RuleNumber='102',
        Protocol='6',
        PortRange=ec2.PortRange(To='65535', From='1024'),
        Egress='true',
        RuleAction='allow',
        CidrBlock=ALLOW_ALL_CIDR,
    ))

subnetNetworkAclAssociation = t.add_resource(
    ec2.SubnetNetworkAclAssociation(
        'SubnetNetworkAclAssociation',
        SubnetId=Ref(subnet),
        NetworkAclId=Ref(networkAcl),
    ))

instanceSecurityGroup = t.add_resource(
    ec2.SecurityGroup(
        'InstanceSecurityGroup',
        GroupDescription='Enable SSH access via port 22',
        SecurityGroupIngress=[
            ec2.SecurityGroupRule(
                IpProtocol='tcp',
                FromPort='22',
                ToPort='22',
                CidrIp=ALLOW_ALL_CIDR),
            ec2.SecurityGroupRule(
                IpProtocol='tcp',