def build(prefix, template, cidr="172.168.0.0/16", vpc_param=None, subnet_param=None): """ Declare a VPC with: * One public subnet * Security group for the EC2 instance * One EC2 t2.nano instance in the public subnet :param prefix: Prefix for all resource names :param template: Template for building CF output """ vpc = None if vpc_param is None: vpc_title = resource_title.vpc_title(prefix) vpc = ec2.VPC(vpc_title) vpc.CidrBlock = cidr vpc.Tags = [tagging.name(vpc_title), tagging.env_name()] template.add_resource(vpc) template.add_output(Output('VPC', Description="VPC Identifier", Value=Ref(vpc))) subnet_resource = None if subnet_param is None: subnet_resource = subnet.build(prefix, template, vpc) security_group_resource = security_group.build(prefix, template, vpc or vpc_param) return (vpc or vpc_param, subnet_resource or subnet_param, security_group_resource)
def create_vpc(self): """Create the VPC resources.""" template = self.template variables = self.get_variables() self.template.add_version(AWS_TEMPLATE_VERSION) self.template.add_description('Create a VPC') vpc = ec2.VPC( VPC_NAME, CidrBlock=variables['VpcCidr'], EnableDnsSupport=True, EnableDnsHostnames=True, Tags=[ec2.Tag('Name', variables['VpcName'] + '-LATESTREPO')] ) template.add_resource(vpc) template.add_output( Output( OUTPUT_VPC_ID, Value=VPC_ID ) ) # create the internet gateway if needed if variables["UseInternetGW"]: template.add_resource(ec2.InternetGateway('InternetGatway')) template.add_resource( ec2.VPCGatewayAttachment( 'GatewayAttach', VpcId=Ref(VPC_NAME), InternetGatewayId=Ref('InternetGatway') ) )
def main(): vpc = ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16') subnet = ec2.Subnet('MySubnet', AvailabilityZone='ap-southeast-2a', VpcId=Ref(vpc), CidrBlock='10.0.1.0/24') template = Template() single_instance_config = SingleInstanceConfig( keypair='INSERT_YOUR_KEYPAIR_HERE', si_image_id='ami-dc361ebf', si_instance_type='t2.micro', vpc=Ref(vpc), subnet=Ref(subnet), instance_dependencies=vpc.title, public_hosted_zone_name=None, sns_topic=None, is_nat=False, iam_instance_profile_arn=None, availability_zone='ap-southeast-2a') SingleInstance(title='jump', template=template, single_instance_config=single_instance_config) template.add_resource(vpc) template.add_resource(subnet) print(template.to_json(indent=2, separators=(',', ': ')))
def main(): vpc = ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16') subnet = ec2.Subnet('MySubnet', AvailabilityZone='ap-southeast-2a', VpcId=Ref(vpc), CidrBlock='10.0.1.0/24') template = Template() sns_topic = SNS(template) single_instance_config = SingleInstanceConfig( keypair='INSERT_YOUR_KEYPAIR_HERE', si_image_id='ami-53371f30', si_instance_type='t2.micro', vpc=Ref(vpc), subnet=Ref(subnet), is_nat=True, instance_dependencies=vpc.title, public_hosted_zone_name=None, iam_instance_profile_arn=None, sns_topic=sns_topic, availability_zone='ap-southeast-2a', ec2_scheduled_shutdown=None, owner='*****@*****.**') SingleInstance(title='nat1', template=template, single_instance_config=single_instance_config) template.add_resource(vpc) template.add_resource(subnet) print(template.to_json(indent=2, separators=(',', ': ')))
def test_internet_gateway(stack: Stack) -> None: """Test InternetGateway construct.""" vpc = ec2.VPC( name_to_id("vpc-test"), CidrBlock="10.0.0.0/16", EnableDnsHostnames="true", EnableDnsSupport="true", ) subnets = [ ec2.Subnet( name_to_id(f"{zone}-subnet"), CidrBlock="10.0.0.0/20", AvailabilityZone="eu-west-1b", VpcId=Ref(vpc), MapPublicIpOnLaunch="true", ) for zone, ip in zip(["eu-west-1a", "eu-west-1b"], ["10.0.0.0/20", "10.0.16.0/20"]) ] igw = InternetGateway(name_prefix="test", vpc=vpc, subnets=subnets) for el in (vpc, *subnets, igw): stack.add(el) assert stack.export()["Resources"] == EXPECTED_TEMPLATE
def main(): template = Template() az_a = 'ap-southeast-2a' az_b = 'ap-southeast-2b' az_c = 'ap-southeast-2c' private_subnets = [] public_subnets = [] vpc = Ref(template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16'))) public_route_table = template.add_resource( ec2.RouteTable('MyUnitPublicRouteTable', VpcId=vpc)) private_route_table = template.add_resource( ec2.RouteTable('MyUnitPrivateRouteTable', VpcId=vpc)) public_subnets.append( Subnet(template=template, route_table=public_route_table, az=az_a, cidr='10.0.1.0/24', vpc=vpc, is_public=True)) public_subnets.append( Subnet(template=template, route_table=public_route_table, az=az_b, cidr='10.0.2.0/24', vpc=vpc, is_public=True)) public_subnets.append( Subnet(template=template, route_table=public_route_table, az=az_c, cidr='10.0.3.0/24', vpc=vpc, is_public=True)) private_subnets.append( Subnet(template=template, route_table=private_route_table, az=az_a, cidr='10.0.101.0/24', vpc=vpc, is_public=False)) private_subnets.append( Subnet(template=template, route_table=private_route_table, az=az_b, cidr='10.0.102.0/24', vpc=vpc, is_public=False)) private_subnets.append( Subnet(template=template, route_table=private_route_table, az=az_c, cidr='10.0.103.0/24', vpc=vpc, is_public=False)) print(template.to_json(indent=2, separators=(',', ': ')))
def createCouchbaseVPC(t): couchbaseVPC = t.add_resource(ec2.VPC( 'VPC', CidrBlock='10.0.0.0/16', EnableDnsSupport='true', EnableDnsHostnames='true', Tags=Tags(Name=Join('', ['vpc-scalabilty-', Ref('AWS::Region')])) )) return couchbaseVPC
def vpc(self): return ec2.VPC( 'DedicatedVPC', InstanceTenancy='default', CidrBlock='10.0.0.0/16', EnableDnsHostnames='true', EnableDnsSupport='true', )
def create_vpc(): return ec2.VPC( 'vpc', CidrBlock=Ref('cidrVpc'), EnableDnsSupport=True, EnableDnsHostnames=True, Tags=_tags(), )
def dump_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", )) resource_tags = Tags(Name=Sub("${AWS::StackName}"), user="******", stelligent_u_lesson='lesson-4-1', stelligent_u_lab='lab-1') vpc = template.add_resource( ec2.VPC( "Vpc", CidrBlock=Ref(vpc_cidr_param), EnableDnsSupport=True, EnableDnsHostnames=True, InstanceTenancy="default", Tags=resource_tags, )) subnet = template.add_resource( ec2.Subnet( "Subnet", VpcId=Ref(vpc), CidrBlock=Ref(subnet_cidr_param), MapPublicIpOnLaunch=False, AvailabilityZone=Select(0, GetAZs()), Tags=resource_tags, )) template.add_output([ Output( "vpcId", Description="InstanceId of the newly created EC2 instance", Value=Ref(vpc), ), Output( "SubnetId", Description="InstanceId of the newly created EC2 instance", Value=Ref(subnet), ), ]) with open(cfn_file, 'w') as f: f.write(template.to_yaml())
def create_vpc(self): t = self.template t.add_resource(ec2.VPC( VPC_NAME, CidrBlock=Ref("CidrBlock"), EnableDnsSupport=True, EnableDnsHostnames=True)) # Just about everything needs this, so storing it on the object t.add_output(Output("VpcId", Value=VPC_ID))
def gen_vpc(self): self.vpc = ec2.VPC( "VPC", CidrBlock="10.0.0.0/16", EnableDnsSupport=True, EnableDnsHostnames=True, ) self.template.add_resource(self.vpc) self.export_value(Ref(self.vpc), "VPC")
def add_vpc(self): t = self.template self.vpc = t.add_resource( ec2.VPC('Vpc', CidrBlock=Ref(self.vpcCidrParam), EnableDnsSupport='true', EnableDnsHostnames='true', Tags=self.defaultTags + [ec2.Tag('Name', Join("", [self.namePrefix, 'Vpc']))]))
def create_vpc(self, name=VPC_NAME): self.vpc = self.template.add_resource( ec2.VPC(name, CidrBlock=self.config['vpc_cidrblock'], EnableDnsSupport=True, EnableDnsHostnames=True, InstanceTenancy="default", Tags=self.__set_tags("ServiceVPC"))) # Just about everything needs this, so storing it on the object self.template.add_output(Output(VPC_ID, Value=self.vpc.Ref()))
def create_vpc(self): t = self.template t.add_resource( ec2.VPC( VPC_NAME, CidrBlock=self.variables['VpcCIDR'], EnableDnsHostnames=True, Tags=Tags(self.variables['Tags']), )) t.add_output(Output("VpcId", Value=VPC_ID)) t.add_output(Output("CIDR", Value=self.variables['VpcCIDR']))
def vpc(self) -> ec2.VPC: """Return the VPC.""" return ec2.VPC( name_to_id(self.name), CidrBlock=self.cidr_block, EnableDnsHostnames="true", EnableDnsSupport="true", Tags=Tags({ "Name": self.name, **self.tags }), )
def create_vpc(self): vpc_name = 'ICPVPC' self.vpc = self.create_resource(ec2.VPC( vpc_name, CidrBlock=VPC_CIDR, EnableDnsSupport=True, EnableDnsHostnames=True, Tags=self.get_tags(Name=vpc_name)), output='VpcId') self.public_route_table = self.create_routing_resources() self.create_subnets()
def setup_resources(): """ Sets Up stack resources """ global vpc, template, public_route_table, private_route_table, az, public_subnets, private_subnets template = Template() private_subnets = [] public_subnets = [] vpc = template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16')) public_route_table = template.add_resource( ec2.RouteTable('MyUnitPublicRouteTable', VpcId=Ref(vpc))) private_route_table = template.add_resource( ec2.RouteTable('MyUnitPrivateRouteTable', VpcId=Ref(vpc))) az = ['ap-southeast-2a', 'ap-southeast-2b', 'ap-southeast-2c']
def add_vpc(self): """Add VPC to template and return the resource.""" name, tags = self._name_tags('vpc') self.vpc = self.t.add_resource( ec2.VPC( name, CidrBlock=self.aws['vpc.cidr_block'], EnableDnsHostnames=True, Tags=Tags(**tags) )) self.t.add_output(Output( "VpcId", Value=Ref(self.vpc) ))
def setup_resources(): """ Create generic testing data """ global template global vpc template = Template() vpc = template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16', EnableDnsSupport='true', EnableDnsHostnames='true'))
def create_vpc(self): t = self.template t.add_resource( ec2.VPC( VPC_NAME, CidrBlock=self.get_variables()["VpcCidrBlock"], EnableDnsSupport=True, EnableDnsHostnames=True, Tags=Tags(Name=self.get_variables()["Namespace"]) ) ) t.add_output(Output("VpcId", Value=VPC_ID))
def create_vpc(self): """Creates a VPC template and returns the JSON string for that CloudFormation Template Returns: str: JSON string for CloudFormation that can be used to launch the CloudFormation stack """ self.vpc = self.create_resource(ec2.VPC('CacVPC', CidrBlock=VPC_CIDR, EnableDnsSupport=True, EnableDnsHostnames=True, Tags=self.get_tags()), output='VpcId') public_route_table = self.create_routing_resources() self.create_subnets(public_route_table) self.create_bastion()
def build_vpc_template(vpc_config): vpc_tags = [{"Key": "Application", "Value": Ref("AWS::StackId")}] vpc = ec2.VPC(name=vpc_config["Name"], CidrBlock=vpc_config["IP Range"], Tags=vpc_tags) t = Template() vpc_config["Subnets"].sort(key=lambda net: net["IP Count"], reverse=True) subnets = build_subnets(vpc_config["Subnets"], vpc_config["IP Range"], vpc_config["Name"]) [subnet.Tags.append(vpc.Tags[0]) for subnet in subnets] private_route_table = build_private_route_table(vpc_config["Name"]) public_route_table = build_public_route_table(vpc_config["Name"]) t.add_resource(vpc) t.add_resource(private_route_table) t.add_resource(public_route_table) t.add_resource(build_public_route()) [ t.add_resource(public_route_table_association) for public_route_table_association in build_public_route_table_associations(vpc_config["Subnets"]) ] [t.add_resource(subnet) for subnet in subnets] [ t.add_resource(gateway_attachments) for gateway_attachments in build_public_gateway(vpc_config["Name"]) ] management_group = build_management_security_group(vpc_config["Name"]) t.add_resource(management_group[0]) default_group = build_default_security_group(vpc_config["Name"]) t.add_resource(default_group[0]) t.add_resource(default_group[1]) t.add_output(management_group[1]) t.add_output(default_group[2]) t.add_output(Output(name="vpcId", Value=Ref(vpc_config["Name"]))) [ t.add_output(Output(name=subnet.name, Value=Ref(subnet.name))) for subnet in subnets ] return t
def main(): template = Template() myvpc = Ref(template.add_resource(ec2.VPC('myVpc', CidrBlock='10.0.0.0/16'))) home_cidrs = [{'name': 'GA1', 'cidr': '123.123.132.123/24'}, {'name': 'GA2', 'cidr': '231.231.231.231/32'}] public_cidr = {'name': 'PublicIp', 'cidr': '0.0.0.0/0'} seo0_jump = LocalSecurityEnabledObject(title='StackJump', vpc=myvpc, template=template) seo1_nat = LocalSecurityEnabledObject(title='StackNAT', vpc=myvpc, template=template) seo2_web = LocalSecurityEnabledObject(title='Unit01Web', vpc=myvpc, template=template) seo3_api = LocalSecurityEnabledObject(title='Unit01Api', vpc=myvpc, template=template) seo4_elb = LocalSecurityEnabledObject(title='Unit01Elb', vpc=myvpc, template=template) # Add inbound SSH traffic to jump box for cidr in home_cidrs: seo0_jump.add_ingress(cidr, '22') # Add traffic from nat to web and api boxes seo1_nat.add_flow(seo2_web, '80') seo1_nat.add_flow(seo2_web, '443') seo1_nat.add_flow(seo3_api, '80') seo1_nat.add_flow(seo3_api, '443') # Add traffic from web and api boxes to nat seo2_web.add_flow(seo1_nat, '80') seo2_web.add_flow(seo1_nat, '443') seo3_api.add_flow(seo1_nat, '80') seo3_api.add_flow(seo1_nat, '443') # Add traffic out of nat to public seo1_nat.add_egress(public_cidr, '80') seo1_nat.add_egress(public_cidr, '443') # Add traffic from elb to web seo4_elb.add_flow(seo2_web, '80') seo4_elb.add_flow(seo2_web, '443') # Add traffic from public to elb seo4_elb.add_ingress(public_cidr, '80') seo4_elb.add_ingress(public_cidr, '443') # Add traffic from web to api seo2_web.add_flow(seo3_api, '80') seo2_web.add_flow(seo3_api, '443') print(template.to_json(indent=2, separators=(',', ': ')))
def create_vpc(t, env, env_number, subnet_mapping, subnet_config): ''' Creates the VPC along with the subnets, IGW and RouteTables ''' vpc_objects = {} vpc_objects['vpc'] = t.add_resource( ec2.VPC("{}VPC".format(env.upper()), CidrBlock="10.{}.0.0/16".format(env_number), InstanceTenancy="default", Tags=Tags(Name="{}VPC".format(env.upper())))) vpc_objects['igw'] = t.add_resource(ec2.InternetGateway("InternetGateway")) vpc_objects['igw_attachment'] = t.add_resource( ec2.VPCGatewayAttachment( "IGWAttachment", VpcId=Ref(vpc_objects['vpc']), InternetGatewayId=Ref(vpc_objects['igw']), )) # Create Subnets vpc_objects['subnets'] = {} vpc_objects['nat_eip'] = {} for subid in subnet_config: vpc_objects['subnets'][subid] = t.add_resource( ec2.Subnet(subid, CidrBlock=subnet_config[subid]['subnet'], VpcId=Ref(vpc_objects['vpc']), AvailabilityZone="{}".format( subnet_config[subid]['az_name']), Tags=Tags(Name="{}Subnet".format(subid)))) # Create NAT Gateways if subnet_config[subid]['service'] == 'nat': az = subnet_config[subid]['az_number'] nat_eip_name = '{}{}NatEIP'.format(env.title(), az) vpc_objects['nat_eip'][nat_eip_name] = t.add_resource( ec2.EIP(nat_eip_name, Domain="vpc")) t.add_resource( ec2.NatGateway('{}{}NatGW'.format(env.title(), az), AllocationId=GetAtt( vpc_objects['nat_eip'][nat_eip_name], 'AllocationId'), SubnetId=Ref(vpc_objects['subnets'][subid]))) return t, vpc_objects
def main(): """ Creates a troposphere template and then adds a single s3 bucket """ template = Template() vpc = template.add_resource(ec2.VPC('MyVPC', CidrBlock='10.0.0.0/16')) internet_gateway = template.add_resource(ec2.InternetGateway('MyInternetGateway')) template.add_resource(ec2.VPCGatewayAttachment('MyVPCGatewayAttachment', InternetGatewayId=Ref(internet_gateway), VpcId=Ref(vpc), DependsOn=internet_gateway.title)) security_group = template.add_resource(ec2.SecurityGroup('mySecGroup', GroupDescription='Security group', VpcId=Ref(vpc), )) subnet = template.add_resource(ec2.Subnet('MyPubSub', AvailabilityZone='ap-southeast-2a', VpcId=Ref(vpc), CidrBlock='10.0.1.0/24')) template.add_resource(ec2.Instance( 'myinstance', KeyName='INSERT_YOUR_KEYPAIR_HERE', ImageId='ami-dc361ebf', InstanceType='t2.nano', NetworkInterfaces=[ec2.NetworkInterfaceProperty( GroupSet=[Ref(security_group)], AssociatePublicIpAddress=True, DeviceIndex='0', DeleteOnTermination=True, SubnetId=Ref(subnet))], SourceDestCheck=True, DependsOn=internet_gateway.title )) SNS(template=template) print(template.to_json(indent=2, separators=(',', ': ')))
def define_vpc(self, vpc_config): vpc = ec2.VPC(vpc_config["name"], DeletionPolicy=self.deletion_policy) vpc.CidrBlock = vpc_config["cidr_block"] vpc.EnableDnsSupport = vpc_config["dns_support"] vpc.EnableDnsHostnames = vpc_config["dns_hostnames"] vpc.Tags = self._get_tags(vpc_config) self._add_resource(vpc) if vpc_config["internet_gateway"]: ig = ec2.InternetGateway(vpc_config["internet_gateway"]["name"], DeletionPolicy=self.deletion_policy) ig.Tags = self._get_tags(vpc_config["internet_gateway"]) self.template.add_resource(ig) iga = ec2.VPCGatewayAttachment( "%sAttachment" % vpc_config["internet_gateway"]["name"], DependsOn=ig.name, DeletionPolicy=self.deletion_policy) iga.VpcId = Ref(vpc) iga.InternetGatewayId = Ref(ig) self.template.add_resource(iga)
def configure_vpc(cfn_template, cluster_name): vpc = ec2.VPC("DustVPC") vpc.CidrBlock = "10.0.0.0/16" vpc.Tags = [ec2.Tag("Name:", cluster_name)] cfn_template.add_resource(vpc) vpc_id = Ref(vpc) subnet = ec2.Subnet('dustSubnet') subnet.VpcId = vpc_id subnet.CidrBlock = "10.0.0.0/24" cfn_template.add_resource(subnet) vpc_subnet = Ref(subnet) net_gateway = ec2.InternetGateway('dustGateway') cfn_template.add_resource(net_gateway) attach_net_gateway = ec2.VPCGatewayAttachment('dustAttachGateway') attach_net_gateway.VpcId = vpc_id attach_net_gateway.InternetGatewayId = Ref(net_gateway) cfn_template.add_resource(attach_net_gateway) route_table = ec2.RouteTable('dustRoutetable') route_table.VpcId = vpc_id cfn_template.add_resource(route_table) route = ec2.Route('dustRoute') route.RouteTableId = Ref(route_table) route.DestinationCidrBlock = "0.0.0.0/0" route.GatewayId = Ref(net_gateway) route.DependsOn = "dustAttachGateway" cfn_template.add_resource(route) attach_route = ec2.SubnetRouteTableAssociation('dustAttachRouteTable') attach_route.SubnetId = vpc_subnet attach_route.RouteTableId = Ref(route_table) cfn_template.add_resource(attach_route) return vpc_id, vpc_subnet
def create_vpc(self): """Create the VPC resources.""" template = self.template variables = self.get_variables() self.template.add_version(AWS_TEMPLATE_VERSION) self.template.add_description('Create a VPC') vpc = ec2.VPC( VPC_NAME, CidrBlock=variables['VpcCidr'], EnableDnsSupport=True, EnableDnsHostnames=True, Tags=[ec2.Tag('Name', variables['VpcName'])] ) template.add_resource(vpc) template.add_output( Output( OUTPUT_VPC_ID, Value=VPC_ID ) )
'PublicSubnetCidr', Type='String', Description='Public Subnet CIDR', Default='172.18.0.0/22', )) private_subnet = t.add_parameter( Parameter( 'PrivateSubnetCidr', Type='String', Description='Public Subnet CIDR', Default='172.18.32.0/21', )) vpc = t.add_resource(ec2.VPC( 'VPC', CidrBlock=Ref(vpc_cidr), )) public_net = t.add_resource( ec2.Subnet( 'PublicSubnet', CidrBlock=Ref(public_subnet), MapPublicIpOnLaunch=True, VpcId=Ref(vpc), )) private_net = t.add_resource( ec2.Subnet( 'PrivateSubnet', CidrBlock=Ref(private_subnet), MapPublicIpOnLaunch=False,