Create dns entries in route53 for multiregion failover setups.

        Args:
            primary_region (str): primary AWS region for failover
        Returns:
            Auto-generated DNS name.
323630
def create_failover_dns(self, primary_region='us-east-1'):
        
        dns_record = self.generated.dns()['global']
        zone_ids = get_dns_zone_ids(env=self.env, facing=self.elb_subnet)

        elb_dns_aws = find_elb(name=self.app_name, env=self.env, region=self.region)
        elb_dns_zone_id = find_elb_dns_zone_id(name=self.app_name, env=self.env, region=self.region)

        if primary_region in elb_dns_aws:
            failover_state = 'PRIMARY'
        else:
            failover_state = 'SECONDARY'
        self.log.info("%s set as %s record", elb_dns_aws, failover_state)

        self.log.info('Updating Application Failover URL: %s', dns_record)

        dns_kwargs = {
            'dns_name': dns_record,
            'elb_dns_zone_id': elb_dns_zone_id,
            'elb_aws_dns': elb_dns_aws,
            'dns_ttl': self.dns_ttl,
            'failover_state': failover_state,
        }

        for zone_id in zone_ids:
            self.log.debug('zone_id: %s', zone_id)
            update_failover_dns_record(self.env, zone_id, **dns_kwargs)

        return dns_record
1321360
def create_domain_name(self,
                           domain_name,
                           certificate_name,
                           certificate_body=None,
                           certificate_private_key=None,
                           certificate_chain=None,
                           certificate_arn=None,
                           lambda_name=None,
                           stage=None,
                           base_path=None):
        

        # This is a Let's Encrypt or custom certificate
        if not certificate_arn:
            agw_response = self.apigateway_client.create_domain_name(
                domainName=domain_name,
                certificateName=certificate_name,
                certificateBody=certificate_body,
                certificatePrivateKey=certificate_private_key,
                certificateChain=certificate_chain
            )
        # This is an AWS ACM-hosted Certificate
        else:
            agw_response = self.apigateway_client.create_domain_name(
                domainName=domain_name,
                certificateName=certificate_name,
                certificateArn=certificate_arn
            )

        api_id = self.get_api_id(lambda_name)
        if not api_id:
            raise LookupError("No API URL to certify found - did you deploy?")

        self.apigateway_client.create_base_path_mapping(
            domainName=domain_name,
            basePath='' if base_path is None else base_path,
            restApiId=api_id,
            stage=stage
        )

        return agw_response['distributionDomainName']
248789
def cli(env, identifier, a_record, aaaa_record, ptr, ttl):
    """"""

    items = ['id',
             'globalIdentifier',
             'fullyQualifiedDomainName',
             'hostname',
             'domain',
             'primaryBackendIpAddress',
             'primaryIpAddress',
             '''primaryNetworkComponent[
                id, primaryIpAddress,
                primaryVersion6IpAddressRecord[ipAddress]
             ]''']
    mask = "mask[%s]" % ','.join(items)
    dns = SoftLayer.DNSManager(env.client)
    vsi = SoftLayer.VSManager(env.client)

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    instance = vsi.get_instance(vs_id, mask=mask)
    zone_id = helpers.resolve_id(dns.resolve_ids,
                                 instance['domain'],
                                 name='zone')

    def sync_a_record():
        """Sync A record."""
        records = dns.get_records(zone_id,
                                  host=instance['hostname'],
                                  record_type='a')
        if not records:
            # don't have a record, lets add one to the base zone
            dns.create_record(zone['id'],
                              instance['hostname'],
                              'a',
                              instance['primaryIpAddress'],
                              ttl=ttl)
        else:
            if len(records) != 1:
                raise exceptions.CLIAbort("Aborting A record sync, found "
                                          "%d A record exists!" % len(records))
            rec = records[0]
            rec['data'] = instance['primaryIpAddress']
            rec['ttl'] = ttl
            dns.edit_record(rec)

    def sync_aaaa_record():
        """Sync AAAA record."""
        records = dns.get_records(zone_id,
                                  host=instance['hostname'],
                                  record_type='aaaa')
        try:
            # done this way to stay within 80 character lines
            component = instance['primaryNetworkComponent']
            record = component['primaryVersion6IpAddressRecord']
            ip_address = record['ipAddress']
        except KeyError:
            raise exceptions.CLIAbort("%s does not have an ipv6 address"
                                      % instance['fullyQualifiedDomainName'])

        if not records:
            # don't have a record, lets add one to the base zone
            dns.create_record(zone['id'],
                              instance['hostname'],
                              'aaaa',
                              ip_address,
                              ttl=ttl)
        else:
            if len(records) != 1:
                raise exceptions.CLIAbort("Aborting A record sync, found "
                                          "%d A record exists!" % len(records))
            rec = records[0]
            rec['data'] = ip_address
            rec['ttl'] = ttl
            dns.edit_record(rec)

    def sync_ptr_record():
        """Sync PTR record."""
        host_rec = instance['primaryIpAddress'].split('.')[-1]
        ptr_domains = (env.client['Virtual_Guest']
                       .getReverseDomainRecords(id=instance['id'])[0])
        edit_ptr = None
        for ptr in ptr_domains['resourceRecords']:
            if ptr['host'] == host_rec:
                ptr['ttl'] = ttl
                edit_ptr = ptr
                break

        if edit_ptr:
            edit_ptr['data'] = instance['fullyQualifiedDomainName']
            dns.edit_record(edit_ptr)
        else:
            dns.create_record(ptr_domains['id'],
                              host_rec,
                              'ptr',
                              instance['fullyQualifiedDomainName'],
                              ttl=ttl)

    if not instance['primaryIpAddress']:
        raise exceptions.CLIAbort('No primary IP address associated with '
                                  'this VS')

    zone = dns.get_zone(zone_id)

    go_for_it = env.skip_confirmations or formatting.confirm(
        "Attempt to update DNS records for %s"
        % instance['fullyQualifiedDomainName'])

    if not go_for_it:
        raise exceptions.CLIAbort("Aborting DNS sync")

    both = False
    if not ptr and not a_record and not aaaa_record:
        both = True

    if both or a_record:
        sync_a_record()

    if both or ptr:
        sync_ptr_record()

    if aaaa_record:
        sync_aaaa_record()
250759
def make_route(self, dst, gw=None, dev=None):
        
        prefix, plen = (dst.split("/")+["128"])[:2]
        plen = int(plen)

        if gw is None:
            gw = "::"
        if dev is None:
            dev, ifaddr, x = self.route(gw)
        else:
            # TODO: do better than that
            # replace that unique address by the list of all addresses
            lifaddr = in6_getifaddr()             
            #filter(lambda x: x[2] == dev, lifaddr)
            devaddrs = [ i for i in lifaddr if i[2] == dev] 
            ifaddr = construct_source_candidate_set(prefix, plen, devaddrs, LOOPBACK_NAME)

        return (prefix, plen, gw, dev, ifaddr)
815954
def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
        
        zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
        primary_zone_info = {"forceImport": True, "createType": "UPLOAD"}
        zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
        files = {'zone': ('', json.dumps(zone_data), 'application/json'),
                 'file': ('file', open(bind_file, 'rb'), 'application/octet-stream')}
        return self.rest_api_connection.post_multi_part("/v1/zones", files)
307703
def update_route53_records(self, domain_name, dns_name):
        
        zone_id = self.get_hosted_zone_id_for_domain(domain_name)

        is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name
        if is_apex:
            record_set = {
                'Name': domain_name,
                'Type': 'A',
                'AliasTarget': {
                    'HostedZoneId': 'Z2FDTNDATAQYW2', # This is a magic value that means "CloudFront"
                    'DNSName': dns_name,
                    'EvaluateTargetHealth': False
                }
            }
        else:
            record_set = {
                'Name': domain_name,
                'Type': 'CNAME',
                'ResourceRecords': [
                    {
                        'Value': dns_name
                    }
                ],
                'TTL': 60
            }

        # Related: https://github.com/boto/boto3/issues/157
        # and: http://docs.aws.amazon.com/Route53/latest/APIReference/CreateAliasRRSAPI.html
        # and policy: https://spin.atomicobject.com/2016/04/28/route-53-hosted-zone-managment/
        # pure_zone_id = zone_id.split('/hostedzone/')[1]

        # XXX: ClientError: An error occurred (InvalidChangeBatch) when calling the ChangeResourceRecordSets operation:
        # Tried to create an alias that targets d1awfeji80d0k2.cloudfront.net., type A in zone Z1XWOQP59BYF6Z,
        # but the alias target name does not lie within the target zone
        response = self.route53.change_resource_record_sets(
            HostedZoneId=zone_id,
            ChangeBatch={
                'Changes': [
                    {
                        'Action': 'UPSERT',
                        'ResourceRecordSet': record_set
                    }
                ]
            }
        )

        return response
77057
def get_instance_route53_names(self, instance):
        '''  '''

        instance_attributes = [ 'public_dns_name', 'private_dns_name',
                                'ip_address', 'private_ip_address' ]

        name_list = set()

        for attrib in instance_attributes:
            try:
                value = getattr(instance, attrib)
            except AttributeError:
                continue

            if value in self.route53_records:
                name_list.update(self.route53_records[value])

        return list(name_list)
403375
def create_elb_dns(self, regionspecific=False):
        
        if regionspecific:
            dns_elb = self.generated.dns()['elb_region']
        else:
            dns_elb = self.generated.dns()['elb']

        dns_elb_aws = find_elb(name=self.app_name, env=self.env, region=self.region)

        zone_ids = get_dns_zone_ids(env=self.env, facing=self.elb_subnet)

        self.log.info('Updating Application URL: %s', dns_elb)

        dns_kwargs = {
            'dns_name': dns_elb,
            'dns_name_aws': dns_elb_aws,
            'dns_ttl': self.dns_ttl,
        }

        for zone_id in zone_ids:
            self.log.debug('zone_id: %s', zone_id)
            update_dns_zone_record(self.env, zone_id, **dns_kwargs)

        return dns_elb
63713
def parse_bulk_create(prs, conn):
    
    prs_create = prs.add_parser(
        'bulk_create', help='create bulk records of specific zone')
    set_option(prs_create, 'infile')
    conn_options(prs_create, conn)
    prs_create.add_argument('--domain', action='store',
                            help='create records with specify zone')
    prs_create.set_defaults(func=create)
415356
def _update_rs_with_primary_from_member(
        sds,
        replica_set_name,
        server_description):
    
    assert replica_set_name is not None

    if replica_set_name != server_description.replica_set_name:
        sds.pop(server_description.address)
    elif (server_description.me and
          server_description.address != server_description.me):
        sds.pop(server_description.address)

    # Had this member been the primary?
    return _check_has_primary(sds)
1332999
def create(name, availability_zones, listeners, subnets=None,
           security_groups=None, scheme='internet-facing',
           region=None, key=None, keyid=None,
           profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if exists(name, region, key, keyid, profile):
        return True
    if isinstance(availability_zones, six.string_types):
        availability_zones = salt.utils.json.loads(availability_zones)

    if isinstance(listeners, six.string_types):
        listeners = salt.utils.json.loads(listeners)

    _complex_listeners = []
    for listener in listeners:
        _complex_listeners.append(listener_dict_to_tuple(listener))

    try:
        lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets,
                                       security_groups=security_groups, scheme=scheme,
                                       complex_listeners=_complex_listeners)
        if lb:
            log.info('Created ELB %s', name)
            return True
        else:
            log.error('Failed to create ELB %s', name)
            return False
    except boto.exception.BotoServerError as error:
        log.error('Failed to create ELB %s: %s: %s',
                  name, error.error_code, error.message,
                  exc_info_on_loglevel=logging.DEBUG)
        return False
362091
def create_route(route_table_id=None, destination_cidr_block=None,
                 route_table_name=None, gateway_id=None,
                 internet_gateway_name=None,
                 instance_id=None, interface_id=None,
                 vpc_peering_connection_id=None, vpc_peering_connection_name=None,
                 region=None, key=None, keyid=None, profile=None,
                 nat_gateway_id=None,
                 nat_gateway_subnet_name=None,
                 nat_gateway_subnet_id=None,
                 ):
    '''
    

    '''

    if not _exactly_one((route_table_name, route_table_id)):
        raise SaltInvocationError('One (but not both) of route_table_id or route_table_name '
                                  'must be provided.')

    if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id,
                         nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)):
        raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, '
                                  'interface_id, vpc_peering_connection_id, nat_gateway_id, '
                                  'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.')

    if destination_cidr_block is None:
        raise SaltInvocationError('destination_cidr_block is required.')

    try:
        if route_table_name:
            route_table_id = _get_resource_id('route_table', route_table_name,
                                              region=region, key=key,
                                              keyid=keyid, profile=profile)
            if not route_table_id:
                return {'created': False,
                        'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}}

        if internet_gateway_name:
            gateway_id = _get_resource_id('internet_gateway', internet_gateway_name,
                                          region=region, key=key,
                                          keyid=keyid, profile=profile)
            if not gateway_id:
                return {'created': False,
                        'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}}

        if vpc_peering_connection_name:
            vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name,
                                                         region=region, key=key,
                                                         keyid=keyid, profile=profile)
            if not vpc_peering_connection_id:
                return {'created': False,
                        'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}}

        if nat_gateway_subnet_name:
            gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name,
                                     region=region, key=key, keyid=keyid, profile=profile)
            if not gws:
                return {'created': False,
                        'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}}
            nat_gateway_id = gws[0]['NatGatewayId']

        if nat_gateway_subnet_id:
            gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id,
                                     region=region, key=key, keyid=keyid, profile=profile)
            if not gws:
                return {'created': False,
                        'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}}
            nat_gateway_id = gws[0]['NatGatewayId']

    except BotoServerError as e:
        return {'created': False, 'error': __utils__['boto.get_error'](e)}

    if not nat_gateway_id:
        return _create_resource('route', route_table_id=route_table_id,
                            destination_cidr_block=destination_cidr_block,
                            gateway_id=gateway_id, instance_id=instance_id,
                            interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id,
                            region=region, key=key, keyid=keyid, profile=profile)
    # for nat gateway, boto3 is required
    try:
        conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)
        ret = conn3.create_route(RouteTableId=route_table_id,
                       DestinationCidrBlock=destination_cidr_block,
                       NatGatewayId=nat_gateway_id)
        return {'created': True, 'id': ret.get('NatGatewayId')}
    except BotoServerError as e:
        return {'created': False, 'error': __utils__['boto.get_error'](e)}
1181885
public static URI[] fromDNSName(String srvName) throws NamingException {
    List<URI> uris = new ArrayList<>();
    Hashtable<String, String> env = new Hashtable<>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    env.put("java.naming.provider.url", "dns:");

    DirContext ctx = new InitialDirContext(env);
    Attributes attributes = ctx.getAttributes(srvName, new String[]{"SRV"});
    NamingEnumeration<? extends Attribute> records = attributes.getAll();

    while (records.hasMore()) {
      Attribute next = records.next();

      @SuppressWarnings("unchecked")
      NamingEnumeration<String> values = (NamingEnumeration<String>) next.getAll();
      while (values.hasMore()) {
        String dns = values.next();
        String[] split = dns.split(" ");
        String port = split[2];
        String host = split[3];
        if (host.endsWith(".")) {
          host = host.substring(0, host.length() - 1);
        }
        URI uri = URI.create("http://" + host + ":" + port);
        uris.add(uri);
      }
    }
    return uris.toArray(new URI[uris.size()]);
  }
719503
def _get_vrf_name(self, ri):
        
        router_id = ri.router_name()[:self.DEV_NAME_LEN]
        is_multi_region_enabled = cfg.CONF.multi_region.enable_multi_region

        if is_multi_region_enabled:
            region_id = cfg.CONF.multi_region.region_id
            vrf_name = "%s-%s" % (router_id, region_id)
        else:
            vrf_name = router_id
        return vrf_name
1011509
def __get_region(conn, vm_):
    '''
    
    '''
    location = __get_location(conn, vm_)
    region = '-'.join(location.name.split('-')[:2])

    return conn.ex_get_region(region)
989172
def create_api_gateway_routes(  self,
                                    lambda_arn,
                                    api_name=None,
                                    api_key_required=False,
                                    authorization_type='NONE',
                                    authorizer=None,
                                    cors_options=None,
                                    description=None,
                                    endpoint_configuration=None
                                ):
        

        restapi = troposphere.apigateway.RestApi('Api')
        restapi.Name = api_name or lambda_arn.split(':')[-1]
        if not description:
            description = 'Created automatically by Zappa.'
        restapi.Description = description
        endpoint_configuration = [] if endpoint_configuration is None else endpoint_configuration
        if self.boto_session.region_name == "us-gov-west-1":
            endpoint_configuration.append("REGIONAL")
        if endpoint_configuration:
            endpoint = troposphere.apigateway.EndpointConfiguration()
            endpoint.Types = list(set(endpoint_configuration))
            restapi.EndpointConfiguration = endpoint
        if self.apigateway_policy:
            restapi.Policy = json.loads(self.apigateway_policy)
        self.cf_template.add_resource(restapi)

        root_id = troposphere.GetAtt(restapi, 'RootResourceId')
        invocation_prefix = "aws" if self.boto_session.region_name != "us-gov-west-1" else "aws-us-gov"
        invocations_uri = 'arn:' + invocation_prefix + ':apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + lambda_arn + '/invocations'

        ##
        # The Resources
        ##
        authorizer_resource = None
        if authorizer:
            authorizer_lambda_arn = authorizer.get('arn', lambda_arn)
            lambda_uri = 'arn:{invocation_prefix}:apigateway:{region_name}:lambda:path/2015-03-31/functions/{lambda_arn}/invocations'.format(
                invocation_prefix=invocation_prefix,
                region_name=self.boto_session.region_name,
                lambda_arn=authorizer_lambda_arn
            )
            authorizer_resource = self.create_authorizer(
                restapi, lambda_uri, authorizer
            )

        self.create_and_setup_methods(  restapi,
                                        root_id,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        0
                                        )

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        root_id,
                                        invocations_uri,
                                        0,
                                        cors_options
                                    )

        resource = troposphere.apigateway.Resource('ResourceAnyPathSlashed')
        self.cf_api_resources.append(resource.title)
        resource.RestApiId = troposphere.Ref(restapi)
        resource.ParentId = root_id
        resource.PathPart = "{proxy+}"
        self.cf_template.add_resource(resource)

        self.create_and_setup_methods(  restapi,
                                        resource,
                                        api_key_required,
                                        invocations_uri,
                                        authorization_type,
                                        authorizer_resource,
                                        1
                                    )  # pragma: no cover

        if cors_options:
            self.create_and_setup_cors( restapi,
                                        resource,
                                        invocations_uri,
                                        1,
                                        cors_options
                                    )  # pragma: no cover
        return restapi
420122
def get_route53_client(agent, region, cooperator=None):
    
    if cooperator is None:
        cooperator = task
    return region.get_client(
        _Route53Client,
        agent=agent,
        creds=region.creds,
        region=REGION_US_EAST_1,
        endpoint=AWSServiceEndpoint(_OTHER_ENDPOINT),
        cooperator=cooperator,
    )