예제 #1
0
    def _create_from_arguments(self, name, number_of_availability_zones):
        # type: (str, int) -> None
        """
        Creates a new Network from the constructor arguments (i.e. not from a
        VPC that already exists).
        :param name: The name of the new network
        :param number_of_availability_zones: The number of AZs to create subnets in
        :return: None
        """
        number_of_availability_zones = number_of_availability_zones or 2
        if number_of_availability_zones < 1 or number_of_availability_zones >= 4:
            raise RunError(
                "Unsupported number of available zones for Network: " +
                str(number_of_availability_zones))

        self.use_private_subnets = self.use_private_subnets or False
        vpc = ec2.Vpc(name,
                      cidr_block="10.10.0.0/16",
                      enable_dns_hostnames=True,
                      enable_dns_support=True,
                      tags={
                          "Name": name,
                      },
                      __opts__=ResourceOptions(parent=self))

        self.vpc_id = vpc.id
        self.security_group_ids = [vpc.default_security_group_id]

        internet_gateway = ec2.InternetGateway(
            name,
            vpc_id=vpc.id,
            tags={
                "Name": name,
            },
            __opts__=ResourceOptions(parent=self))

        public_route_table = ec2.RouteTable(
            name,
            vpc_id=vpc.id,
            routes=[{
                "cidrBlock": "0.0.0.0/0",
                "gatewayId": internet_gateway.id
            }],
            tags={"Name": name},
            __opts__=ResourceOptions(parent=self))

        self.subnet_ids = []
        self.public_subnet_ids = []
        for i in range(number_of_availability_zones):
            route_table, subnet = self._create_subnet(name, public_route_table,
                                                      i)

            # pylint: disable=unused-variable
            route_table_association = ec2.RouteTableAssociation(
                "%s-%d" % (name, i),
                subnet_id=subnet.id,
                route_table_id=route_table.id,
                __opts__=ResourceOptions(parent=self))

            self.subnet_ids.append(subnet.id)
예제 #2
0
def main():
    myvpc = ec2.Vpc("Pulumi VPC",
                    assign_generated_ipv6_cidr_block='False',
                    cidr_block=vpc_cidr,
                    enable_dns_hostnames='True',
                    enable_dns_support='True',
                    tags={"Name": "Pulumi Vpc"})
    pubsubneta = subnet(vpc_network + '.0.0/24', 'a', myvpc, 'True')
    pubsubnetb = subnet(vpc_network + '.1.0/24', 'b', myvpc, 'True')
    pubsubnetc = subnet(vpc_network + '.2.0/24', 'c', myvpc, 'True')

    privsubneta = subnet(vpc_network + '.4.0/24', 'a', myvpc, 'False')
    privsubnetb = subnet(vpc_network + '.5.0/24', 'b', myvpc, 'False')
    privsubnetc = subnet(vpc_network + '.6.0/24', 'c', myvpc, 'False')

    dbsubneta = dbsubnet(vpc_network + '.8.0/24', 'a', myvpc)
    dbsubnetb = dbsubnet(vpc_network + '.9.0/24', 'b', myvpc)
    dbsubnetc = dbsubnet(vpc_network + '.10.0/24', 'c', myvpc)

    igw = ec2.InternetGateway("Pulumi IGW",
                              tags={"Name": "Pulumi IGW"},
                              vpc_id=myvpc)

    publicAcl(myvpc)
    rtpublic = routeTablePub(myvpc, igw)
예제 #3
0
    def __init__(self):

        resource_specs = ParseYAML(resource_type).getSpecs()

        for vpc_name, vpc_conf in resource_specs.items():

            # AWS VPC Dynamic Variables
            resource_name = vpc_name
            resource_cidr = vpc_conf['cidr']
            resource_dns_resolution = vpc_conf['dns-resolution']
            resource_dns_hostnames = vpc_conf['dns-hostnames']

            resource_tags = None
            resource_tags = vpc_conf["tags"] if "tags" in vpc_conf else None

            # Getting list of tags from configuration file
            tags_list = {}
            if resource_tags is not None:
                for each_tag_name, each_tag_value in resource_tags.items():
                    tags_list.update({each_tag_name: each_tag_value})

            # Add mandatory tags
            tags_list.update({"Name": resource_name})
            tags_list.update({
                "Project/Stack":
                pulumi.get_project() + "/" + pulumi.get_stack()
            })
            tags_list.update(resource_mandatory_tags)

            # Create resource
            vpc = net.Vpc(resource_name,
                          cidr_block=resource_cidr,
                          enable_dns_support=resource_dns_resolution,
                          enable_dns_hostnames=resource_dns_hostnames,
                          tags=tags_list)

            # Update resource dictionary
            vpc_ids_dict.update({vpc._name: vpc.id})

            # Export the name of each VPC
            pulumi.export(vpc._name, vpc.id)
예제 #4
0
# Copyright 2016-2020, Pulumi Corporation.  All rights reserved.

import pulumi

from pulumi import Output
from pulumi_aws import applicationloadbalancing, get_availability_zones, ec2

vpc = ec2.Vpc('test',
              cidr_block="10.11.0.0/16",
              enable_dns_hostnames=True,
              enable_dns_support=True)

internet_gateway = ec2.InternetGateway('test', vpc_id=vpc.id)

route_table = ec2.RouteTable('test',
                             vpc_id=vpc.id,
                             routes=[
                                 ec2.RouteTableRouteArgs(
                                     cidr_block="0.0.0.0/0",
                                     gateway_id=internet_gateway.id)
                             ])

zones = Output.from_input(get_availability_zones())
zone_names = zones.apply(lambda zs: zs.names)

subnet0 = ec2.Subnet(
    "test0",
    vpc_id=vpc.id,
    availability_zone=zone_names.apply(lambda names: names[0]),
    cidr_block="10.11.0.0/24",
    map_public_ip_on_launch=True)
예제 #5
0
    def __init__(self,
                 name: str,
                 args: VpcArgs,
                 opts: pulumi.ResourceOptions = None):
        """
        Constructs a Vpc.

        :param name: The Pulumi resource name. Child resource names are constructed based on this.
        :param args: A VpcArgs object containing the arguments for VPC constructin.
        :param opts: A pulumi.ResourceOptions object.
        """
        super().__init__('Vpc', name, None, opts)

        # Make base info available to other methods
        self.name = name
        self.description = args.description
        self.base_tags = args.base_tags

        # Create VPC and Internet Gateway resources
        self.vpc = ec2.Vpc(f"{name}-vpc",
                           cidr_block=args.base_cidr,
                           enable_dns_hostnames=True,
                           enable_dns_support=True,
                           tags={
                               **args.base_tags, "Name":
                               f"{args.description} VPC"
                           },
                           opts=pulumi.ResourceOptions(parent=self, ))

        self.internet_gateway = ec2.InternetGateway(
            f"{name}-igw",
            vpc_id=self.vpc.id,
            tags={
                **args.base_tags, "Name":
                f"{args.description} VPC Internet Gateway"
            },
            opts=pulumi.ResourceOptions(parent=self.vpc, ))

        # Calculate subnet CIDR blocks and create subnets
        subnet_distributor = SubnetDistributor(
            args.base_cidr, len(args.availability_zone_names))

        self.public_subnets = [
            ec2.Subnet(f"{name}-public-subnet-{i}",
                       vpc_id=self.vpc.id,
                       cidr_block=cidr,
                       availability_zone=args.availability_zone_names[i],
                       map_public_ip_on_launch=True,
                       tags={
                           **args.base_tags, "Name":
                           f"${args.description} Public Subnet {i}"
                       },
                       opts=pulumi.ResourceOptions(parent=self.vpc, ))
            for i, cidr in enumerate(subnet_distributor.public_subnets)
        ]

        self.private_subnets = [
            ec2.Subnet(f"{name}-private-subnet-{i}",
                       vpc_id=self.vpc.id,
                       cidr_block=cidr,
                       availability_zone=args.availability_zone_names[i],
                       tags={
                           **args.base_tags, "Name":
                           f"${args.description} Private Subnet {i}"
                       },
                       opts=pulumi.ResourceOptions(parent=self.vpc, ))
            for i, cidr in enumerate(subnet_distributor.private_subnets)
        ]

        # Adopt the default route table for this VPC and adapt it for use with public subnets
        self.public_route_table = ec2.DefaultRouteTable(
            f"{name}-public-rt",
            default_route_table_id=self.vpc.default_route_table_id,
            tags={
                **args.base_tags, "Name":
                f"${args.description} Public Route Table"
            },
            opts=pulumi.ResourceOptions(parent=self.vpc, ))

        ec2.Route(f"{name}-route-public-sn-to-ig",
                  route_table_id=self.public_route_table.id,
                  destination_cidr_block="0.0.0.0/0",
                  gateway_id=self.internet_gateway.id,
                  opts=pulumi.ResourceOptions(parent=self.public_route_table))

        for i, subnet in enumerate(self.public_subnets):
            ec2.RouteTableAssociation(
                f"{name}-public-rta-{i + 1}",
                subnet_id=subnet.id,
                route_table_id=self.public_route_table,
                opts=pulumi.ResourceOptions(parent=self.public_route_table))

        self.nat_elastic_ip_addresses: [ec2.Eip] = list()
        self.nat_gateways: [ec2.NatGateway] = list()
        self.private_route_tables: [ec2.RouteTable] = list()

        # Create a NAT Gateway and appropriate route table for each private subnet
        for i, subnet in enumerate(self.private_subnets):
            self.nat_elastic_ip_addresses.append(
                ec2.Eip(f"{name}-nat-{i + 1}",
                        tags={
                            **args.base_tags, "Name":
                            f"{args.description} NAT Gateway EIP {i + 1}"
                        },
                        opts=pulumi.ResourceOptions(parent=subnet)))

            self.nat_gateways.append(
                ec2.NatGateway(
                    f"{name}-nat-gateway-{i + 1}",
                    allocation_id=self.nat_elastic_ip_addresses[i].id,
                    subnet_id=self.public_subnets[i].id,
                    tags={
                        **args.base_tags, "Name":
                        f"{args.description} NAT Gateway {i + 1}"
                    },
                    opts=pulumi.ResourceOptions(parent=subnet)))

            self.private_route_tables.append(
                ec2.RouteTable(f"{name}-private-rt-{i + 1}",
                               vpc_id=self.vpc.id,
                               tags={
                                   **args.base_tags, "Name":
                                   f"{args.description} Private RT {i + 1}"
                               },
                               opts=pulumi.ResourceOptions(parent=subnet)))

            ec2.Route(f"{name}-route-private-sn-to-nat-{i + 1}",
                      route_table_id=self.private_route_tables[i].id,
                      destination_cidr_block="0.0.0.0/0",
                      nat_gateway_id=self.nat_gateways[i].id,
                      opts=pulumi.ResourceOptions(
                          parent=self.private_route_tables[i]))

            ec2.RouteTableAssociation(
                f"{name}-private-rta-{i + 1}",
                subnet_id=subnet.id,
                route_table_id=self.private_route_tables[i].id,
                opts=pulumi.ResourceOptions(
                    parent=self.private_route_tables[i]))

        # Create S3 endpoint if necessary
        if args.create_s3_endpoint:
            ec2.VpcEndpoint(f"{name}-s3-endpoint",
                            vpc_id=self.vpc.id,
                            service_name=f"com.amazonaws.{config.region}.s3",
                            route_table_ids=[
                                self.public_route_table.id,
                                *[rt.id for rt in self.private_route_tables]
                            ],
                            opts=pulumi.ResourceOptions(parent=self.vpc))

        # Create DynamoDB endpoint if necessary
        if args.create_dynamodb_endpoint:
            ec2.VpcEndpoint(
                f"{name}-dynamodb-endpoint",
                vpc_id=self.vpc.id,
                service_name=f"com.amazonaws.{config.region}.dynamodb",
                route_table_ids=[
                    self.public_route_table.id,
                    *[rt.id for rt in self.private_route_tables]
                ],
                opts=pulumi.ResourceOptions(parent=self.vpc))

        super().register_outputs({})
예제 #6
0
    def __init__(self,
                 name,
                 port_list=None,
                 subnet_count=0,
                 vpc_tags=None,
                 sg_tags=None,
                 private_subnets=None,
                 security_group_ids=None,
                 public_subnets=None):
        ComponentResource.__init__(
            self, "aws:network:dtd", name, {
                "number_of_availability_zones": subnet_count,
                "use_private_subnets": True,
                "subnet_ids": private_subnets,
                "security_group_ids": security_group_ids,
                "public_subnet_ids": public_subnets
            }, None)

        self.name = name
        self.port_list = port_list
        self.subnet_count = subnet_count
        self.vpc_tags = vpc_tags
        self.sg_tags = sg_tags
        self.public_subnets = []
        self.private_subnets = []
        self.security_group_ids = []
        self.vpcid = None

        PUBLIC_SUBNET_COUNT = 0

        if subnet_count < 2 or subnet_count > 3:
            raise RunError(
                "Unsupported amount of subnets! 2 or 3 supported. %d entered" %
                subnet_count)

        # create the VPC
        vpc = ec2.Vpc(name,
                      cidr_block="10.0.0.0/16",
                      enable_dns_hostnames=True,
                      enable_dns_support=True,
                      tags=vpc_tags,
                      __opts__=ResourceOptions(parent=self))

        self.vpcid = vpc.id

        public_route_table_id = self._create_public_subnet_route_table(vpc.id)
        private_route_table_id = None

        # create the subnets
        for i in range(subnet_count):
            # create public subnet(s) first
            if i <= PUBLIC_SUBNET_COUNT:
                self.public_subnets.append(
                    self._create_public_subnet(vpc.id, public_route_table_id,
                                               i))
            # create private subnet(s) next
            else:
                # do create the private route table, eip & NAT just once
                if i == 1:
                    public_subnet_id = self.public_subnets[0]
                    private_route_table_id = self._create_private_subnet_route_table(
                        public_subnet_id, vpc.id)
                self.private_subnets.append(
                    self._create_private_subnet(vpc.id, private_route_table_id,
                                                i))

        self.security_group_ids = self._create_security_groups(vpc.id)
        self.public_sg = self.security_group_ids['public']
        self.private_sg = self.security_group_ids['private']

        # This does not work because the items in the dictionary are of type Output
        # for k in all_security_group_ids:
        #     print(k)
        #     if "public" in k:
        #         self.public_security_groups.append(all_security_group_ids[k])
        #     elif "private" in k:
        #         self.private_security_groups.append(all_security_group_ids[k])
        # self.security_group_ids = list(all_security_group_ids)

        # this may be unnecessary - it is a nice to have for the UI for now
        self.register_outputs({
            "vpc_id": vpc.id,
            "private_subnet_ids": self.private_subnets,
            "public_subnet_ids": self.public_subnet_ids,
            "security_group_ids": self.security_group_ids
        })
예제 #7
0
파일: vpc.py 프로젝트: MDRCS/python-devops
from pulumi_aws import config, ec2, get_availability_zones

## VPC

vpc = ec2.Vpc('eks-vpc',
              cidr_block='10.100.0.0/16',
              instance_tenancy='default',
              enable_dns_hostnames=True,
              enable_dns_support=True,
              tags={'Name': 'pulumi-eks-vpc'})

igw = ec2.InternetGateway('vpc-ig',
                          vpc_id=vpc.id,
                          tags={'Name': 'pulumi-vpc-ig'})

eks_route_table = ec2.RouteTable('vpc-route-table',
                                 vpc_id=vpc.id,
                                 routes=[{
                                     'cidr_block': '0.0.0.0/0',
                                     'gateway_id': igw.id
                                 }],
                                 tags={'Name': 'pulumi-vpc-rt'})

## Subnets, one for each AZ in a region

zones = get_availability_zones()
subnet_ids = []

for zone in zones.names:
    vpc_subnet = ec2.Subnet(f'vpc-subnet-{zone}',
                            assign_ipv6_address_on_creation=False,
예제 #8
0
# by type (gateways, subnets, routes+route tables, etc.). Not sure it would
# work, but there's got to be a way to break this up.

# TODO find or create an AMI chooser, given a region and instance type

# TODO create a config file

_ami = 'ami-032509850cf9ee54e'
_az1 = 'us-west-2b'
_az2 = 'us-west-2c'
_instance_type = 't2.micro'
_key_name = 'sl-us-west-2'

vpc = ec2.Vpc(resource_name='new-vpc',
              cidr_block='10.0.0.0/16',
              tags={
                  'Name': 'infra vpc (front-back-autoscaling)',
                  'Creator': 'timc'
              })

igw = ec2.InternetGateway(
    resource_name='new-igw',
    vpc_id=vpc.id,
    tags={
        'Name': 'infra internet gateway (front-back-autoscaling)',
        'Creator': 'timc'
    })

public_subnet_1 = ec2.Subnet(
    resource_name='new-public-subnet-1',
    vpc_id=vpc.id,
    cidr_block='10.0.0.0/24',
예제 #9
0
    def __init__(self, name: str, args: VpcArgs, opts: ResourceOptions = None):

        super().__init__('custom:resource:VPC', name, {}, opts)

        vpc_name = name + '-vpc'
        self.vpc = ec2.Vpc(vpc_name,
                           cidr_block=args.cidr_block,
                           instance_tenancy=args.instance_tenancy,
                           enable_dns_hostnames=args.enable_dns_hostnames,
                           enable_dns_support=args.enable_dns_support,
                           tags={'Name': vpc_name},
                           opts=ResourceOptions(parent=self))

        igw_name = name + '-igw'
        self.igw = ec2.InternetGateway(igw_name,
                                       vpc_id=self.vpc.id,
                                       tags={'Name': igw_name},
                                       opts=ResourceOptions(parent=self))

        rt_name = name + '-rt'
        self.route_table = ec2.RouteTable(rt_name,
                                          vpc_id=self.vpc.id,
                                          routes=[
                                              ec2.RouteTableRouteArgs(
                                                  cidr_block='0.0.0.0/0',
                                                  gateway_id=self.igw.id,
                                              )
                                          ],
                                          tags={'Name': rt_name},
                                          opts=ResourceOptions(parent=self))

        # Subnets, at least across two zones.
        all_zones = get_availability_zones()
        # limiting to 2 zones for speed and to meet minimal requirements.
        zone_names = [all_zones.names[0], all_zones.names[1]]
        self.subnets = []
        subnet_name_base = f'{name}-subnet'
        for zone in zone_names:
            vpc_subnet = ec2.Subnet(
                f'{subnet_name_base}-{zone}',
                assign_ipv6_address_on_creation=False,
                vpc_id=self.vpc.id,
                map_public_ip_on_launch=True,
                cidr_block=f'10.100.{len(self.subnets)}.0/24',
                availability_zone=zone,
                tags={
                    'Name': f'{subnet_name_base}-{zone}',
                },
                opts=ResourceOptions(parent=self))
            ec2.RouteTableAssociation(f'vpc-route-table-assoc-{zone}',
                                      route_table_id=self.route_table.id,
                                      subnet_id=vpc_subnet.id,
                                      opts=ResourceOptions(parent=self))
            self.subnets.append(vpc_subnet)

        # Security Groups
        rds_sg_name = f'{name}-rds-sg'
        self.rds_security_group = ec2.SecurityGroup(
            rds_sg_name,
            vpc_id=self.vpc.id,
            description='Allow client access.',
            tags={'Name': rds_sg_name},
            ingress=[
                ec2.SecurityGroupIngressArgs(cidr_blocks=['0.0.0.0/0'],
                                             from_port=3306,
                                             to_port=3306,
                                             protocol='tcp',
                                             description='Allow rds access.'),
            ],
            egress=[
                ec2.SecurityGroupEgressArgs(
                    protocol='-1',
                    from_port=0,
                    to_port=0,
                    cidr_blocks=['0.0.0.0/0'],
                )
            ],
            opts=ResourceOptions(parent=self))

        fe_sg_name = f'{name}-fe-sg'
        self.fe_security_group = ec2.SecurityGroup(
            fe_sg_name,
            vpc_id=self.vpc.id,
            description='Allow all HTTP(s) traffic.',
            tags={'Name': fe_sg_name},
            ingress=[
                ec2.SecurityGroupIngressArgs(cidr_blocks=['0.0.0.0/0'],
                                             from_port=443,
                                             to_port=443,
                                             protocol='tcp',
                                             description='Allow https.'),
                ec2.SecurityGroupIngressArgs(cidr_blocks=['0.0.0.0/0'],
                                             from_port=80,
                                             to_port=80,
                                             protocol='tcp',
                                             description='Allow http access'),
            ],
            egress=[
                ec2.SecurityGroupEgressArgs(
                    protocol='-1',
                    from_port=0,
                    to_port=0,
                    cidr_blocks=['0.0.0.0/0'],
                )
            ],
            opts=ResourceOptions(parent=self))

        self.register_outputs({})
예제 #10
0
instance_role_policy_1 = iam.RolePolicyAttachment(
    'instance-role-policy-1',
    policy_arn='arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy',
    role=ec2_role.name)

instance_role_policy_2 = iam.RolePolicyAttachment(
    'instance-role-policy-2',
    policy_arn='arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy',
    role=ec2_role.name)

vpc = ec2.Vpc('eks-vpc',
              cidr_block='10.100.0.0/16',
              instance_tenancy='default',
              enable_dns_hostnames=True,
              enable_dns_support=True,
              tags={
                  'Name': 'vpc',
                  'kubernetes.io/cluster/pulumi-kubeflow-ml': 'shared'
              })

# https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/security_group.html.markdown
eks_cluster_sg = ec2.SecurityGroup(
    'eks-cluster-sg',
    vpc_id=vpc.id,
    description='Allow all traffic and associate with our vpc',
    tags={'Name': 'eks-cluster-sg'},
    egress=[{
        'cidr_blocks': ["0.0.0.0/0"],
        'from_port': '0',
        'to_port': '0',
예제 #11
0
#   edit: unsupported feature on the AWS side
#   edit: maybe a Pulumi usability bug? This will cause occasional failures if not explicit

# TODO need a solution here. I'd like to randomly choose a suitable AZ.
# However, once an AZ is chosen, that choice should be stable across `pulumi
# update`s, so that we're not causing what I call "stack churn". For now I'm
# going with a static choice. The original motivation is that in `us-west-2`,
# `t2.micro` is an unsupported instance type. So about one time in four, when
# creating a new stack, Pulumi chooses an AZ and everything fails.

_availability_zone = 'us-west-2b'
_instance_type = 't2.micro'

vpc = ec2.Vpc(resource_name='new-vpc',
              cidr_block='10.0.0.0/16',
              tags={
                  'Name': 'infra vpc',
                  'Creator': 'timc'
              })

igw = ec2.InternetGateway(resource_name='new-igw',
                          vpc_id=vpc.id,
                          tags={
                              'Name': 'infra internet gateway',
                              'Creator': 'timc'
                          })

subnet = ec2.Subnet(resource_name='new-subnet',
                    vpc_id=vpc.id,
                    cidr_block='10.0.0.0/20',
                    availability_zone=_availability_zone,
                    tags={
예제 #12
0
def setup_vpc():
    # Create a VPC
    vpc_config = Config().require_object("vpc_config")
    vpc = ec2.Vpc("chatapp-vpc",
                  cidr_block=vpc_config['cidr'],
                  enable_dns_hostnames=True,
                  enable_dns_support=True)

    # Create public subnet to place NGW
    public_subnet = ec2.Subnet("PublicSubnet",
                               vpc_id=vpc.id,
                               cidr_block=vpc_config['public_subnet_cidr'],
                               availability_zone="ap-southeast-1a")

    # Create private subnets 1 and 2 for rds and redis clusters
    private_subnet_1 = ec2.Subnet(
        "PrivateSubnet1",
        vpc_id=vpc.id,
        cidr_block=vpc_config['private_subnet_1_cidr'],
        availability_zone="ap-southeast-1b")

    private_subnet_2 = ec2.Subnet(
        "PrivateSubnet2",
        vpc_id=vpc.id,
        cidr_block=vpc_config['private_subnet_2_cidr'],
        availability_zone="ap-southeast-1c")

    # Create internet gateway
    inet_gw = ec2.InternetGateway(
        "inet-gateway",
        vpc_id=vpc.id,
    )

    # create NAT gateway
    elastic_ip = ec2.Eip("eip1",
                         opts=ResourceOptions(delete_before_replace=True))
    nat_gw = ec2.NatGateway("nat-gateway",
                            subnet_id=public_subnet.id,
                            allocation_id=elastic_ip.id)

    # Create private routed route-table
    private_subnet_route_table = ec2.RouteTable("privatesubnetroutetable",
                                                routes=[{
                                                    "cidr_block": "0.0.0.0/0",
                                                    "gateway_id": nat_gw.id
                                                }],
                                                vpc_id=vpc.id)

    # Create public routed route-table
    public_subnet_route_table = ec2.RouteTable("publicsubnetroutetable",
                                               routes=[{
                                                   "cidr_block": "0.0.0.0/0",
                                                   "gateway_id": inet_gw.id
                                               }],
                                               vpc_id=vpc.id)

    # Attach route tables to subnets
    ec2.RouteTableAssociation("PrivateSubnetRT1",
                              subnet_id=private_subnet_1.id,
                              route_table_id=private_subnet_route_table.id)
    ec2.RouteTableAssociation("PrivateSubnetRT2",
                              subnet_id=private_subnet_2.id,
                              route_table_id=private_subnet_route_table.id)
    ec2.RouteTableAssociation("PublicSubnetRT",
                              subnet_id=public_subnet.id,
                              route_table_id=public_subnet_route_table.id)
    return dict(vpc=vpc, private_subnets=[private_subnet_1, private_subnet_2])
예제 #13
0
    read_capacity=1,
    write_capacity=1)

## EC2
eip = ec2.Eip("myeip")

security_group = ec2.SecurityGroup("mysecuritygroup",
                                   ingress=[
                                       ec2.SecurityGroupIngressArgs(
                                           protocol="tcp",
                                           from_port=80,
                                           to_port=80,
                                           cidr_blocks=["0.0.0.0/0"])
                                   ])

vpc = ec2.Vpc("myvpc", cidr_block="10.0.0.0/16")

igw = ec2.InternetGateway("myinternetgateway", vpc_id=vpc.id)

public_route_table = ec2.RouteTable("myroutetable",
                                    routes=[
                                        ec2.RouteTableRouteArgs(
                                            cidr_block="0.0.0.0/0",
                                            gateway_id=igw.id)
                                    ],
                                    vpc_id=vpc.id)

## ECR

repository = ecr.Repository("myrepository")
예제 #14
0
APP = f"{get_project()}-{_env}"
TIERS = ['public', 'app', 'data']
region = boto3.session.Session().region_name
cidr = conf.require(f"cidr.{region}")
aws_dns = conf.require_bool('useAwsDns')
max_azs = conf.require_int('maxAzs')


client = boto3.client('ec2', region_name=region)

vpc = ec2.Vpc(
        resource_name=f'{APP}-vpc',
        cidr_block=cidr,
        enable_dns_hostnames=aws_dns,
        enable_dns_support=aws_dns,
        instance_tenancy='default',
        tags={
            'Name': APP,
            'Environment': _env
        }
    )

igw = ec2.InternetGateway(
        resource_name=f'{APP}-igw',
        vpc_id=vpc.id
    )

azs_response = client.describe_availability_zones(
        Filters=[
            {
                'Name': 'region-name',
예제 #15
0
import pulumi
from pulumi_aws import ec2, get_availability_zones

import utils

# read local config settings
config = pulumi.Config()

private_subnet_cidrs = config.require_object("private_subnet_cidrs")
public_subnet_cidrs = config.require_object("public_subnet_cidrs")
zones_amount = config.require_int("zones_amount")

zones = utils.get_aws_az(zones_amount)

vpc = ec2.Vpc("pulumi-vpc",
              cidr_block=config.require("vpc_cidr"),
              tags={"Name": "pulumi-vpc"})

igw = ec2.InternetGateway("pulumi-igw", vpc_id=vpc.id)

public_rt = ec2.RouteTable(
    "pulumi-public-rt",
    vpc_id=vpc.id,
    routes=[{
        "cidr_block": "0.0.0.0/0",
        "gateway_id": igw.id
    }],
    tags={"Name": "pulumi-public-rt"},
)

public_subnet_ids = []
예제 #16
0
    def __init__(
        self,
        name,
        opts=None,
    ):
        super().__init__("nuage:aws:DevelopmentEnvironment:VPC",
                         f"{name}VpcEnvironment", None, opts)

        vpc = ec2.Vpc(
            f"{name}Vpc",
            cidr_block="172.32.0.0/16",
            enable_dns_hostnames=True,
            enable_dns_support=True,
        )
        subnet_1 = ec2.Subnet(
            f"{name}VpcSubnetA",
            availability_zone="eu-west-1a",
            vpc_id=vpc.id,
            cidr_block="172.32.0.0/20",
            opts=ResourceOptions(depends_on=[vpc]),
        )
        subnet_2 = ec2.Subnet(
            f"{name}VpcSubnetB",
            availability_zone="eu-west-1b",
            vpc_id=vpc.id,
            cidr_block="172.32.16.0/20",
            opts=ResourceOptions(depends_on=[vpc]),
        )
        subnet_3 = ec2.Subnet(
            f"{name}VpcSubnetC",
            availability_zone="eu-west-1c",
            vpc_id=vpc.id,
            cidr_block="172.32.32.0/20",
            opts=ResourceOptions(depends_on=[vpc]),
        )

        private_subnet_1 = ec2.Subnet(
            f"{name}VpcPrivateSubnetA",
            availability_zone="eu-west-1a",
            vpc_id=vpc.id,
            cidr_block="172.32.48.0/20",
            opts=ResourceOptions(depends_on=[vpc]),
        )

        security_group = ec2.SecurityGroup(
            f"{name}SecurityGroup",
            vpc_id=vpc.id,
            opts=ResourceOptions(depends_on=[vpc]),
        )

        security_group_rule = ec2.SecurityGroupRule(
            f"{name}SSHRule",
            security_group_id=security_group.id,
            type="ingress",
            protocol="tcp",
            from_port=22,
            to_port=22,
            cidr_blocks=["0.0.0.0/0"],
        )

        security_group_rule = ec2.SecurityGroupRule(
            f"{name}InboundRule",
            security_group_id=security_group.id,
            type="ingress",
            protocol="all",
            from_port=0,
            to_port=65535,
            source_security_group_id=security_group.id,
        )
        security_group_rule = ec2.SecurityGroupRule(
            f"{name}OutboundRule",
            security_group_id=security_group.id,
            type="egress",
            protocol="all",
            from_port=0,
            to_port=65535,
            cidr_blocks=["0.0.0.0/0"],
        )

        subnets = [subnet_1, subnet_2, subnet_3]

        gateway = ec2.InternetGateway(
            f"{name}InternetGateway",
            vpc_id=vpc.id,
            opts=ResourceOptions(depends_on=[vpc]),
        )

        gateway_route = ec2.Route(
            f"{name}GatewayRoute",
            destination_cidr_block="0.0.0.0/0",
            gateway_id=gateway.id,
            route_table_id=vpc.default_route_table_id,
        )

        elastic_ip = ec2.Eip(f"{name}Eip",
                             vpc=True,
                             opts=ResourceOptions(depends_on=[gateway]))

        nat_gateway = ec2.NatGateway(
            f"{name}NatGateway",
            subnet_id=subnet_1.id,
            allocation_id=elastic_ip.id,
            opts=ResourceOptions(depends_on=[subnet_1, elastic_ip]),
        )

        private_route_table = ec2.RouteTable(
            f"{name}PrivateRouteTable",
            routes=[
                {
                    "cidr_block": "0.0.0.0/0",
                    "nat_gateway_id": nat_gateway.id,
                },
            ],
            vpc_id=vpc.id,
            opts=ResourceOptions(depends_on=[private_subnet_1]),
        )

        private_route_table_assoc = ec2.RouteTableAssociation(
            f"{name}PrivateRouteTableAssoc",
            route_table_id=private_route_table.id,
            subnet_id=private_subnet_1.id,
        )

        outputs = {
            "vpc": vpc,
            "security_group": security_group,
            "public_subnets": [subnet_1, subnet_2, subnet_3],
            "private_subnet": private_subnet_1,
            "nat_gateway": nat_gateway,
        }

        self.set_outputs(outputs)