コード例 #1
0
ファイル: vpc.py プロジェクト: jeffpierce/stacker_blueprints
    def create_nat_instance(self, zone_id, subnet_name):
        t = self.template
        suffix = zone_id
        nat_instance = t.add_resource(
            ec2.Instance(NAT_INSTANCE_NAME % suffix,
                         Condition="UseNatInstances",
                         ImageId=FindInMap('AmiMap', Ref("AWS::Region"),
                                           Ref("ImageName")),
                         SecurityGroupIds=[Ref(DEFAULT_SG),
                                           Ref(NAT_SG)],
                         SubnetId=Ref(subnet_name),
                         InstanceType=Ref('InstanceType'),
                         SourceDestCheck=False,
                         KeyName=Ref('SshKeyName'),
                         Tags=[ec2.Tag('Name', 'nat-gw%s' % suffix)],
                         DependsOn=GW_ATTACH))

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

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

        return nat_instance
コード例 #2
0
ファイル: __init__.py プロジェクト: fsultan/aws-cf-generator
    def define_instance_eip(self, nat_ip_config, nat_device):
        nat_ip = ec2.EIP(nat_ip_config["name"],
                         DependsOn="InternetGatewayAttachment",
                         DeletionPolicy=self.deletion_policy)
        nat_ip.InstanceId = Ref(nat_device)
        nat_ip.Domain = "vpc"

        self._add_resource(nat_ip)
        self.assign_instance_eip(nat_device, nat_ip)
コード例 #3
0
    def create_nat_instance(self, zone_id, subnet_name):
        t = self.template
        variables = self.get_variables()
        suffix = zone_id
        eip_name = "NATExternalIp%s" % suffix

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

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

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

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

        t.add_resource(
            ec2.EIP(eip_name,
                    Domain='vpc',
                    InstanceId=eip_instance_id,
                    DependsOn=GW_ATTACH))
コード例 #4
0
def build_eip(prefix, template, vpc, instance):
    """
    Adds an Elastic IP to the template and its value to the CF outputs.
    """
    eip = ec2.EIP("%sEIP" % prefix)
    eip.InstanceId = Ref(instance)
    eip.Domain = "vpc"
    if isinstance(vpc, ec2.VPC):
        eip.DependsOn = resource_title.vpc_gateway_title(prefix)
    template.add_resource(eip)
    template.add_output(
        Output('MessageServerHost',
               Description="Messaging Service Host Public IP",
               Value=Ref(eip)))
コード例 #5
0
    def add_natgw(self):
        t = self.template
        natGwSubnetId = None

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

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

        self.natGw = t.add_resource(
            ec2.NatGateway('NatGateway',
                           AllocationId=GetAtt(self.natEip, "AllocationId"),
                           SubnetId=natGwSubnetId))
コード例 #6
0
ファイル: EC2.py プロジェクト: joewcarpenter/simple-web-app
    def create_elastic_ip(self, name):
        """
        Create an Elastic IP address

        :param name: Name for the EIP
        """
        eip = ec2.EIP(name, Domain="vpc")

        self.template.add_resource(eip)

        self.template.add_output(
            Output(name,
                   Value=Ref(name),
                   Description=u"Elastic IP Address for {}".format(name),
                   Export=Export(Sub("${AWS::StackName}-" + name))))
        return eip
コード例 #7
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template

        # Elastic IPs
        vpnelasticip = template.add_resource(
            ec2.EIP('VPNElasticIP', Domain='vpc'))
        template.add_output([
            Output('VpnEipPublicIp',
                   Description='VPN instance public IP',
                   Export=Export(Sub('${AWS::StackName}-VpnEipPublicIp')),
                   Value=Ref(vpnelasticip)),
            Output('VpnEipAllocationId',
                   Description='AllocationId of the VPN instance public IP',
                   Export=Export(Sub('${AWS::StackName}-VpnEipAllocationId')),
                   Value=GetAtt(vpnelasticip, 'AllocationId'))
        ])
コード例 #8
0
ファイル: eip.py プロジェクト: ibejohn818/stackformation
    def _build_ip(self, t):

        eip = t.add_resource(ec2.EIP(
            "{}EIP".format(self.name)
        ))

        t.add_output([
            Output(
                "{}AllocationId".format(self.name),
                Value=GetAtt(eip, "AllocationId"),
                Description="{} Elastic IP".format(self.name)
            ),
            Output(
                "{}EIP".format(self.name),
                Value=Ref(eip),
                Description="{} Elastic IP".format(self.name)
            ),
        ])
コード例 #9
0
def create_vpc(t, env, env_number, subnet_mapping, subnet_config):
    '''
    Creates the VPC along with the subnets, IGW and RouteTables
    '''
    vpc_objects = {}
    vpc_objects['vpc'] = t.add_resource(
        ec2.VPC("{}VPC".format(env.upper()),
                CidrBlock="10.{}.0.0/16".format(env_number),
                InstanceTenancy="default",
                Tags=Tags(Name="{}VPC".format(env.upper()))))
    vpc_objects['igw'] = t.add_resource(ec2.InternetGateway("InternetGateway"))
    vpc_objects['igw_attachment'] = t.add_resource(
        ec2.VPCGatewayAttachment(
            "IGWAttachment",
            VpcId=Ref(vpc_objects['vpc']),
            InternetGatewayId=Ref(vpc_objects['igw']),
        ))

    # Create Subnets
    vpc_objects['subnets'] = {}
    vpc_objects['nat_eip'] = {}
    for subid in subnet_config:
        vpc_objects['subnets'][subid] = t.add_resource(
            ec2.Subnet(subid,
                       CidrBlock=subnet_config[subid]['subnet'],
                       VpcId=Ref(vpc_objects['vpc']),
                       AvailabilityZone="{}".format(
                           subnet_config[subid]['az_name']),
                       Tags=Tags(Name="{}Subnet".format(subid))))
        # Create NAT Gateways
        if subnet_config[subid]['service'] == 'nat':
            az = subnet_config[subid]['az_number']
            nat_eip_name = '{}{}NatEIP'.format(env.title(), az)
            vpc_objects['nat_eip'][nat_eip_name] = t.add_resource(
                ec2.EIP(nat_eip_name, Domain="vpc"))
            t.add_resource(
                ec2.NatGateway('{}{}NatGW'.format(env.title(), az),
                               AllocationId=GetAtt(
                                   vpc_objects['nat_eip'][nat_eip_name],
                                   'AllocationId'),
                               SubnetId=Ref(vpc_objects['subnets'][subid])))
    return t, vpc_objects
コード例 #10
0
    def create_nat_gateway(self, availability_zone, public_subnet,
                           private_route_table):
        nat_eip = self.create_resource(
            ec2.EIP(
                '{}NATIP'.format(availability_zone.cfn_name),
                Domain="vpc",
            ))

        nat_gateway = self.create_resource(
            ec2.NatGateway(
                '{}NATGateway'.format(availability_zone.cfn_name),
                AllocationId=GetAtt(nat_eip, 'AllocationId'),
                SubnetId=Ref(public_subnet),
            ))

        self.create_resource(
            ec2.Route('{}PrivateRoute'.format(availability_zone.cfn_name),
                      RouteTableId=Ref(private_route_table),
                      DestinationCidrBlock=ALLOW_ALL_CIDR,
                      NatGatewayId=Ref(nat_gateway)))
コード例 #11
0
 def create_nat_gateways(self):
     # Nat gateways in public subnets, one per AZ
     t = self.template
     for name in self.subnets.keys():
         if self.subnets[name]['net_type'] == 'public':
             if name == 'Public':
                 prefix = ''
             else:
                 prefix = name
             self.subnets[name]['nat_gateways'] = list()
             for i in range(len(self.zones)):
                 nat_gateway = '%sNatGateway%d' % (prefix, i)
                 nat_gateway_eip = '%sNatGatewayEIP%d' % (prefix, i)
                 self.subnets[name]['nat_gateways'].append(nat_gateway)
                 t.add_resource(ec2.EIP(nat_gateway_eip, Domain='vpc'))
                 t.add_resource(
                     ec2.NatGateway(
                         nat_gateway,
                         SubnetId=Ref(self.subnets[name]['az_subnets'][i]),
                         AllocationId=GetAtt(nat_gateway_eip,
                                             'AllocationId')))
コード例 #12
0
    def create_nat_gateway(self):
        t = self.template
        variables = self.get_variables()

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

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

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

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

        t.add_output(Output("NatGatewayId", Value=self.nat_gateway.Ref()))
コード例 #13
0
ファイル: vpc.py プロジェクト: nplutt/contacts
def create_vpc_template(template=None):
    if not template:
        template = Template()
        template.add_description(
            'AWS cloud formation script template.at creates a VPC with a NAT Gg'
        )
        template.add_version('2010-09-09')

    vpc_cidr_block = template.add_parameter(
        Parameter(
            'VPCCIDR',
            Default=vpc_config['cidr_block'],
            Description='The IP address space for this VPC, in CIDR notation',
            Type='String',
        ))

    vpc = template.add_resource(
        ec2.VPC('VPC',
                CidrBlock=Ref(vpc_cidr_block),
                Tags=Tags(vpc_config['tags'])))

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

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

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

    public_security_group = template.add_resource(
        ec2.SecurityGroup(
            security_group_config['public']['name'],
            GroupDescription='{} public security group'.format(
                vpc_config['name']),
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(IpProtocol='tcp',
                                      ToPort=r['port'],
                                      FromPort=r['port'],
                                      CidrIp=r['cidr_block'])
                for r in security_group_config['public']['ingress_rules']
            ],
            VpcId=Ref(vpc),
            Tags=Tags(
                dict(Name='public {} security group'.format(
                    vpc_config['name']))),
        ))

    template.add_output(
        Output('PublicSecurityGroupId',
               Value=Ref(public_security_group),
               Description='Public Security Group Id'))

    private_security_group = template.add_resource(
        ec2.SecurityGroup(
            security_group_config['private']['name'],
            GroupDescription='{} private security group'.format(
                vpc_config['name']),
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol='tcp',
                    ToPort=r['port'],
                    FromPort=r['port'],
                    SourceSecurityGroupId=Ref(public_security_group))
                for r in security_group_config['private']['ingress_rules']
            ],
            VpcId=Ref(vpc),
            Tags=Tags(
                dict(Name='private {} security group'.format(
                    vpc_config['name']))),
        ))

    for i, sub_net in enumerate(sub_nets):
        public_subnet = template.add_parameter(
            Parameter(
                'PublicSubnetCidr{}'.format(i),
                Type='String',
                Description='Public Subnet CIDR',
                Default=sub_net['public_cidr'],
            ))

        public_net = template.add_resource(
            ec2.Subnet(
                'PublicSubnet{}'.format(i),
                AvailabilityZone=sub_net['region'],
                CidrBlock=Ref(public_subnet),
                MapPublicIpOnLaunch=False,
                VpcId=Ref(vpc),
                Tags=Tags(dict(Name='Public Subnet {}'.format(i))),
            ))

        public_route_table = template.add_resource(
            ec2.RouteTable(
                'PublicRouteTable{}'.format(i),
                VpcId=Ref(vpc),
            ))

        template.add_resource(
            ec2.SubnetRouteTableAssociation(
                'PublicRouteAssociation{}'.format(i),
                SubnetId=Ref(public_net),
                RouteTableId=Ref(public_route_table),
            ))

        template.add_resource(
            ec2.Route(
                'PublicDefaultRoute{}'.format(i),
                RouteTableId=Ref(public_route_table),
                DestinationCidrBlock='0.0.0.0/0',
                GatewayId=Ref(igw),
            ))

        template.add_output(
            Output('PublicSubnet{}'.format(i),
                   Value=Ref(public_subnet),
                   Description='Subnet Id'))

        if private_sub_net:
            private_subnet = template.add_parameter(
                Parameter(
                    'PrivateSubnetCidr{}'.format(i),
                    Type='String',
                    Description='Private Subnet CIDR',
                    Default=sub_net['private_cidr'],
                ))

            private_net = template.add_resource(
                ec2.Subnet(
                    'PrivateSubnet{}'.format(i),
                    CidrBlock=Ref(private_subnet),
                    MapPublicIpOnLaunch=False,
                    VpcId=Ref(vpc),
                    Tags=Tags(dict(Name='Private Subnet {}'.format(i))),
                ))

            private_route_table = template.add_resource(
                ec2.RouteTable(
                    'PrivateRouteTable{}'.format(i),
                    VpcId=Ref(vpc),
                ))

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PrivateRouteAssociation{}'.format(i),
                    SubnetId=Ref(private_net),
                    RouteTableId=Ref(private_route_table),
                ))

            template.add_output(
                Output('PrivateSubnet{}'.format(i),
                       Value=Ref(private_subnet),
                       Description='Subnet Id'))

        if nat_gateway and private_sub_net:
            nat_eip = template.add_resource(
                ec2.EIP(
                    'NatEip{}'.format(i),
                    Domain="vpc",
                ))

            nat = template.add_resource(
                ec2.NatGateway(
                    'Nat{}'.format(i),
                    AllocationId=GetAtt(nat_eip, 'AllocationId'),
                    SubnetId=Ref(public_net),
                ))

            template.add_resource(
                ec2.Route(
                    'NatRoute{}'.format(i),
                    RouteTableId=Ref(private_route_table),
                    DestinationCidrBlock='0.0.0.0/0',
                    NatGatewayId=Ref(nat),
                ))

            template.add_output(
                Output(
                    'NatEip{}'.format(i),
                    Value=Ref(nat_eip),
                    Description='Nat Elastic IP',
                ))

    write_json_to_file('vpc.json', template)
コード例 #14
0
    def add_resources(self):
        """ Add All Cloudformation Resources. This will include vpc, igw, and any other network
        resources """
        self.vpc = self.template.add_resource(
            ec2.VPC(
                "VPC",
                CidrBlock=Ref(self.VpcCidr),
                EnableDnsSupport=True,
                Tags=self.base_tags +
                Tags(Name=self.environment_parameters["ClientEnvironmentKey"] +
                     "-SS-VPC"),
            ))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.PubRT2Asocation = self.template.add_resource(
            ec2.SubnetRouteTableAssociation(
                "PubR2Associate",
                SubnetId=Ref(self.PubSubnet2),
                RouteTableId=Ref(self.PubRT2),
            ))
コード例 #15
0
def dump_lab_yaml(cfn_file):

    template = Template()

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

    ami_id_param = template.add_parameter(
        Parameter("AmiId",
                  Description="string of vpc cidr block to use",
                  Type="AWS::EC2::Image::Id"))

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

    sg = template.add_resource(
        ec2.SecurityGroup(
            "MySg",
            GroupDescription="who cares",
            VpcId=ImportValue("VpcId-jdix"),
            Tags=resource_tags,
        ))

    sshIn = template.add_resource(
        ec2.SecurityGroupIngress("MySshIn",
                                 CidrIp="0.0.0.0/0",
                                 IpProtocol="tcp",
                                 FromPort=22,
                                 ToPort=22,
                                 GroupId=Ref(sg)))

    pingIn = template.add_resource(
        ec2.SecurityGroupIngress("MyPingIn",
                                 CidrIp="0.0.0.0/0",
                                 IpProtocol="icmp",
                                 FromPort=-1,
                                 ToPort=-1,
                                 GroupId=Ref(sg)))

    instance = template.add_resource(
        ec2.Instance(
            "MyInstance",
            ImageId=Ref(ami_id_param),
            SubnetId=ImportValue("SubnetId-jdix"),
            InstanceType=Ref(instance_type_param),
            KeyName=Ref(key_name_param),
            Tags=resource_tags,
            SecurityGroupIds=[Ref(sg)],
        ))

    priv_instance = template.add_resource(
        ec2.Instance(
            "MyPrivInstance",
            ImageId=Ref(ami_id_param),
            SubnetId=ImportValue("PrivSubnetId-jdix"),
            InstanceType=Ref(instance_type_param),
            KeyName=Ref(key_name_param),
            Tags=resource_tags,
            SecurityGroupIds=[Ref(sg)],
        ))

    instance_elastic_ip = template.add_resource(
        ec2.EIP(
            "MyEip",
            InstanceId=Ref(instance),
            Tags=resource_tags,
        ))

    template.add_output([
        Output(
            "InstanceId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(instance),
            Export=Export("InstanceId-jdix"),
        ),
        Output(
            "InstancePrivateIP",
            Description="InstanceId of the newly created EC2 instance",
            Value=GetAtt(instance, "PrivateIp"),
            Export=Export("InstancePrivateIP-jdix"),
        )
    ])
    template_out_yaml(cfn_file, template)
コード例 #16
0
def dump_base_yaml(cfn_file):

    template = Template()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
        Output(
            "PrivSubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(priv_subnet),
            Export=Export("PrivSubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
コード例 #17
0
ファイル: bastion.py プロジェクト: visudo-com/aws-web-stacks
database_security_group_bastion_ingress = ec2.SecurityGroupIngress(
    'DatabaseSecurityGroupBastionIngress',
    template=template,
    GroupId=Ref("DatabaseSecurityGroup"),
    IpProtocol="tcp",
    FromPort=FindInMap("RdsEngineMap", Ref("DatabaseEngine"), "Port"),
    ToPort=FindInMap("RdsEngineMap", Ref("DatabaseEngine"), "Port"),
    SourceSecurityGroupId=Ref(bastion_security_group),
    Description="Bastion Access",
    Condition=bastion_database_condition,
)

# Elastic IP for Bastion instance
bastion_eip = ec2.EIP(
    "BastionEIP",
    template=template,
    Condition=bastion_type_set,
    Domain="vpc",
)

bastion_instance = ec2.Instance(
    "BastionInstance",
    template=template,
    ImageId=Ref(bastion_ami),
    InstanceType=Ref(bastion_instance_type),
    KeyName=Ref(bastion_key_name),
    SecurityGroupIds=[Ref(bastion_security_group)],
    SubnetId=Ref(public_subnet_a),
    BlockDeviceMappings=[
        ec2.BlockDeviceMapping(
            DeviceName="/dev/sda1",
            Ebs=ec2.EBSBlockDevice(
コード例 #18
0
ファイル: ssm_network.py プロジェクト: thawkins83/ssm-ansible
def ssm_network():
    template = Template()

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

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

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

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

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

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

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

    ssm_ig = ec2.InternetGateway(
        'SsmIG',
    )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return template.to_yaml()
コード例 #19
0
        ec2.SecurityGroupRule(
            IpProtocol='tcp',
            FromPort=80,
            ToPort=80,
            CidrIp='0.0.0.0/0',
        ),
        ec2.SecurityGroupRule(
            IpProtocol='tcp',
            FromPort=443,
            ToPort=443,
            CidrIp='0.0.0.0/0',
        ),
    ]
))

eip = template.add_resource(ec2.EIP("Eip"))

ec2_instance = template.add_resource(ec2.Instance(
    'Ec2Instance',
    ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
    InstanceType=Ref(instance_type),
    KeyName=Ref(key_name),
    SecurityGroups=[Ref(security_group)],
    BlockDeviceMappings=[
        ec2.BlockDeviceMapping(
            DeviceName="/dev/sda1",
            Ebs=ec2.EBSBlockDevice(
                VolumeSize=Ref(root_size),
            )
        ),
    ],
コード例 #20
0
    def add_resources(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

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

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

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

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

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

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

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

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

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

            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PubSubnet%iRTAssoc' % (i + 1),
                    Condition='PublicAZ%i' % (i + 1),
                    RouteTableId=Ref(publicroutetable),
                    SubnetId=Ref('PubSubnet%i' % (i + 1))))
            template.add_resource(
                ec2.SubnetRouteTableAssociation(
                    'PriSubnet%iRTAssoc' % (i + 1),
                    Condition='PrivateAZ%i' % (i + 1),
                    RouteTableId=Ref('PrivateRouteTable%i' % (i + 1)),
                    SubnetId=Ref('PriSubnet%i' % (i + 1))))
コード例 #21
0
ファイル: pritunl.py プロジェクト: nxtlytics/ivy-rain
    def configure(self):
        """
        Returns a Pritunl template
        """
        self.defaults = {'instance_type': 't3.large'}

        self.service = 'pritunl'
        self.set_description('Sets up Pritunl servers')
        self.get_default_security_groups()
        self.get_standard_parameters()
        self.get_standard_policies()

        _vpn_config = constants.ENVIRONMENTS[self.env]['pritunl']
        _global_config = constants.ENVIRONMENTS[self.env]
        _bootstrap_mode = _vpn_config.get('bootstrap_mode', False)

        _bootstrap_ami = get_latest_ami_id(
            self.region, 'amzn2-ami-hvm-2.0.????????-x86_64-gp2', 'amazon')
        _ivy_ami = get_latest_ami_id(self.region, 'ivy-base',
                                     _global_config.get('ami_owner', 'self'))

        self.ami = self.add_parameter(
            Parameter('AMI',
                      Type='String',
                      Description='AMI ID for instances',
                      Default=_bootstrap_ami if _bootstrap_mode else _ivy_ami))

        _public_dns = _vpn_config['public_dns']

        _vpn_name = '{}Pritunl'.format(self.env)

        # We want the preferred subnet only.
        _vpn_subnet = self.get_subnets('public', _preferred_only=True)[0]

        # Add our security group
        _vpn_security_group = self.add_resource(
            ec2.SecurityGroup(
                '{}SecurityGroup'.format(_vpn_name),
                VpcId=self.vpc_id,
                GroupDescription='Security Group for Pritunl {}'.format(
                    _vpn_name),
                SecurityGroupIngress=[
                    {
                        "IpProtocol": "icmp",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": "0.0.0.0/0"
                    },  # Ping
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "80",
                        "ToPort": "80",
                        "CidrIp": "0.0.0.0/0"
                    },  # HTTP
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "443",
                        "ToPort": "443",
                        "CidrIp": "0.0.0.0/0"
                    },  # HTTPS
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "22",
                        "ToPort": "22",
                        "CidrIp": "0.0.0.0/0"
                    },  # SSH
                    {
                        "IpProtocol": "udp",
                        "FromPort": "10000",
                        "ToPort": "20000",
                        "CidrIp": "0.0.0.0/0"
                    },  # HTTPS/OVPN
                    {
                        "IpProtocol": "tcp",
                        "FromPort": "27017",
                        "ToPort": "27017",
                        "CidrIp": constants.SUPERNET
                    },  # mongodb master
                    {
                        "IpProtocol": "-1",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": constants.SUPERNET
                    }  # Replies from local VPC
                ],
                SecurityGroupEgress=[{
                    "IpProtocol": "-1",
                    "FromPort": "-1",
                    "ToPort": "-1",
                    "CidrIp": "0.0.0.0/0"
                }]))

        # Add EBS volume if local mongo used
        _data_volume = None
        if _vpn_config.get('local_mongo', False):
            self.add_iam_policy(
                iam.Policy(
                    PolicyName='AttachVolume',
                    PolicyDocument={
                        'Statement': [{
                            'Effect':
                            'Allow',
                            'Resource':
                            '*',
                            'Action': [
                                'ec2:AttachVolume', 'ec2:DeleteSnapshot',
                                'ec2:DescribeTags',
                                'ec2:DescribeVolumeAttribute',
                                'ec2:DescribeVolumeStatus',
                                'ec2:DescribeVolumes', 'ec2:DetachVolume'
                            ]
                        }]
                    }))
            _data_volume = ec2.Volume(
                '{}DataVolume'.format(_vpn_name),
                Size=_vpn_config.get('data_volume_size', 20),
                VolumeType='gp2',
                AvailabilityZone=_vpn_subnet['AvailabilityZone'],
                DeletionPolicy='Retain',
                Tags=self.get_tags(service_override=self.service,
                                   role_override=_vpn_name) +
                [ec2.Tag('Name', _vpn_name + "-datavol")])
            self.add_resource(_data_volume)

        # Add the elastic IP and the ENI for it, then attach it.
        _vpn_eip = self.add_resource(
            ec2.EIP('{}InstanceEIP'.format(_vpn_name), Domain='vpc'))
        _vpn_eni = self.add_resource(
            ec2.NetworkInterface(
                '{}InstanceENI'.format(_vpn_name),
                SubnetId=_vpn_subnet['SubnetId'],
                Description='ENI for {}'.format(_vpn_name),
                GroupSet=[Ref(_vpn_security_group)] + self.security_groups,
                SourceDestCheck=False,
                Tags=self.get_tags(service_override=self.service,
                                   role_override=_vpn_name)))
        self.get_eni_policies()

        self.add_resource(
            ec2.EIPAssociation('{}AssociateVPNInstanceENI'.format(_vpn_name),
                               AllocationId=GetAtt(_vpn_eip, "AllocationId"),
                               NetworkInterfaceId=Ref(_vpn_eni)))

        # Add a route53 DNS name
        if self.get_partition() != 'aws-us-gov':
            self.add_resource(
                route53.RecordSetGroup('{}Route53'.format(_vpn_name),
                                       HostedZoneName=constants.ENVIRONMENTS[
                                           self.env]['route53_zone'],
                                       RecordSets=[
                                           route53.RecordSet(
                                               Name=_public_dns,
                                               ResourceRecords=[Ref(_vpn_eip)],
                                               Type='A',
                                               TTL=600)
                                       ]))

        # Get all route tables in the VPC
        _vpc_route_tables = self.ec2_conn.describe_route_tables(
            Filters=[{
                'Name': 'vpc-id',
                'Values': [self.vpc_id]
            }])['RouteTables']

        # Set up the routing table for the VPC
        # Allow for changing client subnets in constants.py
        for client_subnet in _vpn_config['client_subnets']:
            for route_table in _vpc_route_tables:
                self.add_resource(
                    ec2.Route('{}Route{}{}'.format(
                        _vpn_name,
                        client_subnet.translate({
                            ord("."): "",
                            ord("/"): ""
                        }), route_table['RouteTableId'].replace('-', '')),
                              RouteTableId=route_table['RouteTableId'],
                              DestinationCidrBlock=client_subnet,
                              NetworkInterfaceId=Ref(_vpn_eni)))

        _mongodb = _vpn_config.get('mongodb')
        _server_id = _vpn_config['server_id']

        _userdata_template = self.get_cloudinit_template(
            _tpl_name="pritunl_bootstrap" if _bootstrap_mode else None,
            replacements=(('__PROMPT_COLOR__', self.prompt_color()),
                          ('__SERVER_ID__', _server_id), ('__SERVICE__',
                                                          self.service),
                          ('__MONGODB__', _mongodb if _mongodb else '')))

        _userdata = Sub(
            _userdata_template.replace(
                '${', '${!')  # Replace bash brackets with CFN escaped style
            .replace(
                '{#', '${'
            ),  # Replace rain-style CFN escapes with proper CFN brackets
            {
                'CFN_ENI_ID': Ref(_vpn_eni),
                'CFN_EBS_ID': Ref(_data_volume) if _data_volume else ''
            })

        _vpn_launch_configuration = self.add_resource(
            autoscaling.LaunchConfiguration(
                '{}LaunchConfiguration'.format(_vpn_name),
                AssociatePublicIpAddress=True,
                KeyName=Ref(self.keypair_name),
                ImageId=Ref(self.ami),
                InstanceType=Ref(self.instance_type),
                InstanceMonitoring=False,
                IamInstanceProfile=Ref(self.instance_profile),
                UserData=Base64(_userdata)))
        self.add_resource(
            autoscaling.AutoScalingGroup(
                '{}ASGroup'.format(_vpn_name),
                AvailabilityZones=[_vpn_subnet['AvailabilityZone']],
                HealthCheckType='EC2',
                LaunchConfigurationName=Ref(_vpn_launch_configuration),
                MinSize=0,
                MaxSize=1,
                VPCZoneIdentifier=[_vpn_subnet['SubnetId']],
                Tags=self.get_autoscaling_tags(service_override=self.service,
                                               role_override=_vpn_name) +
                [autoscaling.Tag('Name', _vpn_name, True)]))
コード例 #22
0
    def add_resources_and_outputs(self):
        """Add resources to template."""
        template = self.template
        variables = self.get_variables()

        ec2networkinterface = template.add_resource(
            ec2.NetworkInterface(
                'Ec2NetworkInterface',
                Description=variables['Description'].ref,
                GroupSet=variables['SecurityGroupIds'].ref,
                SecondaryPrivateIpAddressCount=variables[
                    'SecondaryAddressCount'],
                SourceDestCheck=variables['SourceDestCheck'].ref,
                SubnetId=variables['SubnetId'].ref,
                Tags=Tags(variables['Tags']),
            )
        )

        template.add_output(
            Output(
                '{}Id'.format(ec2networkinterface.title),
                Description='ID of the EC2 Network Interface created',
                Export=Export(
                    Sub('${AWS::StackName}-%sId' % ec2networkinterface.title)
                ),
                Value=Ref(ec2networkinterface)
            )
        )

        template.add_output(
            Output(
                '{}PrimaryPrivateIp'.format(ec2networkinterface.title),
                Description='Primary Private IP of the EC2 Network Interface',
                Export=Export(
                    Sub('${AWS::StackName}-%sPrimaryPrivateIp'
                        % ec2networkinterface.title)
                ),
                Value=GetAtt(
                    ec2networkinterface, 'PrimaryPrivateIpAddress')
            )
        )

        for i in range(variables['SecondaryAddressCount']):
            template.add_output(
                Output(
                    '{}SecondaryPrivateIp{}'.format(
                        ec2networkinterface.title, i+1),
                    Description='Secondary Private IP {} of'
                                ' the EC2 Network Interface'.format(i+1),
                    Export=Export(
                        Sub('${AWS::StackName}-%sSecondaryPrivateIp%i'
                            % (ec2networkinterface.title, i+1))
                    ),
                    Value=Select(i, GetAtt(
                        ec2networkinterface, 'SecondaryPrivateIpAddresses')
                    )
                )
            )

        if variables['AttachEip']:
            # allocate and output an EIP for the primary private IP
            primaryeip = template.add_resource(
                ec2.EIP(
                    'Ec2EipPrimary',
                    Domain='vpc',
                )
            )
            template.add_output(
                Output(
                    '{}PrimaryPublicIp'.format(ec2networkinterface.title),
                    Description='Primary Public IP of'
                                ' the EC2 Network Interface',
                    Export=Export(
                        Sub('${AWS::StackName}-%sPrimaryPublicIp'
                            % ec2networkinterface.title)
                    ),
                    Value=Ref(primaryeip)
                )
            )
            # associate it to the primary private IP
            template.add_resource(
                ec2.EIPAssociation(
                    'Ec2EipPrimaryAssociation',
                    AllocationId=GetAtt(primaryeip, 'AllocationId'),
                    NetworkInterfaceId=Ref(ec2networkinterface),
                    PrivateIpAddress=GetAtt(
                        ec2networkinterface, 'PrimaryPrivateIpAddress'),
                )
            )

            # allocate and output EIP(s) for any secondary private IPs
            for i in range(variables['SecondaryAddressCount']):
                # allocate and output an EIP for a secondary private IP
                secondaryeip = template.add_resource(
                    ec2.EIP(
                        'Ec2EipSecondary{}'.format(i+1),
                        Domain='vpc',
                    )
                )
                template.add_output(
                    Output(
                        '{}SecondaryPublicIp{}'.format(
                            ec2networkinterface.title, i+1),
                        Description='Secondary Public IP {} of'
                                    ' the EC2 Network Interface'.format(i+1),
                        Export=Export(
                            Sub('${AWS::StackName}-%sSecondaryPublicIp%i'
                                % (ec2networkinterface.title, i+1))
                        ),
                        Value=Ref(secondaryeip)
                    )
                )
                # associate it to a secondary private IP
                template.add_resource(
                    ec2.EIPAssociation(
                        'Ec2EipSecondaryAssociation{}'.format(i+1),
                        AllocationId=GetAtt(secondaryeip, 'AllocationId'),
                        NetworkInterfaceId=Ref(ec2networkinterface),
                        PrivateIpAddress=Select(i, GetAtt(
                            ec2networkinterface, 'SecondaryPrivateIpAddresses')
                        )
                    )
                )
コード例 #23
0
def create():
    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   passwd="AmazingTheory62",
                                   database="cloud_formation")

    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM ec2_table")
    myresult = (mycursor.fetchone())
    sname = myresult[0]
    name = myresult[1]
    region = myresult[2]
    itype = myresult[3]
    vpc1 = myresult[4]
    subnet1 = myresult[5]

    #print(type(vpc1))

    template = Template()

    keyname_param = template.add_parameter(
        Parameter("KeyName",
                  Description="Name of an existing EC2 KeyPair to enable SSH "
                  "access to the instance",
                  Type="String",
                  Default="jayaincentiuskey"))

    vpcid_param = template.add_parameter(
        Parameter(
            "VpcId",
            Description="VpcId of your existing Virtual Private Cloud (VPC)",
            Type="String",
            Default=vpc1))

    subnetid_param = template.add_parameter(
        Parameter(
            "SubnetId",
            Description=
            "SubnetId of an existing subnet (for the primary network) in "
            "your Virtual Private Cloud (VPC)"
            "access to the instance",
            Type="String",
            Default=subnet1))

    secondary_ip_param = template.add_parameter(
        Parameter(
            "SecondaryIPAddressCount",
            Description=
            "Number of secondary IP addresses to assign to the network "
            "interface (1-5)",
            ConstraintDescription="must be a number from 1 to 5.",
            Type="Number",
            Default="1",
            MinValue="1",
            MaxValue="5",
        ))

    sshlocation_param = template.add_parameter(
        Parameter(
            "SSHLocation",
            Description="The IP address range that can be used to SSH to the "
            "EC2 instances",
            Type="String",
            MinLength="9",
            MaxLength="18",
            Default="0.0.0.0/0",
            AllowedPattern="(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"
            "/(\\d{1,2})",
            ConstraintDescription="must be a valid IP CIDR range of the "
            "form x.x.x.x/x."))

    template.add_mapping('RegionMap', {"us-west-2": {"AMI": region}})

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

    ssh_sg = template.add_resource(
        ec2.SecurityGroup(
            "SSHSecurityGroup",
            VpcId=Ref(vpcid_param),
            GroupDescription="Enable SSH access via port 22",
            SecurityGroupIngress=[
                ec2.SecurityGroupRule(
                    IpProtocol="tcp",
                    FromPort="22",
                    ToPort="22",
                    CidrIp=Ref(sshlocation_param),
                ),
            ],
        ))

    eth0 = template.add_resource(
        ec2.NetworkInterface(
            "Eth0",
            Description="eth0",
            GroupSet=[
                Ref(ssh_sg),
            ],
            SourceDestCheck=True,
            SubnetId=Ref(subnetid_param),
            Tags=Tags(
                Name="Interface 0",
                Interface="eth0",
            ),
            SecondaryPrivateIpAddressCount=Ref(secondary_ip_param),
        ))

    # eipassoc1 = template.add_resource(ec2.EIPAssociation(
    #     "EIPAssoc1",
    #     NetworkInterfaceId=Ref(eth0),
    #     AllocationId=GetAtt("EIP1", "AllocationId"),
    #     PrivateIpAddress=GetAtt("Eth0", "PrimaryPrivateIpAddress"),
    # ))

    ec2_instance = template.add_resource(
        ec2.Instance("EC2Instance",
                     ImageId=FindInMap("RegionMap", Ref("AWS::Region"), "AMI"),
                     InstanceType=itype,
                     KeyName=Ref(keyname_param),
                     NetworkInterfaces=[
                         ec2.NetworkInterfaceProperty(
                             NetworkInterfaceId=Ref(eth0),
                             DeviceIndex="0",
                         ),
                     ],
                     Tags=Tags(Name=name, )))

    template.add_output([
        Output(
            "InstanceId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(ec2_instance),
        ),
        Output(
            "EIP1",
            Description="Primary public IP address for Eth0",
            Value=Join(
                " ",
                ["IP address",
                 Ref(eip1), "on subnet",
                 Ref(subnetid_param)]),
        ),
        Output(
            "PrimaryPrivateIPAddress",
            Description="Primary private IP address of Eth0",
            Value=Join(" ", [
                "IP address",
                GetAtt("Eth0", "PrimaryPrivateIpAddress"), "on subnet",
                Ref(subnetid_param)
            ]),
        ),
        Output(
            "FirstSecondaryPrivateIPAddress",
            Description="First secondary private IP address of Eth0",
            Value=Join(" ", [
                "IP address",
                Select("0", GetAtt("Eth0", "SecondaryPrivateIpAddresses")),
                "on subnet",
                Ref(subnetid_param)
            ]),
        ),
    ])

    print(template.to_json())
    file = open('ec2json.json', 'w')
    file.write(template.to_json())
    file.close()
    os.system('aws cloudformation create-stack --stack-name ' + sname +
              ' --template-body file://ec2json.json')
コード例 #24
0
ファイル: vpc.py プロジェクト: ath-rja/AwsIBox
    def __init__(self, key):
        vpc_net = '10.80'
        o_subnetprivate = []
        o_subnetpublic = []

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

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

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

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

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

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

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

            R_RouteNatGateway = EC2RouteNatGateway('RouteNatGateway')

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

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

        R_RouteInternetGateway = EC2RouteInternetGateway(
            'RouteInternetGateway')

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

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

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

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

            add_obj([
                p_SubnetCidrBlockPrivate,
                p_SubnetCidrBlockPublic,
            ])

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

            add_obj(c_Zone)

            # resources

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

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

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

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

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

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

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

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

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

        add_obj([
            O_SubnetsPrivate,
            O_SubnetsPublic,
        ])
コード例 #25
0
                                      ToPort='8000',
                                      CidrIp='0.0.0.0/0'),
            ]))

    for m in range(0, NUMBER_OF_MACHINES):

        ec2_instance = template.add_resource(
            ec2.Instance(("EC2Instance%d" % m),
                         ImageId=IMAGE_ID,
                         InstanceType=INSTANCE_TYPE,
                         KeyName=KEY_PAIR_NAME,
                         SecurityGroups=[Ref(security_group)],
                         UserData=get_user_data()))

        eip = template.add_resource(
            ec2.EIP(("EIP%d" % m), InstanceId=Ref(ec2_instance)))

        template.add_output([
            Output(
                ("%dInstanceID" % m),
                Description="Instance ID of the newly created EC2 instance",
                Value=Ref(ec2_instance),
            ),
            Output(
                ("%dPublicIP" % m),
                Description=
                "Public IP address of the newly created EC2 instance",
                Value=GetAtt(ec2_instance, "PublicIp"),
            ),
            Output(
                ("%dPublicDNS" % m),
コード例 #26
0
def dump_base_yaml(cfn_file):

    template = Template()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    template.add_output([
        Output(
            "VpcId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(vpc),
            Export=Export("VpcId-jdix"),
        ),
        Output(
            "SubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(subnet),
            Export=Export("SubnetId-jdix"),
        ),
        Output(
            "PrivSubnetId",
            Description="InstanceId of the newly created EC2 instance",
            Value=Ref(priv_subnet),
            Export=Export("PrivSubnetId-jdix"),
        ),
    ])
    template_out_yaml(cfn_file, template)
コード例 #27
0
]

instance = ec2.Instance("ec2instance", ImageId="ami-cd0f5cb6", InstanceType="t2.micro")
instance.SecurityGroups = [Ref(securityGroup)]
instance.KeyName = Ref(keyName)
instance.BlockDeviceMappings = [
    ec2.BlockDeviceMapping(
        DeviceName='/dev/sda1',
        Ebs=ec2.EBSBlockDevice(
            VolumeSize=30
        )
    )
]
instance.Tags = [ec2.Tag('Name', Ref(name))]

ipAddress = ec2.EIP('IPAddress')
ipAssociation = ec2.EIPAssociation(
    'EIPAssociation',
    InstanceId=Ref(instance),
    EIP=Ref(ipAddress)
)

# It would be nice to generate the route53 record here as well, but a
# different account has the Hosted Zone configured :(

t.add_resource(instance)
t.add_resource(securityGroup)
t.add_resource(ipAddress)
t.add_resource(ipAssociation)
t.add_output(Output('InstanceId',
    Description='InstanceId of the newly created EC2 instance',
コード例 #28
0
    def configure(self):
        """
        Returns a vpn template
        """
        self.defaults = {'instance_type': 't2.small'}

        self.service = 'vpn'
        self.add_description('Sets up VPNs')
        self.get_eni_policies()
        self.get_default_security_groups()
        self.get_standard_parameters()
        self.get_standard_policies()
        self.ami = self.add_parameter(
            Parameter('AMI',
                      Type='String',
                      Description='AMI ID for instances',
                      Default=get_latest_ami_id(
                          self.region, 'amzn2-ami-hvm-2.0.????????-x86_64-gp2',
                          'amazon')))

        # Custom config per VPN
        for vpn in constants.ENVIRONMENTS[self.env]['vpn']:
            if not vpn['active']:
                continue
            _vpn_name = vpn['name']
            _vpn_subnet = self.get_subnets('public', _preferred_only=True)[0]
            _role = 'vpn-{}'.format(_vpn_name)

            _vpn_security_group = self.add_resource(
                ec2.SecurityGroup(
                    self.cfn_name('VPNSecurityGroup', _vpn_name),
                    VpcId=self.vpc_id,
                    GroupDescription='Security Group for VPN {}'.format(
                        _vpn_name),
                    SecurityGroupIngress=[{
                        "IpProtocol": "50",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "51",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "udp",
                        "FromPort": "500",
                        "ToPort": "500",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "udp",
                        "FromPort": "4500",
                        "ToPort": "4500",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "icmp",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": "0.0.0.0/0"
                    }, {
                        "IpProtocol": "-1",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": constants.SUPERNET
                    }],
                    SecurityGroupEgress=[{
                        "IpProtocol": "50",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "51",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "udp",
                        "FromPort": "500",
                        "ToPort": "500",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "udp",
                        "FromPort": "4500",
                        "ToPort": "4500",
                        "CidrIp": vpn['remote_ip'] + '/32'
                    }, {
                        "IpProtocol": "tcp",
                        "FromPort": "80",
                        "ToPort": "80",
                        "CidrIp": "0.0.0.0/0"
                    }, {
                        "IpProtocol": "tcp",
                        "FromPort": "443",
                        "ToPort": "443",
                        "CidrIp": "0.0.0.0/0"
                    }, {
                        "IpProtocol": "udp",
                        "FromPort": "123",
                        "ToPort": "123",
                        "CidrIp": "0.0.0.0/0"
                    }, {
                        "IpProtocol": "icmp",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": "0.0.0.0/0"
                    }, {
                        "IpProtocol": "-1",
                        "FromPort": "-1",
                        "ToPort": "-1",
                        "CidrIp": constants.SUPERNET
                    }]))
            _vpn_eip = self.add_resource(
                ec2.EIP(self.cfn_name('VPNInstanceEIP', _vpn_name),
                        Domain='vpc'))
            _vpn_eni = self.add_resource(
                ec2.NetworkInterface(
                    self.cfn_name('VPNInstanceENI', _vpn_name),
                    SubnetId=_vpn_subnet['SubnetId'],
                    Description='ENI for VPN - {}'.format(_vpn_name),
                    GroupSet=[Ref(_vpn_security_group)] + self.security_groups,
                    SourceDestCheck=False,
                    Tags=self.get_tags(role_override=_role)))
            self.add_resource(
                ec2.EIPAssociation(self.cfn_name('AssociateVPNInstanceENI',
                                                 _vpn_name),
                                   AllocationId=GetAtt(_vpn_eip,
                                                       "AllocationId"),
                                   NetworkInterfaceId=Ref(_vpn_eni)))
            # Set up Routes from all VPC subnets to the ENI
            _vpc_route_tables = self.ec2_conn.describe_route_tables(
                Filters=[{
                    'Name': 'vpc-id',
                    'Values': [self.vpc_id]
                }])['RouteTables']

            _local_subnets = iter(
                map(
                    lambda x: constants.ENVIRONMENTS[x]['vpc']['cidrblock'],
                    filter(lambda z: z in vpn.get('local_envs', []),
                           constants.ENVIRONMENTS.keys())))
            _local_subnets = list(
                itertools.chain(_local_subnets, [
                    self.vpc_metadata['cidrblock'],
                ]))

            # append remote vpc subnets
            _remote_subnets = iter(
                map(
                    lambda x: constants.ENVIRONMENTS[x]['vpc']['cidrblock'],
                    filter(lambda z: z in vpn.get('remote_envs', []),
                           constants.ENVIRONMENTS.keys())))
            _remote_subnets = list(
                itertools.chain(_remote_subnets, vpn.get('remote_subnets',
                                                         [])))

            for remote_subnet in _remote_subnets:
                for route_table in _vpc_route_tables:
                    self.add_resource(
                        ec2.Route(self.cfn_name(_vpn_name, "VPNRoute",
                                                remote_subnet,
                                                route_table['RouteTableId']),
                                  RouteTableId=route_table['RouteTableId'],
                                  DestinationCidrBlock=remote_subnet,
                                  NetworkInterfaceId=Ref(_vpn_eni)))

            _user_data_template = self.get_cloudinit_template(replacements=(
                ('__PROMPT_COLOR__',
                 self.prompt_color()), ('__LOCAL_SUBNETS__',
                                        ','.join(sorted(_local_subnets))),
                ('__REMOTE_IP__',
                 vpn['remote_ip']), ('__REMOTE_SUBNETS__',
                                     ','.join(sorted(_remote_subnets))),
                ('__SECRET__',
                 vpn['secret']), ('__IKE__',
                                  vpn.get('ike', 'aes256-sha1-modp1536')),
                ('__IKE_LIFETIME__', vpn.get('ikelifetime', '28800s')),
                ('__ESP__',
                 vpn.get('esp', 'aes256-sha1')), ('__KEYLIFE__',
                                                  vpn.get('keylife', '1800s')),
                ('__IPTABLES_RULES__',
                 '\n'.join(vpn.get('iptables_rules', ''))),
                ('__SERVICE__', self.service), ('__VPN_NAME__', _vpn_name),
                ('__TAG__', _vpn_name.lower()), ('__VPC_ID__', self.vpc_id)))
            _user_data = Sub(
                _user_data_template.replace(
                    '${',
                    '${!')  # Replace bash brackets with CFN escaped style
                .replace(
                    '{#', '${'
                ),  # Replace rain-style CFN escapes with proper CFN brackets,
                {
                    'CFN_EIP_ADDR': Ref(_vpn_eip),
                    'CFN_ENI_ID': Ref(_vpn_eni),
                })

            _vpn_launch_configuration = self.add_resource(
                autoscaling.LaunchConfiguration(
                    self.cfn_name('VPNLaunchConfiguration', _vpn_name),
                    AssociatePublicIpAddress=True,
                    KeyName=Ref(self.keypair_name),
                    ImageId=Ref(self.ami),
                    InstanceType=Ref(self.instance_type),
                    InstanceMonitoring=False,
                    IamInstanceProfile=Ref(self.instance_profile),
                    UserData=Base64(_user_data)))
            self.add_resource(
                autoscaling.AutoScalingGroup(
                    self.cfn_name('VPNASGroup', _vpn_name),
                    AvailabilityZones=[_vpn_subnet['AvailabilityZone']],
                    HealthCheckType='EC2',
                    LaunchConfigurationName=Ref(_vpn_launch_configuration),
                    MinSize=1,
                    MaxSize=1,
                    DesiredCapacity=1,
                    VPCZoneIdentifier=[_vpn_subnet['SubnetId']],
                    Tags=self.get_autoscaling_tags(role_override=_role) +
                    [autoscaling.Tag('Name', _role, True)]))
コード例 #29
0
ファイル: NatGateway.py プロジェクト: zhnc/troposphere
    ec2.Route(
        'PublicDefaultRoute',
        RouteTableId=Ref(public_route_table),
        DestinationCidrBlock='0.0.0.0/0',
        GatewayId=Ref(igw),
    ))

private_route_association = t.add_resource(
    ec2.SubnetRouteTableAssociation(
        'PrivateRouteAssociation',
        SubnetId=Ref(private_net),
        RouteTableId=Ref(private_route_table),
    ))

nat_eip = t.add_resource(ec2.EIP(
    'NatEip',
    Domain="vpc",
))

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

t.add_resource(
    ec2.Route(
        'NatRoute',
        RouteTableId=Ref(private_route_table),
        DestinationCidrBlock='0.0.0.0/0',
        NatGatewayId=Ref(nat),
コード例 #30
0
    def add_public_subnet_group(
        self,
        name_prefix: str,
        cidr_block: str,
        no_of_subnets: int = 4,
        create_nat_gateways: bool = False,
    ):
        """Create public subnets and, optionally, NAT Gateways

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