def Run(self, args):
        # We explicitly want to allow --networks='' as a valid option and we need
        # to differentiate between that option and not passing --networks at all.
        if args.visibility == 'public':
            if args.IsSpecified('networks'):
                raise exceptions.InvalidArgumentException(
                    '--networks',
                    'If --visibility is set to public (default), setting networks is '
                    'not allowed.')
        if args.visibility == 'private' and args.networks is None:
            raise exceptions.RequiredArgumentException('--networks', ("""
           If --visibility is set to private, a list of networks must be
           provided.'
         NOTE: You can provide an empty value ("") for private zones that
          have NO network binding.
          """))

        api_version = util.GetApiFromTrack(self.ReleaseTrack())
        dns = apis.GetClientInstance('dns', api_version)
        messages = apis.GetMessagesModule('dns', api_version)
        registry = util.GetRegistry(api_version)

        zone_ref = registry.Parse(
            args.dns_zone,
            params={'project': properties.VALUES.core.project.GetOrFail},
            collection='dns.managedZones')

        visibility = messages.ManagedZone.VisibilityValueValuesEnum(
            args.visibility)
        visibility_config = None
        if visibility == messages.ManagedZone.VisibilityValueValuesEnum.private:
            # Handle explicitly empty networks case (--networks='')
            networks = args.networks if args.networks != [''] else []

            def GetNetworkSelfLink(network):
                return registry.Parse(network,
                                      collection='compute.networks',
                                      params={
                                          'project': zone_ref.project
                                      }).SelfLink()

            network_urls = [GetNetworkSelfLink(n) for n in networks]
            network_configs = [
                messages.ManagedZonePrivateVisibilityConfigNetwork(
                    networkUrl=nurl) for nurl in network_urls
            ]
            visibility_config = messages.ManagedZonePrivateVisibilityConfig(
                networks=network_configs)

        if args.forwarding_targets or args.private_forwarding_targets:
            forwarding_config = command_util.ParseManagedZoneForwardingConfigWithForwardingPath(
                messages=messages,
                server_list=args.forwarding_targets,
                private_server_list=args.private_forwarding_targets)
        else:
            forwarding_config = None

        dnssec_config = _MakeDnssecConfig(args, messages)
        labels = labels_util.ParseCreateArgs(args,
                                             messages.ManagedZone.LabelsValue)

        peering_config = None
        if args.target_project and args.target_network:
            peering_network = 'https://www.googleapis.com/compute/v1/projects/{}/global/networks/{}'.format(
                args.target_project, args.target_network)
            peering_config = messages.ManagedZonePeeringConfig()
            peering_config.targetNetwork = messages.ManagedZonePeeringConfigTargetNetwork(
                networkUrl=peering_network)

        reverse_lookup_config = None
        if args.IsSpecified(
                'managed_reverse_lookup') and args.managed_reverse_lookup:
            reverse_lookup_config = messages.ManagedZoneReverseLookupConfig()

        zone = messages.ManagedZone(name=zone_ref.managedZone,
                                    dnsName=util.AppendTrailingDot(
                                        args.dns_name),
                                    description=args.description,
                                    dnssecConfig=dnssec_config,
                                    labels=labels,
                                    visibility=visibility,
                                    forwardingConfig=forwarding_config,
                                    privateVisibilityConfig=visibility_config,
                                    peeringConfig=peering_config,
                                    reverseLookupConfig=reverse_lookup_config)

        result = dns.managedZones.Create(
            messages.DnsManagedZonesCreateRequest(managedZone=zone,
                                                  project=zone_ref.project))
        log.CreatedResource(zone_ref)
        return [result]
Exemple #2
0
  def Run(self, args):
    # We explicitly want to allow --networks='' as a valid option and we need
    # to differentiate between that option and not passing --networks at all.
    if args.visibility == 'public' and args.IsSpecified('networks'):
      raise exceptions.InvalidArgumentException(
          '--networks',
          'If --visibility is set to public (default), setting networks is '
          'not allowed.')
    if args.visibility == 'private' and args.networks is None:
      raise exceptions.RequiredArgumentException('--networks', ("""\
           If --visibility is set to private, a list of networks must be
           provided.'
         NOTE: You can provide an empty value ("") for private zones that
          have NO network binding.
          """))

    dns = apis.GetClientInstance('dns', 'v1')
    messages = apis.GetMessagesModule('dns', 'v1')

    registry = util.GetRegistry('v1')

    zone_ref = registry.Parse(
        args.dns_zone,
        params={
            'project': properties.VALUES.core.project.GetOrFail,
        },
        collection='dns.managedZones')

    visibility = messages.ManagedZone.VisibilityValueValuesEnum(args.visibility)
    visibility_config = None
    if visibility == messages.ManagedZone.VisibilityValueValuesEnum.private:
      # Handle explicitly empty networks case (--networks='')
      networks = args.networks if args.networks != [''] else []

      def GetNetworkSelfLink(network):
        return registry.Parse(
            network,
            collection='compute.networks',
            params={
                'project': zone_ref.project
            }).SelfLink()

      network_urls = [GetNetworkSelfLink(n) for n in networks]
      network_configs = [
          messages.ManagedZonePrivateVisibilityConfigNetwork(networkUrl=nurl)
          for nurl in network_urls
      ]
      visibility_config = messages.ManagedZonePrivateVisibilityConfig(
          networks=network_configs)

    dnssec_config = _MakeDnssecConfig(args, messages)

    labels = labels_util.ParseCreateArgs(args, messages.ManagedZone.LabelsValue)

    zone = messages.ManagedZone(
        name=zone_ref.managedZone,
        dnsName=util.AppendTrailingDot(args.dns_name),
        description=args.description,
        dnssecConfig=dnssec_config,
        labels=labels,
        visibility=visibility,
        privateVisibilityConfig=visibility_config)

    result = dns.managedZones.Create(
        messages.DnsManagedZonesCreateRequest(managedZone=zone,
                                              project=zone_ref.project))
    log.CreatedResource(zone_ref)
    return [result]
def CreateRecordSetFromArgs(args,
                            api_version='v1',
                            allow_extended_records=False):
    """Creates and returns a record-set from the given args.

  Args:
    args: The arguments to use to create the record-set.
    api_version: [str], the api version to use for creating the RecordSet.
    allow_extended_records: [bool], enables extended records if true, otherwise
      throws an exception when given an extended record type.

  Raises:
    UnsupportedRecordType: If given record-set type is not supported

  Returns:
    ResourceRecordSet, the record-set created from the given args.
  """
    messages = apis.GetMessagesModule('dns', api_version)
    if allow_extended_records:
        if args.type in record_types.CLOUD_DNS_EXTENDED_TYPES:
            # Extended records are internal to Cloud DNS, so don't have wire values.
            rd_type = rdatatype.NONE
        else:
            rd_type = _TryParseRRTypeFromString(args.type)
    else:
        rd_type = _TryParseRRTypeFromString(args.type)

    record_set = messages.ResourceRecordSet()
    # Need to assign kind to default value for useful equals comparisons.
    record_set.kind = record_set.kind
    record_set.name = util.AppendTrailingDot(args.name)
    record_set.ttl = args.ttl
    record_set.type = args.type

    if args.rrdatas:
        record_set.rrdatas = args.rrdatas
        if rd_type is rdatatype.TXT or rd_type is rdatatype.SPF:
            record_set.rrdatas = [
                import_util.QuotedText(datum) for datum in args.rrdatas
            ]

    elif args.routing_policy_type == 'WRR':
        record_set.routingPolicy = messages.RRSetRoutingPolicy(
            wrr=messages.RRSetRoutingPolicyWrrPolicy(items=[]))
        for policy_item in args.routing_policy_data:
            if rd_type is rdatatype.TXT or rd_type is rdatatype.SPF:
                policy_item['rrdatas'] = [
                    import_util.QuotedText(datum)
                    for datum in policy_item['rrdatas']
                ]
            record_set.routingPolicy.wrr.items.append(
                messages.RRSetRoutingPolicyWrrPolicyWrrPolicyItem(
                    weight=float(policy_item['key']),
                    rrdatas=policy_item['rrdatas']))

    elif args.routing_policy_type == 'GEO':
        record_set.routingPolicy = messages.RRSetRoutingPolicy(
            geo=messages.RRSetRoutingPolicyGeoPolicy(items=[]))
        for policy_item in args.routing_policy_data:
            if rd_type is rdatatype.TXT or rd_type is rdatatype.SPF:
                policy_item['rrdatas'] = [
                    import_util.QuotedText(datum)
                    for datum in policy_item['rrdatas']
                ]
            record_set.routingPolicy.geo.items.append(
                messages.RRSetRoutingPolicyGeoPolicyGeoPolicyItem(
                    location=policy_item['key'],
                    rrdatas=policy_item['rrdatas']))

    return record_set