feat: Add new gcloud commands, API clients, and third-party libraries across various services.

This commit is contained in:
2026-01-01 20:26:35 +01:00
parent 5e23cbece0
commit a19e592eb7
25221 changed files with 8324611 additions and 0 deletions

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The gcloud dns command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class DNS(base.Group):
"""Manage your Cloud DNS managed-zones and record-sets.
The gcloud dns command group lets you create and manage DNS zones and
their associated records on Google Cloud DNS.
Cloud DNS is a scalable, reliable and managed authoritative DNS service
running on the same infrastructure as Google. It has low latency, high
availability and is a cost-effective way to make your applications and
services available to your users.
More information on Cloud DNS can be found here:
https://cloud.google.com/dns and detailed documentation can be found
here: https://cloud.google.com/dns/docs/
## EXAMPLES
To see how to create and maintain managed-zones, run:
$ {command} managed-zones --help
To see how to maintain the record-sets within a managed-zone, run:
$ {command} record-sets --help
To display Cloud DNS related information for your project, run:
$ {command} project-info describe --help
"""
category = base.NETWORKING_CATEGORY
def Filter(self, context, args):
# TODO(b/190532649): Determine if command group works with project number
base.RequireProjectID(args)
del context, args
base.DisableUserProjectQuota()

View File

@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns active-peering-zones command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ActivePeeringZones(base.Group):
"""Manage your Cloud DNS active-peering-zones.
Manage your Cloud DNS active-peering-zones.
## EXAMPLES
To list the consumer active-peering-zones targeting a producer network, run:
$ {command} list --target-network="my-producer-network"
To revoke a peering connection from the producer by deactivating
an active-peering-zone, run:
$ {command} deactivate consumer_zone_id
"""

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns active-peering-zones deactivate command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Deactivate(base.DeleteCommand):
"""Deactivates a Cloud DNS peering zone.
This command deactivates a Cloud DNS peering zone, removing any peering config
and setting a deactivate time. Reponses sent to the deactivated zone will
return REFUSED.
## EXAMPLES
To deactivate a peering zone, run:
$ {command} peering_zone_id
"""
@staticmethod
def Args(parser):
flags.GetZoneIdArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
dns = util.GetApiClient('v1alpha2')
messages = apis.GetMessagesModule('dns', 'v1alpha2')
result = dns.activePeeringZones.Deactivate(
messages.DnsActivePeeringZonesDeactivateRequest(
peeringZoneId=int(args.zone_id),
project=properties.VALUES.core.project.GetOrFail()))
return result

View File

@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns active-managed-zones list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class List(base.ListCommand):
"""View the list of all active managed zones that target your network.
## EXAMPLES
To see the full list of active managed zones, run:
$ {command}
To see the list of the first 10 active managed zones, run:
$ {command} --limit=10
"""
@staticmethod
def Args(parser):
flags.GetPeeringZoneListArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
dns = util.GetApiClient('v1alpha2')
messages = apis.GetMessagesModule('dns', 'v1alpha2')
project_id = args.project if args.project is not None \
else properties.VALUES.core.project.GetOrFail()
network_url = args.target_network
ids_response = dns.activePeeringZones.List(
messages.DnsActivePeeringZonesListRequest(
project=project_id, targetNetwork=network_url))
zone_list = []
for zone_id in ids_response.peeringZones:
zone_list.append(
dns.activePeeringZones.GetPeeringZoneInfo(
messages.DnsActivePeeringZonesGetPeeringZoneInfoRequest(
project=project_id, peeringZoneId=zone_id.id)))
return zone_list

View File

@@ -0,0 +1,34 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns dns-keys command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Dnskeys(base.Group):
"""Manage Cloud DNS DNSKEY records.
The commands in this group manage Cloud DNS DNS key resources. A DNS key
resource represents a cryptographic signing key for use in DNSSEC; a DNSKEY
record contains a public key used for digitally signing zone data.
For more information, including instructions for managing and using DNS keys,
see the [documentation for DNSSEC](https://cloud.google.com/dns/dnssec).
"""
pass

View File

@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns dns-keys describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import dns_keys
from googlecloudsdk.core import properties
class DescribeBase(object):
"""Show details about a DNSKEY."""
detailed_help = dns_keys.DESCRIBE_HELP
@staticmethod
def Args(parser):
dns_keys.AddDescribeFlags(parser, is_beta=True)
def Run(self, args):
keys = dns_keys.Keys.FromApiVersion(self.GetApiVersion())
return keys.Describe(
args.key_id,
zone=args.zone,
project=properties.VALUES.core.project.GetOrFail)
def GetApiVersion(self):
raise NotImplementedError
@base.ReleaseTracks(base.ReleaseTrack.GA)
class DescribeGA(DescribeBase, base.DescribeCommand):
@staticmethod
def Args(parser):
dns_keys.AddDescribeFlags(parser, hide_short_zone_flag=True)
def GetApiVersion(self):
return 'v1'
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DescribeBeta(DescribeBase, base.DescribeCommand):
def GetApiVersion(self):
return 'v1beta2'
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribeAlpha(DescribeBase, base.DescribeCommand):
def GetApiVersion(self):
return 'v1alpha2'

View File

@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns dns-keys list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import dns_keys
from googlecloudsdk.core import properties
class ListBase(object):
"""View the list of all your DNSKEY records."""
detailed_help = dns_keys.LIST_HELP
@staticmethod
def Args(parser):
dns_keys.AddListFlags(parser)
def Run(self, args):
keys = dns_keys.Keys.FromApiVersion(self.GetApiVersion())
return keys.List(args.zone, properties.VALUES.core.project.GetOrFail)
def GetApiVersion(self):
raise NotImplementedError
@base.ReleaseTracks(base.ReleaseTrack.GA)
class ListGA(ListBase, base.ListCommand):
@staticmethod
def Args(parser):
dns_keys.AddListFlags(parser, hide_short_zone_flag=True)
def GetApiVersion(self):
return 'v1'
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(ListBase, base.ListCommand):
def GetApiVersion(self):
return 'v1beta2'
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(ListBase, base.ListCommand):
def GetApiVersion(self):
return 'v1alpha2'

View File

@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zones command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class ManagedZones(base.Group):
"""Manage your Cloud DNS managed-zones.
Manage your Cloud DNS managed-zones. See
[Managing Zones](https://cloud.google.com/dns/zones/) for details.
## EXAMPLES
To create a managed-zone, run:
$ {command} create my-zone --description="My Zone" --dns-name="my.zone.com."
To delete a managed-zone, run:
$ {command} delete my-zone
To view the details of a managed-zone, run:
$ {command} describe my-zone
To see the list of all managed-zones, run:
$ {command} list
"""
pass

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for managing Dns managed zone configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Dns managed zone configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Dns managed zone.
description: |
*{command}* exports the configuration for a Dns managed zone.
Managed zone configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
managed zones within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a managed zone, run:
$ {command} my-managed-zone
To export the configuration for a managed zone to a file, run:
$ {command} my-managed-zone --path=/path/to/dir/
To export the configuration for a managed zone in Terraform
HCL format, run:
$ {command} my-managed-zone --resource-format=terraform
To export the configurations for all managed zones within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Managed zone to export the configuration for.
spec: !REF googlecloudsdk.command_lib.dns.resources:managed_zone

View File

@@ -0,0 +1,283 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone create command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
def _AddArgsCommon(parser, messages, api_version='v1'):
"""Adds the common arguments for all versions."""
flags.GetDnsZoneArg(
'The name of the managed-zone to be created.'
).AddToParser(parser)
flags.GetManagedZonesDnsNameArg().AddToParser(parser)
flags.GetManagedZonesDescriptionArg().AddToParser(parser)
flags.AddCommonManagedZonesDnssecArgs(parser, messages, api_version)
labels_util.AddCreateLabelsFlags(parser)
flags.GetManagedZoneNetworksArg().AddToParser(parser)
flags.GetManagedZoneVisibilityArg().AddToParser(parser)
flags.GetForwardingTargetsArg().AddToParser(parser)
flags.GetDnsPeeringArgs().AddToParser(parser)
flags.GetPrivateForwardingTargetsArg().AddToParser(parser)
flags.GetReverseLookupArg().AddToParser(parser)
flags.GetServiceDirectoryArg().AddToParser(parser)
flags.GetManagedZoneLoggingArg().AddToParser(parser)
flags.GetManagedZoneGkeClustersArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
def _MakeDnssecConfig(args, messages, api_version='v1'):
"""Parse user-specified args into a DnssecConfig message."""
dnssec_config = None
if args.dnssec_state is not None:
dnssec_config = command_util.ParseDnssecConfigArgs(
args, messages, api_version
)
else:
bad_args = [
'denial_of_existence',
'ksk_algorithm',
'zsk_algorithm',
'ksk_key_length',
'zsk_key_length',
]
for bad_arg in bad_args:
if getattr(args, bad_arg, None) is not None:
raise exceptions.InvalidArgumentException(
bad_arg,
'DNSSEC must be enabled in order to use other DNSSEC arguments. '
'Please set --dnssec-state to "on" or "transfer".',
)
return dnssec_config
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.UniverseCompatible
class Create(base.CreateCommand):
r"""Create a Cloud DNS managed-zone.
This command creates a Cloud DNS managed-zone.
## EXAMPLES
To create a managed-zone, run:
$ {command} my-zone --dns-name=my.zone.com. --description="My zone!"
To create a managed-zone with DNSSEC, run:
$ {command} my-zone-2 --description="Signed Zone"
--dns-name=myzone.example
--dnssec-state=on
To create a zonal managed-zone scoped to a GKE Cluster in us-east1-a, run:
$ {command} my-zonal-zone --description="Signed Zone"
--dns-name=cluster.local
--visibility=private
--gkeclusters=cluster1
--location=us-east1-a
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (
base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA,
)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
messages = apis.GetMessagesModule('dns', api_version)
_AddArgsCommon(parser, messages, api_version=api_version)
parser.display_info.AddCacheUpdater(flags.ManagedZoneCompleter)
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.',
)
# We explicitly want to allow --gkeclusters='' as an optional flag.
elif args.IsSpecified('gkeclusters'):
raise exceptions.InvalidArgumentException(
'--gkeclusters',
'If --visibility is set to public (default), setting gkeclusters is'
' not allowed.',
)
if (
args.visibility == 'private'
and args.networks is None
and args.gkeclusters is None
):
raise exceptions.RequiredArgumentException(
'--networks, --gkeclusters',
("""If --visibility is set to private, a list of networks or list of
GKE clusters must be provided.'
NOTE: You can provide an empty value ("") for private zones that
have NO network or GKE clusters binding.
"""),
)
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
registry = util.GetRegistry(api_version)
zone_ref = registry.Parse(
args.dns_zone,
util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones',
)
visibility_flag = args.visibility
private_enum = None
if api_version == 'v2':
# v2 doesn't set lower_camel_enums, so enums are in upper case
private_enum = messages.ManagedZone.VisibilityValueValuesEnum.PRIVATE
visibility_flag = args.visibility.upper()
else:
private_enum = messages.ManagedZone.VisibilityValueValuesEnum.private
visibility = messages.ManagedZone.VisibilityValueValuesEnum(visibility_flag)
visibility_config = None
if visibility == private_enum:
# Handle explicitly empty networks case (--networks='')
networks = (
args.networks if args.networks and 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
]
# Handle the case when '--gkeclusters' is not specified.
gkeclusters = args.gkeclusters or []
gkecluster_configs = [
messages.ManagedZonePrivateVisibilityConfigGKECluster(
gkeClusterName=name
)
for name in gkeclusters
]
visibility_config = messages.ManagedZonePrivateVisibilityConfig(
networks=network_configs, gkeClusters=gkecluster_configs
)
forwarding_config = None
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,
)
)
dnssec_config = _MakeDnssecConfig(args, messages, api_version)
labels = labels_util.ParseCreateArgs(args, messages.ManagedZone.LabelsValue)
peering_config = None
if args.target_project and args.target_network:
peering_network = (
f'https://www.{properties.VALUES.core.universe_domain.Get()}/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()
service_directory_config = None
if (
args.IsSpecified('service_directory_namespace')
and args.service_directory_namespace
):
service_directory_config = messages.ManagedZoneServiceDirectoryConfig(
namespace=messages.ManagedZoneServiceDirectoryConfigNamespace(
namespaceUrl=args.service_directory_namespace
)
)
cloud_logging_config = None
if args.IsSpecified('log_dns_queries'):
cloud_logging_config = messages.ManagedZoneCloudLoggingConfig()
cloud_logging_config.enableLogging = args.log_dns_queries
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,
serviceDirectoryConfig=service_directory_config,
cloudLoggingConfig=cloud_logging_config,
)
request = messages.DnsManagedZonesCreateRequest(
managedZone=zone, project=zone_ref.project
)
if api_version == 'v2':
# For a request with location, use v2 api.
request.location = args.location
result = dns.managedZones.Create(request)
log.CreatedResource(zone_ref)
return [result]

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone delete command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
"""Delete an empty Cloud DNS managed-zone.
This command deletes an empty Cloud DNS managed-zone. An empty managed-zone
has only SOA and NS record-sets.
## EXAMPLES
To delete an empty managed-zone, run:
$ {command} my-zone
To delete an empty zonal managed-zone in us-east1-c, run:
$ {command} my-zone --location=us-east1-c
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetDnsZoneArg(
'The name of the empty managed-zone to be deleted.').AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns = util.GetApiClient(api_version)
registry = util.GetRegistry(api_version)
zone_ref = registry.Parse(
args.dns_zone,
util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
request = dns.MESSAGES_MODULE.DnsManagedZonesDeleteRequest(
managedZone=zone_ref.managedZone, project=zone_ref.project)
if api_version == 'v2':
# For a request with location, use v2 api.
request.location = args.location
result = dns.managedZones.Delete(request)
log.DeletedResource(zone_ref)
return result

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import managed_zones
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.dns import flags
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""View the details of a Cloud DNS managed-zone.
This command displays the details of the specified managed-zone.
## EXAMPLES
To display the details of your managed-zone, run:
$ {command} my-zone
To display the details of a zonal managed-zone in Zonal Cloud DNS service in
us-east1-c, run:
$ {command} my-zone --location=us-east1-c
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to be described.').AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
location = args.location if api_version == 'v2' else None
zones_client = managed_zones.Client.FromApiVersion(api_version, location)
registry = util.GetRegistry(api_version)
zone_ref = registry.Parse(
args.zone,
util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
# This is a special case in that the . and .. mess up the URI in the HTTP
# request. All other bad arguments are handled server side.
if zone_ref.managedZone == '.' or zone_ref.managedZone == '..':
raise exceptions.BadArgumentException('describe', zone_ref.managedZone)
return zones_client.Get(zone_ref)

View File

@@ -0,0 +1,138 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone get-iam-policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class GetIamPolicyAlpha(base.Command):
"""Get the IAM policy for a Cloud DNS managed-zone.
This command displays the IAM policy of the specified managed-zone.
## EXAMPLES
To view the details of your managed-zone IAM policy , run:
$ {command} my-zone
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to get the IAM policy for.').AddToParser(
parser)
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/managedZones/{1}'.format(
zone_ref.project, zone_ref.managedZone)
req = messages.DnsProjectsManagedZonesGetIamPolicyRequest(
resource=resource_name,
googleIamV1GetIamPolicyRequest=messages.GoogleIamV1GetIamPolicyRequest(
options=messages.GoogleIamV1GetPolicyOptions(
requestedPolicyVersion=iam_util
.MAX_LIBRARY_IAM_SUPPORTED_VERSION)))
return dns_client.projects_managedZones.GetIamPolicy(req)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class GetIamPolicyBeta(base.Command):
"""Get the IAM policy for a Cloud DNS managed-zone.
This command displays the IAM policy of the specified managed-zone.
## EXAMPLES
To view the details of your managed-zone IAM policy , run:
$ {command} my-zone
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to get the IAM policy for.').AddToParser(
parser)
def Run(self, args):
# The v1/v1beta2 apitools gcloud clients are not compatible with this method
api_version = 'v2'
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/locations/{1}/managedZones/{2}'.format(
zone_ref.project, 'global', zone_ref.managedZone)
req = messages.DnsManagedZonesGetIamPolicyRequest(
resource=resource_name,
googleIamV1GetIamPolicyRequest=messages.GoogleIamV1GetIamPolicyRequest(
options=messages.GoogleIamV1GetPolicyOptions(
requestedPolicyVersion=iam_util
.MAX_LIBRARY_IAM_SUPPORTED_VERSION)))
return dns_client.managedZones.GetIamPolicy(req)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class GetIamPolicyGA(base.Command):
"""Get the IAM policy for a Cloud DNS managed-zone.
This command displays the IAM policy of the specified managed-zone.
## EXAMPLES
To view the details of your managed-zone IAM policy , run:
$ {command} my-zone
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to get the IAM policy for.').AddToParser(
parser)
def Run(self, args):
# The v1/v1beta2 apitools gcloud clients are not compatible with this method
api_version = 'v2'
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/locations/{1}/managedZones/{2}'.format(
zone_ref.project, 'global', zone_ref.managedZone)
req = messages.DnsManagedZonesGetIamPolicyRequest(
resource=resource_name,
googleIamV1GetIamPolicyRequest=messages.GoogleIamV1GetIamPolicyRequest(
options=messages.GoogleIamV1GetPolicyOptions(
requestedPolicyVersion=iam_util
.MAX_LIBRARY_IAM_SUPPORTED_VERSION)))
return dns_client.managedZones.GetIamPolicy(req)

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zones list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
def _GetUriFunction(api_version):
def _GetUri(resource):
return util.GetRegistry(api_version).Create(
'dns.managedZones',
project=properties.VALUES.core.project.GetOrFail,
managedZone=resource.name).SelfLink()
return _GetUri
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""View the list of all your managed-zones.
This command displays the list of your managed-zones.
## EXAMPLES
To see the list of all managed-zones, run:
$ {command}
To see the list of first 10 managed-zones, run:
$ {command} --limit=10
To see the list of all managed-zones in a Zonal Cloud DNS service in
us-east1-c, run:
$ {command} --location=us-east1-c
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
parser.display_info.AddFormat('table(name, dnsName, description,'
' visibility)')
parser.display_info.AddUriFunc(
_GetUriFunction(util.GetApiFromTrack(cls.ReleaseTrack())))
flags.GetLocationArg().AddToParser(parser)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns_client = util.GetApiClient(api_version)
project_id = properties.VALUES.core.project.GetOrFail()
request = dns_client.MESSAGES_MODULE.DnsManagedZonesListRequest(
project=project_id)
# For a request with location, use v2 api.
if api_version == 'v2':
request.location = args.location
return list_pager.YieldFromList(
dns_client.managedZones, request, field='managedZones')

View File

@@ -0,0 +1,150 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone set-iam-policy command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class SetIamPolicyAlpha(base.Command):
"""Set the IAM policy for a Cloud DNS managed-zone.
This command sets the IAM policy of the specified managed-zone.
## EXAMPLES
To set the IAM policy of your managed-zone , run:
$ {command} my-zone --policy-file=policy.json
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to set the IAM policy for.').AddToParser(
parser)
parser.add_argument(
'--policy-file',
required=True,
help='JSON or YAML file with the IAM policy')
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/managedZones/{1}'.format(
zone_ref.project, zone_ref.managedZone)
policy, update_mask = iam_util.ParsePolicyFileWithUpdateMask(
args.policy_file, messages.GoogleIamV1Policy)
req = messages.DnsProjectsManagedZonesSetIamPolicyRequest(
resource=resource_name,
googleIamV1SetIamPolicyRequest=messages.GoogleIamV1SetIamPolicyRequest(
policy=policy, updateMask=update_mask))
return dns_client.projects_managedZones.SetIamPolicy(req)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class SetIamPolicyBeta(base.Command):
"""Set the IAM policy for a Cloud DNS managed-zone.
This command sets the IAM policy of the specified managed-zone.
## EXAMPLES
To set the IAM policy of your managed-zone , run:
$ {command} my-zone --policy-file=policy.json
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to set the IAM policy for.').AddToParser(
parser)
parser.add_argument(
'--policy-file',
required=True,
help='JSON or YAML file with the IAM policy')
def Run(self, args):
# The v1/v1beta2 apitools gcloud clients are not compatible with this method
api_version = 'v2'
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/locations/{1}/managedZones/{2}'.format(
zone_ref.project, 'global', zone_ref.managedZone)
policy, update_mask = iam_util.ParsePolicyFileWithUpdateMask(
args.policy_file, messages.GoogleIamV1Policy)
req = messages.DnsManagedZonesSetIamPolicyRequest(
resource=resource_name,
googleIamV1SetIamPolicyRequest=messages.GoogleIamV1SetIamPolicyRequest(
policy=policy, updateMask=update_mask))
return dns_client.managedZones.SetIamPolicy(req)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class SetIamPolicyGA(base.Command):
"""Set the IAM policy for a Cloud DNS managed-zone.
This command sets the IAM policy of the specified managed-zone.
## EXAMPLES
To set the IAM policy of your managed-zone , run:
$ {command} my-zone --policy-file=policy.json
"""
@staticmethod
def Args(parser):
flags.GetZoneResourceArg(
'The name of the managed-zone to set the IAM policy for.').AddToParser(
parser)
parser.add_argument(
'--policy-file',
required=True,
help='JSON or YAML file with the IAM policy')
def Run(self, args):
# The v1/v1beta2 apitools gcloud clients are not compatible with this method
api_version = 'v2'
dns_client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
zone_ref = args.CONCEPTS.zone.Parse()
resource_name = 'projects/{0}/locations/{1}/managedZones/{2}'.format(
zone_ref.project, 'global', zone_ref.managedZone)
policy, update_mask = iam_util.ParsePolicyFileWithUpdateMask(
args.policy_file, messages.GoogleIamV1Policy)
req = messages.DnsManagedZonesSetIamPolicyRequest(
resource=resource_name,
googleIamV1SetIamPolicyRequest=messages.GoogleIamV1SetIamPolicyRequest(
policy=policy, updateMask=update_mask))
return dns_client.managedZones.SetIamPolicy(req)

View File

@@ -0,0 +1,273 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns managed-zone update command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import managed_zones
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import properties
def _CommonArgs(parser, messages, api_version='v1'):
"""Helper function to retrieve necessary flag values."""
flags.GetZoneResourceArg(
'The name of the managed-zone to be updated.'
).AddToParser(parser)
flags.AddCommonManagedZonesDnssecArgs(parser, messages, api_version)
flags.GetManagedZonesDescriptionArg().AddToParser(parser)
labels_util.AddUpdateLabelsFlags(parser)
flags.GetManagedZoneNetworksArg().AddToParser(parser)
base.ASYNC_FLAG.AddToParser(parser)
flags.GetForwardingTargetsArg().AddToParser(parser)
flags.GetDnsPeeringArgs().AddToParser(parser)
flags.GetPrivateForwardingTargetsArg().AddToParser(parser)
flags.GetReverseLookupArg().AddToParser(parser)
flags.GetManagedZoneLoggingArg().AddToParser(parser)
flags.GetManagedZoneGkeClustersArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
def _Update(
zones_client,
args,
private_visibility_config=None,
forwarding_config=None,
peering_config=None,
reverse_lookup_config=None,
cloud_logging_config=None,
api_version='v1',
cleared_fields=None,
):
"""Helper function to perform the update.
Args:
zones_client: the managed zones API client.
args: the args provided by the user on the command line.
private_visibility_config: zone visibility config.
forwarding_config: zone forwarding config.
peering_config: zone peering config.
reverse_lookup_config: zone reverse lookup config.
cloud_logging_config: Stackdriver logging config.
api_version: the API version of this request.
cleared_fields: the fields that should be included in the request JSON as
their default value (fields that are their default value will be omitted
otherwise).
Returns:
The update labels and PATCH call response.
"""
registry = util.GetRegistry(api_version)
zone_ref = registry.Parse(
args.zone,
util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones',
)
dnssec_config = command_util.ParseDnssecConfigArgs(
args, zones_client.messages, api_version
)
labels_update = labels_util.ProcessUpdateArgsLazy(
args,
zones_client.messages.ManagedZone.LabelsValue,
lambda: zones_client.Get(zone_ref).labels,
)
update_results = []
if labels_update.GetOrNone():
update_results.append(
zones_client.UpdateLabels(zone_ref, labels_update.GetOrNone())
)
kwargs = {}
if private_visibility_config:
kwargs['private_visibility_config'] = private_visibility_config
if forwarding_config:
kwargs['forwarding_config'] = forwarding_config
if peering_config:
kwargs['peering_config'] = peering_config
if reverse_lookup_config:
kwargs['reverse_lookup_config'] = reverse_lookup_config
if cloud_logging_config:
kwargs['cloud_logging_config'] = cloud_logging_config
if dnssec_config or args.description or kwargs:
update_results.append(
zones_client.Patch(
zone_ref,
args.async_,
dnssec_config=dnssec_config,
description=args.description,
labels=None,
cleared_fields=cleared_fields,
**kwargs,
)
)
return update_results
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.UniverseCompatible
class UpdateGA(base.UpdateCommand):
"""Update an existing Cloud DNS managed-zone.
Update an existing Cloud DNS managed-zone.
## EXAMPLES
To change the description of a managed-zone, run:
$ {command} my-zone --description="Hello, world!"
To change the description of a zonal managed-zone in us-east1-a, run:
$ {command} my-zone --description="Hello, world!" --location=us-east1-a
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (
base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA,
)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
messages = apis.GetMessagesModule('dns', api_version)
_CommonArgs(parser, messages, api_version=api_version)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
location = args.location if api_version == 'v2' else None
zones_client = managed_zones.Client.FromApiVersion(api_version, location)
messages = zones_client.messages
forwarding_config = None
if args.IsSpecified('forwarding_targets') or args.IsSpecified(
'private_forwarding_targets'
):
forwarding_config = (
command_util.ParseManagedZoneForwardingConfigWithForwardingPath(
messages=messages,
server_list=args.forwarding_targets,
private_server_list=args.private_forwarding_targets,
)
)
peering_config = None
if args.target_project and args.target_network:
peering_network = (
f'https://www.{properties.VALUES.core.universe_domain.Get()}/compute/v1'
'/projects/{}/global/networks/{}'.format(
args.target_project, args.target_network
)
)
peering_config = messages.ManagedZonePeeringConfig()
peering_config.targetNetwork = (
messages.ManagedZonePeeringConfigTargetNetwork(
networkUrl=peering_network
)
)
visibility_config = None
# When the Python object is converted to JSON for the HTTP request body, all
# fields that are their default value will be omitted by default. This is
# problematic for list fields, as an empty list signals that the list field
# should be cleared in a PATCH request, but an empty list is also the
# default list value.
#
# Cleared fields tracks the fields that should be included as their default
# value in the HTTP request body's JSON. Cleared fields is ultimately
# passed to the JSON encoder in the SDK library internals to achieve this.
cleared_fields = []
if args.networks is not None or args.gkeclusters is not None:
# If the user explicitly gave an empty value to networks, clear the field.
# Note that a value of 'None' means the user did not include the networks
# flag, so it should not be cleared in that case.
if args.networks == []: # pylint: disable=g-explicit-bool-comparison
cleared_fields.append('privateVisibilityConfig.networks')
networks = args.networks if args.networks else []
def GetNetworkSelfLink(network):
return (
util.GetRegistry(api_version)
.Parse(
network,
collection='compute.networks',
params={'project': properties.VALUES.core.project.GetOrFail},
)
.SelfLink()
)
network_urls = [GetNetworkSelfLink(n) for n in networks]
network_configs = [
messages.ManagedZonePrivateVisibilityConfigNetwork(networkUrl=nurl)
for nurl in network_urls
]
# If the user explicitly gave an empty value to clusters, clear the field.
if args.gkeclusters == []: # pylint: disable=g-explicit-bool-comparison
cleared_fields.append('privateVisibilityConfig.gkeClusters')
gkeclusters = args.gkeclusters if args.gkeclusters else []
gkecluster_configs = [
messages.ManagedZonePrivateVisibilityConfigGKECluster(
gkeClusterName=name
)
for name in gkeclusters
]
visibility_config = messages.ManagedZonePrivateVisibilityConfig(
networks=network_configs, gkeClusters=gkecluster_configs
)
reverse_lookup_config = None
if (
args.IsSpecified('managed_reverse_lookup')
and args.managed_reverse_lookup
):
reverse_lookup_config = messages.ManagedZoneReverseLookupConfig()
cloud_logging_config = None
if args.IsSpecified('log_dns_queries'):
cloud_logging_config = messages.ManagedZoneCloudLoggingConfig()
cloud_logging_config.enableLogging = args.log_dns_queries
return _Update(
zones_client,
args,
private_visibility_config=visibility_config,
forwarding_config=forwarding_config,
peering_config=peering_config,
reverse_lookup_config=reverse_lookup_config,
cloud_logging_config=cloud_logging_config,
api_version=api_version,
cleared_fields=cleared_fields,
)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns operations command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class DnsOperations(base.Group):
"""Manage your Cloud DNS operations."""
pass

View File

@@ -0,0 +1,102 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns operations describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import operations
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
def _CommonArgs(parser):
flags.GetZoneArg('Name of zone to get operations from.').AddToParser(parser)
parser.add_argument('operation_id', metavar='OPERATION_ID',
help='The id of the operation to display.')
def _Describe(operations_client, args):
operation_ref = util.GetRegistry(operations_client.version).Parse(
args.operation_id,
params={
'project': properties.VALUES.core.project.GetOrFail,
'managedZone': args.zone
},
collection='dns.managedZoneOperations')
return operations_client.Get(operation_ref)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DescribeBeta(base.DescribeCommand):
"""Describe an operation.
This command displays the details of a single managed-zone operation.
## EXAMPLES
To describe a managed-zone operation:
$ {command} 1234 --zone=my_zone
"""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
operations_client = operations.Client.FromApiVersion(api_version)
return _Describe(operations_client, args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""Describe an operation.
This command displays the details of a single managed-zone operation.
## EXAMPLES
To describe a managed-zone operation:
$ {command} 1234 --zone=my_zone
"""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
operations_client = operations.Client.FromApiVersion('v1')
return _Describe(operations_client, args)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribeAlpha(DescribeBeta):
"""Describe an operation.
This command displays the details of a single managed-zone operation.
## EXAMPLES
To describe a managed-zone operation:
$ {command} 1234 --zone=my_zone
"""

View File

@@ -0,0 +1,127 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns operations list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import itertools
from googlecloudsdk.api_lib.dns import operations
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
def _CommonArgs(parser):
"""Add arguments to the parser for `operations list` command."""
# The operations describe command needs both the zone name and the ID.
# We need the zone name in the list output otherwise it gets confusing
# when listing multiple zones. Since the zone name doesn't change, it
# doesn't matter if we get it from oldValue or newValue.
parser.display_info.AddFormat("""
table(
zoneContext.oldValue.name:label=ZONE_NAME:sort=1,
id,
startTime,
user,
type
)
""")
base.URI_FLAG.RemoveFromParser(parser)
base.PAGE_SIZE_FLAG.RemoveFromParser(parser)
flags.GetZoneResourceArg(
'Name of one or more zones to read.',
positional=False, plural=True).AddToParser(parser)
def _List(operations_client, args):
zone_refs = args.CONCEPTS.zones.Parse()
return itertools.chain.from_iterable(
operations_client.List(z, limit=args.limit) for z in zone_refs)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(base.ListCommand):
"""List Cloud DNS operations.
This command displays Cloud DNS operations for one or more Cloud DNS
managed-zones (see `$ gcloud dns managed-zones --help`).
## EXAMPLES
To see the list of all operations for two managed-zones, run:
$ {command} --zones=zone1,zone2
To see the last 5 operations for two managed-zones, run:
$ {command} --zones=zone1,zone2 --sort-by=~start_time --limit=5
"""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
operations_client = operations.Client.FromApiVersion(api_version)
return _List(operations_client, args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List Cloud DNS operations.
This command displays Cloud DNS operations for one or more Cloud DNS
managed-zones (see `$ gcloud dns managed-zones --help`).
## EXAMPLES
To see the list of all operations for two managed-zones, run:
$ {command} --zones=zone1,zone2
To see the last 5 operations for two managed-zones, run:
$ {command} --zones=zone1,zone2 --sort-by=~start_time --limit=5
"""
@staticmethod
def Args(parser):
_CommonArgs(parser)
def Run(self, args):
operations_client = operations.Client.FromApiVersion('v1')
return _List(operations_client, args)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(ListBeta):
"""List Cloud DNS operations.
This command displays Cloud DNS operations for one or more Cloud DNS
managed-zones (see `$ gcloud dns managed-zones --help`).
## EXAMPLES
To see the list of all operations for two managed-zones, run:
$ {command} --zones=zone1,zone2
To see the last 5 operations for two managed-zones, run:
$ {command} --zones=zone1,zone2 --sort-by=~start_time --limit=5
"""

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns operations command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Policies(base.Group):
"""Manage your Cloud DNS policies."""
pass

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for managing Dns policy configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Dns policy configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Dns policy.
description: |
*{command}* exports the configuration for a Dns policy.
Policy configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
policies within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a policy, run:
$ {command} my-policy
To export the configuration for a policy to a file, run:
$ {command} my-policy --path=/path/to/dir/
To export the configuration for a policy in Terraform
HCL format, run:
$ {command} my-policy --resource-format=terraform
To export the configurations for all policies within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Policy to export the configuration for.
spec: !REF googlecloudsdk.command_lib.dns.resources:policy

View File

@@ -0,0 +1,278 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns policy create command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
def _AddArgsCommon(parser):
flags.GetPolicyDescriptionArg(required=True).AddToParser(parser)
flags.GetPolicyNetworksArg(required=True).AddToParser(parser)
flags.GetPolicyInboundForwardingArg().AddToParser(parser)
flags.GetPolicyAltNameServersArg().AddToParser(parser)
flags.GetPolicyLoggingArg().AddToParser(parser)
flags.GetPolicyPrivateAltNameServersArg().AddToParser(parser)
flags.GetEnableDns64AllQueriesArg().AddToParser(parser)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class CreateGA(base.UpdateCommand):
r"""Creates a new Cloud DNS policy.
This command creates a new Cloud DNS policy.
## EXAMPLES
To create a new policy with minimal arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=''
To create a new policy with all optional arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=network1,network2 \
--alternative-name-servers=192.168.1.1,192.168.1.2 \
--enable-inbound-forwarding \
--enable-logging \
--enable-dns64-all-queries
"""
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to create', api_version='v1')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Policy
policy_ref = args.CONCEPTS.policy.Parse()
policy_name = policy_ref.Name()
policy = messages.Policy(
name=policy_name,
enableLogging=False,
enableInboundForwarding=False,
)
if args.IsSpecified('networks'):
if args.networks == ['']:
args.networks = []
policy.networks = command_util.ParsePolicyNetworks(
args.networks, policy_ref.project, api_version)
else:
raise exceptions.RequiredArgumentException('--networks', ("""
A list of networks must be
provided.'
NOTE: You can provide an empty value ("") for policies that
have NO network binding.
"""))
if args.IsSpecified('alternative_name_servers') or args.IsSpecified(
'private_alternative_name_servers'):
if args.alternative_name_servers == ['']:
args.alternative_name_servers = []
if args.private_alternative_name_servers == ['']:
args.private_alternative_name_servers = []
policy.alternativeNameServerConfig = command_util.ParseAltNameServers(
version=api_version,
server_list=args.alternative_name_servers,
private_server_list=args.private_alternative_name_servers)
if args.IsSpecified('enable_inbound_forwarding'):
policy.enableInboundForwarding = args.enable_inbound_forwarding
if args.IsSpecified('enable_logging'):
policy.enableLogging = args.enable_logging
if args.IsSpecified('enable_dns64_all_queries'):
policy.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(
allQueries=args.enable_dns64_all_queries
)
)
else:
policy.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(allQueries=False)
)
if args.IsSpecified('description'):
policy.description = args.description
create_request = messages.DnsPoliciesCreateRequest(
policy=policy, project=policy_ref.project)
result = client.policies.Create(create_request)
log.CreatedResource(policy_ref, kind='Policy')
return result
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(CreateGA):
r"""Creates a new Cloud DNS policy.
This command creates a new Cloud DNS policy.
## EXAMPLES
To create a new policy with minimal arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=''
To create a new policy with all optional arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=network1,network2 \
--alternative-name-servers=192.168.1.1,192.168.1.2 \
--private-alternative-name-servers=100.64.0.1 \
--enable-inbound-forwarding \
--enable-logging \
--enable-dns64-all-queries
"""
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to create', api_version='v1beta2')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Policy
policy_ref = args.CONCEPTS.policy.Parse()
policy_name = policy_ref.Name()
policy = messages.Policy(
name=policy_name,
enableLogging=False,
enableInboundForwarding=False,
)
if args.IsSpecified('networks'):
if args.networks == ['']:
args.networks = []
policy.networks = command_util.ParsePolicyNetworks(
args.networks, policy_ref.project, api_version)
else:
raise exceptions.RequiredArgumentException('--networks', ("""
A list of networks must be
provided.'
NOTE: You can provide an empty value ("") for policies that
have NO network binding.
"""))
if args.IsSpecified('alternative_name_servers') or args.IsSpecified(
'private_alternative_name_servers'):
if args.alternative_name_servers == ['']:
args.alternative_name_servers = []
if args.private_alternative_name_servers == ['']:
args.private_alternative_name_servers = []
policy.alternativeNameServerConfig = command_util.BetaParseAltNameServers(
version=api_version,
server_list=args.alternative_name_servers,
private_server_list=args.private_alternative_name_servers)
if args.IsSpecified('enable_inbound_forwarding'):
policy.enableInboundForwarding = args.enable_inbound_forwarding
if args.IsSpecified('enable_logging'):
policy.enableLogging = args.enable_logging
if args.IsSpecified('enable_dns64_all_queries'):
policy.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(
allQueries=args.enable_dns64_all_queries
)
)
else:
policy.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(allQueries=False)
)
if args.IsSpecified('description'):
policy.description = args.description
create_request = messages.DnsPoliciesCreateRequest(
policy=policy, project=policy_ref.project)
result = client.policies.Create(create_request)
log.CreatedResource(policy_ref, kind='Policy')
return result
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(CreateBeta):
r"""Creates a new Cloud DNS policy.
This command creates a new Cloud DNS policy.
## EXAMPLES
To create a new policy with minimal arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=''
To create a new policy with all optional arguments, run:
$ {command} mypolicy \
--description='My new policy test policy 5' \
--networks=network1,network2 \
--alternative-name-servers=192.168.1.1,192.168.1.2 \
--private-alternative-name-servers=100.64.0.1 \
--enable-inbound-forwarding \
--enable-logging \
--enable-dns64-all-queries
"""
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to create', api_version='v1alpha2')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')

View File

@@ -0,0 +1,30 @@
- &GA
release_tracks: [GA]
help_text:
brief: Deletes a Cloud DNS policy.
description: |
Deletes a Cloud DNS policy.
## EXAMPLES
To delete a policy, run:
$ {command} mypolicy
request:
collection: dns.policies
method: delete
api_version: v1
arguments:
resource:
help_text: The name of the policy you want to delete.
is_positional: true
spec: !REF googlecloudsdk.command_lib.dns.resources:policy
- <<: *GA
release_tracks: [BETA, ALPHA]
request:
collection: dns.policies
method: delete
api_version: v1beta2

View File

@@ -0,0 +1,23 @@
- help_text:
brief: Describes a Cloud DNS policy.
description: |
Describes details of a Cloud DNS policy.
## EXAMPLES
To describe a policy, run:
$ {command} mypolicy
request:
collection: dns.policies
method: get
api_version: v1
arguments:
resource:
help_text: The name of the policy you want to describe.
is_positional: true
spec: !REF googlecloudsdk.command_lib.dns.resources:policy
output:
format: json

View File

@@ -0,0 +1,61 @@
- &GA
release_tracks: [GA]
help_text:
brief: View the list of all your Cloud DNS policies.
description: |
Displays the list of all Cloud DNS policies in a given project.
## EXAMPLES
To see the list of all policies, run:
$ {command}
To see the list of first 10 policies, run:
$ {command} --limit=10
request:
collection: dns.policies
method: list
api_version: v1
response:
id_field: name
arguments:
resource:
help_text: The project you want to list policies for.
spec: !REF googlecloudsdk.command_lib.dns.resources:project
output:
format: |
table(name,
description,
enableInboundForwarding:label=FORWARDING,
enableLogging:label=LOGGING,
alternativeNameServerConfig.targetNameServers.extract(
ipv4Address).map().join(", ").list():label=ALTERNATE_NAME_SERVERS,
networks.firstof(networkUrl).map().scope().join(", "):label=NETWORKS,
dns64Config.scope.allQueries:label=DNS64_ALL_QUERIES
)
- <<: *GA
release_tracks: [ALPHA, BETA]
request:
collection: dns.policies
method: list
api_version: v1beta2
output:
format: |
table(name,
description,
enableInboundForwarding:label=FORWARDING,
enableLogging:label=LOGGING,
alternativeNameServerConfig.targetNameServers.extract(
ipv4Address).map().join(", ").list():label=ALTERNATE_NAME_SERVERS,
networks.firstof(networkUrl).map().scope().join(", "):label=NETWORKS,
dns64Config.scope.allQueries:label=DNS64_ALL_QUERIES
)

View File

@@ -0,0 +1,237 @@
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns policy update command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
def _AddArgsCommon(parser):
flags.GetPolicyDescriptionArg().AddToParser(parser)
flags.GetPolicyNetworksArg().AddToParser(parser)
flags.GetPolicyInboundForwardingArg().AddToParser(parser)
flags.GetPolicyAltNameServersArg().AddToParser(parser)
flags.GetPolicyLoggingArg().AddToParser(parser)
flags.GetPolicyPrivateAltNameServersArg().AddToParser(parser)
flags.GetEnableDns64AllQueriesArg(update=True).AddToParser(parser)
def _ArgsNeededForUpdateCommon():
return (
'networks',
'description',
'enable_inbound_forwarding',
'enable_logging',
'alternative_name_servers',
'enable_dns64_all_queries',
)
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateGA(base.UpdateCommand):
"""Update an existing Cloud DNS policy.
Update an existing Cloud DNS policy.
## EXAMPLES
To change the description of a policy, run:
$ {command} mypolicy --description="Hello, world!"
"""
def _FetchPolicy(self, policy_ref, api_version):
"""Get policy to be Updated."""
client = util.GetApiClient(api_version)
m = apis.GetMessagesModule('dns', api_version)
get_request = m.DnsPoliciesGetRequest(
policy=policy_ref.Name(), project=policy_ref.project)
return client.policies.Get(get_request)
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to update', api_version='v1')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Policy
policy_ref = args.CONCEPTS.policy.Parse()
to_update = self._FetchPolicy(policy_ref, api_version)
args_needed_for_update = _ArgsNeededForUpdateCommon()
if not any(args.IsSpecified(arg) for arg in args_needed_for_update):
log.status.Print('Nothing to update.')
return to_update
if args.IsSpecified('networks'):
if args.networks == ['']:
args.networks = []
to_update.networks = command_util.ParsePolicyNetworks(
args.networks, policy_ref.project, api_version)
if args.IsSpecified('alternative_name_servers') or args.IsSpecified(
'private_alternative_name_servers'):
if args.alternative_name_servers == ['']:
args.alternative_name_servers = []
if args.private_alternative_name_servers == ['']:
args.private_alternative_name_servers = []
to_update.alternativeNameServerConfig = command_util.ParseAltNameServers(
version=api_version,
server_list=args.alternative_name_servers,
private_server_list=args.private_alternative_name_servers)
if args.IsSpecified('enable_inbound_forwarding'):
to_update.enableInboundForwarding = args.enable_inbound_forwarding
if args.IsSpecified('enable_logging'):
to_update.enableLogging = args.enable_logging
if args.IsSpecified('enable_dns64_all_queries'):
to_update.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(
allQueries=args.enable_dns64_all_queries
)
)
if args.IsSpecified('description'):
to_update.description = args.description
update_req = messages.DnsPoliciesUpdateRequest(
policy=to_update.name,
policyResource=to_update,
project=policy_ref.project)
updated_policy = client.policies.Update(update_req).policy
log.UpdatedResource(updated_policy.name, kind='Policy')
return updated_policy
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(UpdateGA):
"""Update an existing Cloud DNS policy.
Update an existing Cloud DNS policy.
## EXAMPLES
To change the description of a policy, run:
$ {command} mypolicy --description="Hello, world!"
"""
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to update', api_version='v1beta2')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrack(self.ReleaseTrack())
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Policy
policy_ref = args.CONCEPTS.policy.Parse()
to_update = self._FetchPolicy(policy_ref, api_version)
args_needed_for_update = _ArgsNeededForUpdateCommon()
if not any(args.IsSpecified(arg) for arg in args_needed_for_update):
log.status.Print('Nothing to update.')
return to_update
if args.IsSpecified('networks'):
if args.networks == ['']:
args.networks = []
to_update.networks = command_util.ParsePolicyNetworks(
args.networks, policy_ref.project, api_version)
if args.IsSpecified('alternative_name_servers') or args.IsSpecified(
'private_alternative_name_servers'):
if args.alternative_name_servers == ['']:
args.alternative_name_servers = []
if args.private_alternative_name_servers == ['']:
args.private_alternative_name_servers = []
to_update.alternativeNameServerConfig = command_util.ParseAltNameServers(
version=api_version,
server_list=args.alternative_name_servers,
private_server_list=args.private_alternative_name_servers)
if args.IsSpecified('enable_inbound_forwarding'):
to_update.enableInboundForwarding = args.enable_inbound_forwarding
if args.IsSpecified('enable_logging'):
to_update.enableLogging = args.enable_logging
if args.IsSpecified('enable_dns64_all_queries'):
to_update.dns64Config = messages.PolicyDns64Config(
scope=messages.PolicyDns64ConfigScope(
allQueries=args.enable_dns64_all_queries
)
)
if args.IsSpecified('description'):
to_update.description = args.description
update_req = messages.DnsPoliciesUpdateRequest(
policy=to_update.name,
policyResource=to_update,
project=policy_ref.project)
updated_policy = client.policies.Update(update_req).policy
log.UpdatedResource(updated_policy.name, kind='Policy')
return updated_policy
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(UpdateBeta):
"""Update an existing Cloud DNS policy.
Update an existing Cloud DNS policy.
## EXAMPLES
To change the description of a policy, run:
$ {command} mypolicy --description="Hello, world!"
"""
@staticmethod
def Args(parser):
resource_args.AddPolicyResourceArg(
parser, verb='to update', api_version='v1alpha2')
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')

View File

@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns project-info command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class ProjectInfo(base.Group):
"""View Cloud DNS related information for a project.
View Cloud DNS related information for a project.
## EXAMPLES
To display Cloud DNS related information for your project, run:
$ {command} describe
"""
pass

View File

@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns project-info describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import resources
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
"""View Cloud DNS related information for a project.
This command displays Cloud DNS related information for your project including
quotas for various resources and operations.
## EXAMPLES
To display Cloud DNS related information for your project, run:
$ {command} my_project_id
"""
@staticmethod
def Args(parser):
parser.add_argument(
'dns_project', metavar='PROJECT_ID',
help='The identifier for the project you want DNS related info for.')
def Run(self, args):
dns = util.GetApiClient('v1')
project_ref = resources.REGISTRY.Parse(
args.dns_project, collection='dns.projects')
return dns.projects.Get(
dns.MESSAGES_MODULE.DnsProjectsGetRequest(
project=project_ref.project))
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class DescribeBeta(base.DescribeCommand):
"""View Cloud DNS related information for a project.
This command displays Cloud DNS related information for your project including
quotas for various resources and operations.
## EXAMPLES
To display Cloud DNS related information for your project, run:
$ {command} my_project_id
To display Cloud DNS related information for your project in us-east1-c, run:
$ {command} my_project_id --location=us-east1-c
"""
@staticmethod
def Args(parser):
parser.add_argument(
'dns_project',
metavar='PROJECT_ID',
help='The identifier for the project you want DNS related info for.',
)
flags.GetLocationArg().AddToParser(parser)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns = util.GetApiClient(api_version)
project_ref = util.GetRegistry(api_version).Parse(
args.dns_project, collection='dns.projects'
)
request_kwargs = {'project': project_ref.project}
if api_version.startswith('v2'):
request_kwargs['location'] = args.location
return dns.projects.Get(
dns.MESSAGES_MODULE.DnsProjectsGetRequest(**request_kwargs)
)

View File

@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class RecordSets(base.Group):
"""Manage the record-sets within your managed-zones.
Manage the record-sets within your managed-zones.
## EXAMPLES
To import record-sets from a BIND zone file, run:
$ {command} import --zone=MANAGED_ZONE --zone-file-format ZONE_FILE
To export record-sets in yaml format, run:
$ {command} export --zone=MANAGED_ZONE
To see how to make scriptable changes to your record-sets through
transactions, run:
$ {command} transaction --help
To list all changes, run:
$ {command} changes list --zone=MANAGED_ZONE
To see change details, run:
$ {command} changes describe CHANGE_ID --zone=MANAGED_ZONE
To see the list of all record-sets, run:
$ {command} list --zone=MANAGED_ZONE
"""
pass

View File

@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets changes command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Changes(base.Group):
"""View details about changes to your Cloud DNS record-sets.
View details about changes to your Cloud DNS record-sets.
## EXAMPLES
To view the details of a particular change, run:
$ {command} describe CHANGE_ID --zone=MANAGED_ZONE
To view the list of all changes, run:
$ {command} list --zone=MANAGED_ZONE
"""
pass

View File

@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets changes describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
class Describe(base.DescribeCommand):
"""View the details of a change.
This command displays the details of the specified change.
## EXAMPLES
To display the details of a change, run:
$ {command} change_id
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
parser.add_argument(
'change_id', metavar='CHANGE_ID',
help='The ID of the change you want details for.')
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
dns_client = util.GetApiClient(api_version)
change_ref = util.GetRegistry(api_version).Parse(
args.change_id,
params={
'project': properties.VALUES.core.project.GetOrFail,
'managedZone': args.MakeGetOrRaise('--zone'),
},
collection='dns.changes')
return dns_client.changes.Get(
dns_client.MESSAGES_MODULE.DnsChangesGetRequest(
project=change_ref.project,
managedZone=change_ref.managedZone,
changeId=change_ref.changeId))

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets changes list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
class List(base.ListCommand):
"""View the list of changes that have been made to your record-sets.
This command displays the list of changes that have been made to your
record-sets.
## EXAMPLES
To see the list of changes, run:
$ {command}
To see the list of first 10 changes, run:
$ {command} --limit=10
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
parser.add_argument(
'--sort-order', default=None, required=False,
choices=['ascending', 'descending'],
help='Sort order for listing.')
parser.display_info.AddFormat(flags.CHANGES_FORMAT)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params={
'project': properties.VALUES.core.project.GetOrFail,
},
collection='dns.managedZones')
return list_pager.YieldFromList(
dns_client.changes,
dns_client.MESSAGES_MODULE.DnsChangesListRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
sortOrder=args.sort_order),
limit=args.limit, field='changes')

View File

@@ -0,0 +1,136 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets create command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.dns import resource_record_sets as rrsets_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
@base.UniverseCompatible
class Create(base.CreateCommand):
"""Creates a record-set in a managed-zone."""
detailed_help = {
'DESCRIPTION':
textwrap.dedent("""\
This command creates a record-set contained within the specified
managed-zone.
"""),
'EXAMPLES':
textwrap.dedent("""\
To create a record-set with dnsName foo.bar.com., record type A,
rrdata [1.2.3.4, 9.8.7.6] and ttl 60 in my_zone run this:
$ {command} foo.bar.com. --rrdatas=1.2.3.4,9.8.7.6 --type=A --ttl=60
--zone=my_zone
To create a geo routed record-set with dnsName foo.bar.com., record
type A, routing_policy_data "us-centra1=1.2.3.4,2.3.4.5;us-west1=3.4.5.6,9.8.7.6"
and ttl 60 in my_zone.
$ {command} foo.bar.com. --routing_policy_data="us-centra1=1.2.3.4,2.3.4.5;us-west1=3.4.5.6,9.8.7.6"
--routing_policy_type=GEO --type=A --ttl=60 --zone=my_zone --location=us-east1-a
To create a record-set with dnsName foo.bar.com., record type A,
rrdata [1.2.3.4, 9.8.7.6] and ttl 60 in my_zone in us-east1-a run this:
$ {command} us-east1-a.bar.com. --rrdatas=1.2.3.4,9.8.7.6 --type=A --ttl=60
--zone=my_zone --location=us-east1-a
To create a failover type health checked routed record-set with dnsName
foo.bar.com., record type A, primary routing data "config1", backup
routing data "us-centra1=1.2.3.4,2.3.4.5;us-west1=3.4.5.6,9.8.7.6", with a
trickle traffic ratio of 10% to the backup data,
and ttl 60 in my_zone.
$ {command} foo.bar.com. --type=A --ttl=60 \
--zone=routing-policy-test --routing_policy_type=FAILOVER \
--routing-policy-primary-data='config1' \
--routing-policy-backup-data-type=GEO \
--routing-policy-backup-data='us-centra1=1.2.3.4,2.3.4.5;us-west1=3.4.5.6,9.8.7.6' \
--backup-data-trickle-ratio=0.1 --enable-health-checking --zone=my_zone
To create a geo fenced health checked routed record-set with dnsName
foo.bar.com., record type A, routing-policy-data
"us-centra1=config1,config2;us-west1=3.4.5.6,9.8.7.6",
and ttl 60 in my_zone.
$ {command} foo.bar.com. --type=A --ttl=60 \
--zone=routing-policy-test --routing_policy_type=GEO \
--routing_policy_data='us-centra1=config1,config2;us-west1=3.4.5.6,9.8.7.6' \
--enable-health-checking --enable-geo-fencing --zone=my_zone
""")
}
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetResourceRecordSetsNameArg().AddToParser(parser)
flags.GetResourceRecordSetsTypeArg(True).AddToParser(parser)
flags.GetResourceRecordSetsTtlArg(False).AddToParser(parser)
flags.GetResourceRecordSetsRrdatasArgGroup(
use_deprecated_names=cls._BetaOrAlpha(),
).AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
parser.display_info.AddTransforms(flags.RESOURCERECORDSETS_TRANSFORMS)
parser.display_info.AddFormat(flags.RESOURCERECORDSETS_FORMAT)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
messages = apis.GetMessagesModule('dns', api_version)
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones',
)
request = messages.DnsResourceRecordSetsCreateRequest(
project=zone_ref.project,
managedZone=zone_ref.managedZone,
resourceRecordSet=rrsets_util.CreateRecordSetFromArgs(
args,
zone_ref.project,
api_version,
),
)
if api_version == 'v2':
request.location = args.location
result = dns_client.resourceRecordSets.Create(request)
return result

View File

@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets delete command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Delete(base.DeleteCommand):
"""Delete a record-set in a managed-zone.
This command deletes a record-set contained within the specified
managed-zone.
## EXAMPLES
To delete a record-set with dnsName foo.bar.com. and record type A, rrdata
run:
$ {command} foo.bar.com. --type=A --zone=my_zone
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetResourceRecordSetsNameArg().AddToParser(parser)
flags.GetResourceRecordSetsTypeArg(True).AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
messages = apis.GetMessagesModule('dns', api_version)
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
param = util.GetParamsForRegistry(api_version, args, parent='managedZones')
param['name'] = args.name
rrsets_ref = util.GetRegistry(api_version).Parse(
args.type,
params=param,
collection='dns.resourceRecordSets')
request = messages.DnsResourceRecordSetsDeleteRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
name=util.AppendTrailingDot(args.name),
type=args.type)
if api_version == 'v2':
request.location = args.location
result = dns_client.resourceRecordSets.Delete(request)
log.DeletedResource(rrsets_ref)
return result

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Describe(base.DescribeCommand):
"""Describe a record-set in a managed-zone.
This command describes a record-set contained within the specified
managed-zone.
## EXAMPLES
To describe a record-set with dnsName foo.bar.com. and record type A, rrdata
run:
$ {command} foo.bar.com. --type=A --zone=my_zone
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetResourceRecordSetsNameArg().AddToParser(parser)
flags.GetResourceRecordSetsTypeArg(True).AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
parser.display_info.AddTransforms(flags.RESOURCERECORDSETS_TRANSFORMS)
parser.display_info.AddFormat(flags.RESOURCERECORDSETS_FORMAT)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
messages = apis.GetMessagesModule('dns', api_version)
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
request = messages.DnsResourceRecordSetsGetRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
name=util.AppendTrailingDot(args.name),
type=args.type)
if api_version == 'v2':
request.location = args.location
return dns_client.resourceRecordSets.Get(request)

View File

@@ -0,0 +1,133 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets export command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import export_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.util import files
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Export(base.Command):
r"""Export your record-sets into a file.
This command exports the record-sets contained within the specified
managed-zone into a file.
The formats you can export to are YAML records format (default) and
BIND zone file format.
## EXAMPLES
To export record-sets into a yaml file, run:
$ {command} records.yaml --zone=examplezonename
To export record-sets into a BIND zone formatted file instead, run:
$ {command} pathto.zonefile --zone=examplezonename --zone-file-format
Similarly, to import record-sets into a BIND zone formatted zone file, run:
$ gcloud dns record-sets import pathto.zonefile --zone-file-format \
--zone=examplezonename
"""
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.add_argument('records_file',
help='File to which record-sets should be exported.')
parser.add_argument(
'--zone-file-format',
required=False,
action='store_true',
help='Indicates that records-file should be in the zone file format.'
' When using this flag, expect the record-set'
' to be exported to a BIND zone formatted file. If you omit this '
'flag, the record-set is exported into a YAML formatted records '
'file. Note, this format flag determines the format of the '
'output recorded in the records-file; it is different from the '
'global `--format` flag which affects console output alone.')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns = util.GetApiClient(api_version)
# Get the managed-zone.
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
try:
get_request = dns.MESSAGES_MODULE.DnsManagedZonesGetRequest(
project=zone_ref.project, managedZone=zone_ref.managedZone)
if api_version == 'v2':
get_request.location = args.location
zone = dns.managedZones.Get(get_request)
except apitools_exceptions.HttpError as error:
raise calliope_exceptions.HttpException(error)
# Get all the record-sets.
record_sets = []
list_request = dns.MESSAGES_MODULE.DnsResourceRecordSetsListRequest(
project=zone_ref.project, managedZone=zone_ref.Name())
if api_version == 'v2':
list_request.location = args.location
for record_set in list_pager.YieldFromList(
dns.resourceRecordSets, list_request, field='rrsets'):
if args.zone_file_format:
if record_set.type == 'ALIAS':
# For BIND file format, ALIAS record sets must be ignored, as they are
# not DNS standards. A zone will have at most one ALIAS record.
log.warning(
'Skipping ALIAS record found in zone, as ALIAS record are custom'
' to Cloud DNS and do not have a standard BIND format. To '
'export ALIAS records, use YAML format instead.'
)
continue
record_sets.append(record_set)
# Export the record-sets.
try:
with files.FileWriter(args.records_file) as export_file:
if args.zone_file_format:
export_util.WriteToZoneFile(export_file, record_sets, zone.dnsName)
else:
export_util.WriteToYamlFile(export_file, record_sets)
except Exception as exp:
msg = 'Unable to export record-sets to file [{0}]: {1}'.format(
args.records_file, exp)
raise export_util.UnableToExportRecordsToFile(msg)
log.status.Print('Exported record-sets to [{0}].'.format(args.records_file))

View File

@@ -0,0 +1,188 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets import command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from apitools.base.py import exceptions as apitools_exceptions
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import import_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
from googlecloudsdk.core.util import files
@base.UnicodeIsSupported
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Import(base.Command):
"""Import record-sets into your managed-zone.
This command imports record-sets contained within the specified record-sets
file into your managed-zone. Note that NS records for the origin of the zone
and the SOA NS field are not imported since name-servers are managed by
Cloud DNS. By default, record-sets cannot be imported if there are any
conflicts. A conflict exists if an existing record-set has the same name and
type as a record-set that is being imported. In contrast, if the
--delete-all-existing flag is used, the imported record-sets will replace all
the records-sets currently in the managed-zone.
## EXAMPLES
To import record-sets from a yaml record-sets file, run:
$ {command} YAML_RECORDS_FILE --zone=MANAGED_ZONE
To import record-sets from a zone file, run:
$ {command} ZONE_FILE --zone-file-format --zone=MANAGED_ZONE
To replace all the record-sets in your zone with records from a yaml
file, run:
$ {command} YAML_RECORDS_FILE --delete-all-existing --zone=MANAGED_ZONE
"""
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.add_argument('records_file',
help='File from which record-sets should be '
'imported. For examples of YAML-formatted '
'and BIND zone-formatted records files, refer to '
'https://cloud.google.com/dns/records'
'#importing_and_exporting_record_sets')
parser.add_argument(
'--zone-file-format',
required=False,
action='store_true',
help=('Indicates that the input records-file is in BIND zone format. '
'If omitted, indicates that the records-file is in YAML format.'))
parser.add_argument(
'--delete-all-existing',
required=False,
action='store_true',
help='Indicates that all existing record-sets should be deleted before'
' importing the record-sets in the records-file.')
parser.add_argument(
'--replace-origin-ns',
required=False,
action='store_true',
help='Indicates that NS records for the origin of a zone should be'
' imported if defined')
parser.display_info.AddFormat(flags.CHANGES_FORMAT)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
if not os.path.exists(args.records_file):
raise import_util.RecordsFileNotFound(
'Specified record file [{0}] not found.'.format(args.records_file))
if os.path.isdir(args.records_file):
raise import_util.RecordsFileIsADirectory(
'Specified record file [{0}] is a directory'.format(
args.records_file))
dns = util.GetApiClient(api_version)
# Get the managed-zone.
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
try:
get_request = dns.MESSAGES_MODULE.DnsManagedZonesGetRequest(
project=zone_ref.project, managedZone=zone_ref.managedZone)
if api_version == 'v2':
get_request.location = args.location
zone = dns.managedZones.Get(get_request)
except apitools_exceptions.HttpError as error:
raise calliope_exceptions.HttpException(error)
# Get the current record-sets.
current = {}
list_request = dns.MESSAGES_MODULE.DnsResourceRecordSetsListRequest(
project=zone_ref.project, managedZone=zone_ref.Name())
if api_version == 'v2':
list_request.location = args.location
for record in list_pager.YieldFromList(
dns.resourceRecordSets, list_request, field='rrsets'):
current[(record.name, record.type)] = record
# Get the imported record-sets.
try:
with files.FileReader(args.records_file) as import_file:
if args.zone_file_format:
imported = import_util.RecordSetsFromZoneFile(
import_file, zone.dnsName, api_version=api_version)
else:
imported = import_util.RecordSetsFromYamlFile(
import_file,
include_extended_records=True,
api_version=api_version)
except Exception as exp:
msg = ('Unable to read record-sets from specified records-file [{0}] '
'because [{1}]')
msg = msg.format(args.records_file, exp.message)
raise import_util.UnableToReadRecordsFile(msg)
# Get the change resulting from the imported record-sets.
change = import_util.ComputeChange(
current,
imported,
args.delete_all_existing,
zone.dnsName,
args.replace_origin_ns,
api_version=api_version)
if not change:
msg = 'Nothing to do, all the records in [{0}] already exist.'.format(
args.records_file)
log.status.Print(msg)
return None
# Send the change to the service.
create_request = dns.MESSAGES_MODULE.DnsChangesCreateRequest(
change=change, managedZone=zone.name, project=zone_ref.project)
if api_version == 'v2':
create_request.location = args.location
result = dns.changes.Create(create_request)
param = util.GetParamsForRegistry(api_version, args, parent='managedZones')
param['changeId'] = result.id
change_ref = util.GetRegistry(api_version).Parse(
line=None,
collection='dns.changes',
params=param)
msg = 'Imported record-sets from [{0}] into managed-zone [{1}].'.format(
args.records_file, zone_ref.Name())
log.status.Print(msg)
log.CreatedResource(change_ref)
return result

View File

@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class List(base.ListCommand):
"""View the list of record-sets in a managed-zone.
This command displays the list of record-sets contained within the specified
managed-zone.
## EXAMPLES
To see the list of all record-sets in my_zone, run:
$ {command} --zone=my_zone
To see the list of first 10 record-sets in my_zone, run:
$ {command} --zone=my_zone --limit=10
To see the list of 'my.zone.com.' record-sets in my_zone, run:
$ {command} --zone=my_zone --name="my.zone.com."
To see the list of 'my.zone.com.' CNAME record-sets in my_zone, run:
$ {command} --zone=my_zone --name="my.zone.com." --type="CNAME"
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
name_type_group = parser.add_group()
name_type_group.add_argument(
'--name', required=True,
help='Only list record-sets with this exact domain name.')
name_type_group.add_argument(
'--type', required=False,
help='Only list records of this type. If present, the --name parameter '
'must also be present.')
parser.display_info.AddTransforms(flags.RESOURCERECORDSETS_TRANSFORMS)
parser.display_info.AddFormat(flags.RESOURCERECORDSETS_FORMAT)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
list_request = dns_client.MESSAGES_MODULE.DnsResourceRecordSetsListRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
name=util.AppendTrailingDot(args.name),
type=args.type)
if api_version == 'v2':
list_request.location = args.location
return list_pager.YieldFromList(
dns_client.resourceRecordSets,
list_request,
limit=args.limit,
field='rrsets')

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import transaction_util
from googlecloudsdk.calliope import base
class Transaction(base.Group):
r"""Make scriptable and transactional changes to your record-sets.
Make scriptable and transactional changes to your record-sets.
## EXAMPLES
To start a transaction, run:
$ {command} start --zone=MANAGED_ZONE
To append a record-set addition to the transaction, run:
$ {command} add --name RECORD_SET_NAME --ttl TTL --type TYPE DATA \
--zone=MANAGED_ZONE
To append a record-set removal to the transaction, run:
$ {command} remove --name RECORD_SET_NAME --ttl TTL --type TYPE DATA
To look at the details of the transaction, run:
$ {command} describe --zone=MANAGED_ZONE
To delete the transaction, run:
$ {command} abort --zone=MANAGED_ZONE
To execute the transaction, run:
$ {command} execute --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--transaction-file',
default=transaction_util.DEFAULT_PATH,
help='Path of the file which contains the transaction.')

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction abort command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from googlecloudsdk.api_lib.dns import transaction_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
class Abort(base.Command):
"""Abort transaction.
This command aborts the transaction and deletes the transaction file.
## EXAMPLES
To abort the transaction, run:
$ {command} --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
def Run(self, args):
if not os.path.isfile(args.transaction_file):
raise transaction_util.TransactionFileNotFound(
'Transaction not found at [{0}]'.format(args.transaction_file))
os.remove(args.transaction_file)
log.status.Print('Aborted transaction [{0}].'.format(args.transaction_file))

View File

@@ -0,0 +1,102 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction add command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import resource_record_sets as rrsets_util
from googlecloudsdk.api_lib.dns import transaction_util as trans_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
@base.UniverseCompatible
class Add(base.Command):
r"""Append a record-set addition to the transaction.
This command appends a record-set addition to the transaction.
For a guide detailing how to manage records, see:
https://cloud.google.com/dns/records/
## EXAMPLES
To add an A record with an IP address of "1.2.3.4", domain name of
"my.domain.", and a managed zone "MANAGED_ZONE", run:
$ {command} "1.2.3.4" \
--name=my.domain. --ttl=1234 \
--type=A --zone=MANAGED_ZONE
To add a TXT record with multiple data values while specifying time to
live as 14400 seconds, run:
$ {command} "Hello world" "Bye world" \
--name=my.domain. --ttl=14400 \
--type=TXT --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
parser.add_argument(
'--name', required=True,
help='DNS or domain name of the record-set to add.')
parser.add_argument(
'--ttl', required=True, type=int,
help='TTL (time to live) for the record-set to add.')
parser.add_argument(
'--type', required=True,
help='DNS record type of the record-set to add.')
parser.add_argument(
'rrdatas', nargs='+',
help='DNS data (Address/CNAME/MX info, etc.) of the record-set to add. '
'This is RDATA; the format of this information varies depending '
'on the type and class of the resource record.')
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
with trans_util.TransactionFile(args.transaction_file) as trans_file:
change = trans_util.ChangeFromYamlFile(
trans_file, api_version=api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
change.additions.append(
rrsets_util.CreateRecordSetFromArgs(
args,
zone_ref.project,
api_version=api_version))
with trans_util.TransactionFile(args.transaction_file, 'w') as trans_file:
trans_util.WriteToYamlFile(trans_file, change)
log.status.Print(
'Record addition appended to transaction at [{0}].'.format(
args.transaction_file))

View File

@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import transaction_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
class Describe(base.DescribeCommand):
"""Describe the transaction.
This command displays the contents of the transaction.
## EXAMPLES
To look at the contents of the transaction, run:
$ {command} --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
with transaction_util.TransactionFile(args.transaction_file) as trans_file:
return transaction_util.ChangeFromYamlFile(
trans_file, api_version=api_version)

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction execute command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from googlecloudsdk.api_lib.dns import import_util
from googlecloudsdk.api_lib.dns import transaction_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
class Execute(base.ListCommand):
"""Execute the transaction on Cloud DNS.
This command executes the transaction on Cloud DNS. This will result in
record-sets being changed as specified in the transaction.
## EXAMPLES
To execute the transaction, run:
$ {command} --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
parser.display_info.AddFormat(flags.CHANGES_FORMAT)
parser.display_info.AddCacheUpdater(None)
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
with transaction_util.TransactionFile(args.transaction_file) as trans_file:
change = transaction_util.ChangeFromYamlFile(
trans_file, api_version=api_version)
if import_util.IsOnlySOAIncrement(change, api_version=api_version):
log.status.Print(
'Nothing to do, empty transaction [{0}]'.format(
args.transaction_file))
os.remove(args.transaction_file)
return None
dns = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params={
'project': properties.VALUES.core.project.GetOrFail,
},
collection='dns.managedZones')
# Send the change to the service.
result = dns.changes.Create(dns.MESSAGES_MODULE.DnsChangesCreateRequest(
change=change, managedZone=zone_ref.Name(), project=zone_ref.project))
change_ref = util.GetRegistry(api_version).Create(
collection='dns.changes', project=zone_ref.project,
managedZone=zone_ref.Name(), changeId=result.id)
msg = 'Executed transaction [{0}] for managed-zone [{1}].'.format(
args.transaction_file, zone_ref.Name())
log.status.Print(msg)
log.CreatedResource(change_ref)
os.remove(args.transaction_file)
return result

View File

@@ -0,0 +1,114 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction remove command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import resource_record_sets as rrsets_util
from googlecloudsdk.api_lib.dns import transaction_util as trans_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.UniverseCompatible
class Remove(base.Command):
r"""Append a record-set deletion to the transaction.
This command appends a record-set deletion to the transaction.
## EXAMPLES
To remove an A record, run:
$ {command} --zone=MANAGED_ZONE --name=my.domain. --ttl=1234 \
--type=A "1.2.3.4"
To remove a TXT record with multiple data values, run:
$ {command} --zone=MANAGED_ZONE --name=my.domain. --ttl=2345 \
--type=TXT "Hello world" "Bye world"
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
parser.add_argument(
'--name', required=True,
help='DNS name of the record-set to be removed.')
parser.add_argument(
'--ttl', required=True, type=int,
help='TTL for the record-set to be removed.')
parser.add_argument(
'--type', required=True,
help='Type of the record-set to be removed.')
parser.add_argument(
'rrdatas', nargs='+',
help='DNS name of the record-set to be removed.')
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
with trans_util.TransactionFile(args.transaction_file) as trans_file:
change = trans_util.ChangeFromYamlFile(
trans_file, api_version=api_version)
dns = util.GetApiClient(api_version)
# Ensure the record to be removed exists
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params={
'project': properties.VALUES.core.project.GetOrFail,
},
collection='dns.managedZones')
record_to_remove = rrsets_util.CreateRecordSetFromArgs(
args,
zone_ref.project,
api_version=api_version)
existing_records = [record for record in list_pager.YieldFromList(
dns.resourceRecordSets,
dns.MESSAGES_MODULE.DnsResourceRecordSetsListRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
name=util.AppendTrailingDot(args.name),
type=args.type),
field='rrsets')]
if not existing_records or existing_records[0] != record_to_remove:
raise trans_util.RecordDoesNotExist('Record to be removed does not exist')
change.deletions.append(record_to_remove)
with trans_util.TransactionFile(args.transaction_file, 'w') as trans_file:
trans_util.WriteToYamlFile(trans_file, change)
log.status.Print(
'Record removal appended to transaction at [{0}].'.format(
args.transaction_file))

View File

@@ -0,0 +1,112 @@
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets transaction start command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from apitools.base.py import exceptions as apitools_exceptions
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import import_util
from googlecloudsdk.api_lib.dns import transaction_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core.util import files
class Start(base.Command):
"""Start a transaction.
This command starts a transaction.
## EXAMPLES
To start a transaction, run:
$ {command} --zone=MANAGED_ZONE
"""
@staticmethod
def Args(parser):
flags.GetZoneArg().AddToParser(parser)
def Run(self, args):
api_version = 'v1'
# If in the future there are differences between API version, do NOT use
# this patter of checking ReleaseTrack. Break this into multiple classes.
if self.ReleaseTrack() == base.ReleaseTrack.BETA:
api_version = 'v1beta2'
elif self.ReleaseTrack() == base.ReleaseTrack.ALPHA:
api_version = 'v1alpha2'
if os.path.isfile(args.transaction_file):
raise transaction_util.TransactionFileAlreadyExists(
'Transaction already exists at [{0}]'.format(args.transaction_file))
dns = util.GetApiClient(api_version)
# Get the managed-zone.
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params={
'project': properties.VALUES.core.project.GetOrFail,
},
collection='dns.managedZones')
try:
zone = dns.managedZones.Get(
dns.MESSAGES_MODULE.DnsManagedZonesGetRequest(
project=zone_ref.project,
managedZone=zone_ref.managedZone))
except apitools_exceptions.HttpError as error:
raise calliope_exceptions.HttpException(error)
# Initialize an empty change
change = dns.MESSAGES_MODULE.Change()
# Get the SOA record, there will be one and only one.
# Add addition and deletion for SOA incrementing to change.
records = [record for record in list_pager.YieldFromList(
dns.resourceRecordSets,
dns.MESSAGES_MODULE.DnsResourceRecordSetsListRequest(
project=zone_ref.project,
managedZone=zone_ref.Name(),
name=zone.dnsName,
type='SOA'),
field='rrsets')]
change.deletions.append(records[0])
change.additions.append(
import_util.NextSOARecordSet(records[0], api_version=api_version))
# Write change to transaction file
try:
with files.FileWriter(args.transaction_file) as transaction_file:
transaction_util.WriteToYamlFile(transaction_file, change)
except Exception as exp:
msg = 'Unable to write transaction [{0}] because [{1}]'
msg = msg.format(args.transaction_file, exp)
raise transaction_util.UnableToAccessTransactionFile(msg)
log.status.Print('Transaction started [{0}].'.format(
args.transaction_file))

View File

@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns record-sets update command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import resource_record_sets as rrsets_util
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
@base.ReleaseTracks(
base.ReleaseTrack.GA, base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA
)
@base.UniverseCompatible
class Update(base.UpdateCommand):
"""Updates a record-set in a managed-zone.
This command updates a record-set contained within the specified
managed-zone.
## EXAMPLES
To update a record-set with dnsName foo.bar.com., record type A to have rrdata
[1.2.3.4, 9.8.7.6] and ttl 60 in my_zone, run:
$ {command} foo.bar.com. --rrdatas=1.2.3.4,9.8.7.6 --type=A --ttl=60
--zone=my_zone
To update a record-set with dnsName foo.bar.com., record type A to have rrdata
[1.2.3.4, 9.8.7.6] and ttl 60 in my_zone that is located in us-east1-a, run:
$ {command} foo.bar.com. --rrdatas=1.2.3.4,9.8.7.6 --type=A --ttl=60
--zone=my_zone --location=us-east1-a
"""
@classmethod
def _IsBetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetZoneArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
flags.GetResourceRecordSetsNameArg().AddToParser(parser)
flags.GetResourceRecordSetsTypeArg(True).AddToParser(parser)
flags.GetResourceRecordSetsTtlArg(False).AddToParser(parser)
flags.GetResourceRecordSetsRrdatasArgGroup(
use_deprecated_names=cls._IsBetaOrAlpha(),
).AddToParser(parser)
parser.display_info.AddCacheUpdater(None)
parser.display_info.AddTransforms(flags.RESOURCERECORDSETS_TRANSFORMS)
parser.display_info.AddFormat(flags.RESOURCERECORDSETS_FORMAT)
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
messages = apis.GetMessagesModule('dns', api_version)
dns_client = util.GetApiClient(api_version)
zone_ref = util.GetRegistry(api_version).Parse(
args.zone,
params=util.GetParamsForRegistry(api_version, args),
collection='dns.managedZones')
resource_record_set = rrsets_util.CreateRecordSetFromArgs(
args,
zone_ref.project,
api_version,
)
request = messages.DnsResourceRecordSetsPatchRequest(
project=zone_ref.project,
managedZone=zone_ref.managedZone,
name=util.AppendTrailingDot(resource_record_set.name),
type=resource_record_set.type,
resourceRecordSet=resource_record_set,
)
if api_version == 'v2':
request.location = args.location
result = dns_client.resourceRecordSets.Patch(request)
return result

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class ResponsePolicy(base.Group):
"""Manage your Cloud DNS response policy.
## EXAMPLES
To create a response policy, run:
$ {command} create myresponsepolicy --description="My Response Policy" --network=''
To update a response policy, run:
$ {command} update myresponsepolicy --description="My Response Policy" --network=''
To delete a response policy, run:
$ {command} delete myresponsepolicy
To view the details of a response policy, run
$ {command} describe myresponsepolicy
To see a list of all response policies, run
$ {command} list
"""
pass

View File

@@ -0,0 +1,129 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies create command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
def _AddArgsCommon(parser):
flags.GetResponsePolicyDescriptionArg(required=True).AddToParser(parser)
flags.GetResponsePolicyNetworksArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
flags.GetResponsePolicyGkeClustersArg().AddToParser(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Create(base.UpdateCommand):
r"""Creates a new Cloud DNS response policy.
This command creates a new Cloud DNS response policy.
## EXAMPLES
To create a new response policy with minimal arguments, run:
$ {command} myresponsepolicy --description='My new response policy.'
--networks=''
To create a new response policy with all optional arguments, run:
$ {command} myresponsepolicy --description='My new response policy.'
--networks=network1,network2
To create a new zonal response policy scoped to a GKE cluster in
us-central1-a, run (alpha/beta):
$ {command} beta myresponsepolicy --description='My new response
policy.'
--gkeclusters=cluster1 --location=us-central1-a
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
resource_args.AddResponsePolicyResourceArg(
parser,
verb='to create',
api_version=util.GetApiFromTrack(cls.ReleaseTrack()))
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy
registry = util.GetRegistry(api_version)
response_policy_ref = registry.Parse(
args.response_policies,
util.GetParamsForRegistry(api_version, args),
collection='dns.responsePolicies')
response_policy_name = response_policy_ref.Name()
response_policy = messages.ResponsePolicy(
responsePolicyName=response_policy_name)
if args.IsSpecified('networks') or args.IsSpecified('gkeclusters'):
if args.networks == ['']:
args.networks = []
response_policy.networks = command_util.ParseResponsePolicyNetworks(
args.networks, response_policy_ref.project, api_version)
if args.IsSpecified('gkeclusters'):
gkeclusters = args.gkeclusters
response_policy.gkeClusters = [
messages.ResponsePolicyGKECluster(gkeClusterName=name)
for name in gkeclusters
]
else:
raise exceptions.RequiredArgumentException(
'--networks,--gkeclusters',
("""A list of networks or GKE clusters must be provided.'
NOTE: You can provide an empty value ("") for response policies that
have NO network or GKE clusters binding.
"""))
if args.IsSpecified('description'):
response_policy.description = args.description
create_request = messages.DnsResponsePoliciesCreateRequest(
responsePolicy=response_policy, project=response_policy_ref.project)
if api_version == 'v2':
create_request.location = args.location
result = client.responsePolicies.Create(create_request)
log.CreatedResource(response_policy_ref, kind='ResponsePolicy')
return result

View File

@@ -0,0 +1,80 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies delete command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
r"""Deletes a Cloud DNS response policy.
This command deletes a new Cloud DNS response policy.
## EXAMPLES
To delete a global response policy (default), run:
$ {command} myresponsepolicy
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
resource_args.AddResponsePolicyResourceArg(
parser, verb='to describe', api_version=api_version)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy
registry = util.GetRegistry(api_version)
response_policy_ref = registry.Parse(
args.response_policies,
util.GetParamsForRegistry(api_version, args),
collection='dns.responsePolicies')
response_policy_name = response_policy_ref.Name()
request = messages.DnsResponsePoliciesDeleteRequest(
responsePolicy=response_policy_name,
project=response_policy_ref.project)
if api_version == 'v2':
request.location = args.location
result = client.responsePolicies.Delete(request)
log.DeletedResource(response_policy_ref, kind='ResponsePolicy')
return result

View File

@@ -0,0 +1,77 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
r"""Describes a Cloud DNS response policy.
This command describes details of a Cloud DNS response policy.
## EXAMPLES
To describe a global response policy (default), run:
$ {command} myresponsepolicy
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
resource_args.AddResponsePolicyResourceArg(
parser, verb='to describe', api_version=api_version)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy
registry = util.GetRegistry(api_version)
response_policy_ref = registry.Parse(
args.response_policies,
util.GetParamsForRegistry(api_version, args),
collection='dns.responsePolicies')
response_policy_name = response_policy_ref.Name()
request = messages.DnsResponsePoliciesGetRequest(
responsePolicy=response_policy_name,
project=response_policy_ref.project)
if api_version == 'v2':
request.location = args.location
result = client.responsePolicies.Get(request)
return result

View File

@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
r"""Displays the list of all Cloud DNS response policies in a given project.
## EXAMPLES
To list response policies in Global Cloud DNS server (default), run:
$ {command}
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
request = messages.DnsResponsePoliciesListRequest(
project=properties.VALUES.core.project.GetOrFail())
if api_version == 'v2':
request.location = args.location
return list_pager.YieldFromList(
client.responsePolicies, request, field='responsePolicies')

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules command group."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class ResponsePolicyRules(base.Group):
"""Manage your Cloud DNS response policy rules.
## EXAMPLES
To create a new response policy rule with local data rrsets, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.zone.com."
--local-data=name=www.zone.com.,type=CNAME,ttl=21600,rrdatas=zone.com.
To create a new response policy rule with behavior, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.zone.com." --behavior=bypassResponsePolicy
To update a new response policy rule with local data rrsets, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--local-data=name=www.zone.com.,type=A,ttl=21600,rrdatas=1.2.3.4
To update a new response policy rule with behavior, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--behavior=bypassResponsePolicy
"""
pass

View File

@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules create command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
def _AddArgsCommon(parser):
"""Adds the common arguments for all versions."""
flags.GetLocalDataResourceRecordSets().AddToParser(parser)
# TODO(b/215745011) use AddResponsePolicyRulesBehaviorFlag once switch to v2
flags.GetResponsePolicyRulesBehavior().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.add_argument(
'--dns-name',
required=True,
help='DNS name (wildcard or exact) to apply this rule to.')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Create(base.UpdateCommand):
r"""Creates a new Cloud DNS response policy rule.
## EXAMPLES
To create a new response policy rule with local data rrsets, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.zone.com."
--local-data=name=www.zone.com.,type=CNAME,ttl=21600,rrdatas=zone.com.
To create a new response policy rule with behavior, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.zone.com." --behavior=bypassResponsePolicy
To create a new response policy rule with behavior in a zonal response
policy in us-east1-a, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.zone.com." --behavior=bypassResponsePolicy
--location=us-east1-a
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
_AddArgsCommon(parser)
resource_args.AddResponsePolicyRuleArg(
parser, verb='to create', api_version=api_version)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy Rule
registry = util.GetRegistry(api_version)
response_policy_rule_ref = registry.Parse(
args.response_policy_rule,
util.GetParamsForRegistry(api_version, args, parent='responsePolicies'),
collection='dns.responsePolicyRules')
response_policy_rule_name = response_policy_rule_ref.Name()
response_policy_rule = messages.ResponsePolicyRule(
ruleName=response_policy_rule_name)
response_policy_rule.dnsName = args.dns_name
if args.IsSpecified('behavior') and args.IsSpecified('local_data'):
raise exceptions.ConflictingArgumentsException(
'Only one of arguments [--behavior, --local-data] is allowed.')
if args.IsSpecified('behavior'):
response_policy_rule.behavior = command_util.ParseResponsePolicyRulesBehavior(
args, api_version)
elif args.IsSpecified('local_data'):
rrsets = []
for rrset in args.local_data:
resource_record_set = messages.ResourceRecordSet(
name=rrset.get('name'),
type=rrset.get('type'),
ttl=rrset.get('ttl'),
rrdatas=rrset.get('rrdatas').split('|'))
rrsets.append(resource_record_set)
local_data = messages.ResponsePolicyRuleLocalData(
localDatas=rrsets)
response_policy_rule.localData = local_data
create_request = messages.DnsResponsePolicyRulesCreateRequest(
responsePolicy=args.response_policy,
project=response_policy_rule_ref.project,
responsePolicyRule=response_policy_rule)
if api_version == 'v2':
create_request.location = args.location
result = client.responsePolicyRules.Create(create_request)
log.CreatedResource(response_policy_rule_ref, kind='ResponsePolicyRule')
return result

View File

@@ -0,0 +1,79 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules delete command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
r"""Deletes a Cloud DNS response policy rule.
## EXAMPLES
To delete a response policy rule, run:
$ {command} --response-policy=myresponsepolicy rulename
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
resource_args.AddResponsePolicyRuleArg(
parser, verb='to delete', api_version=api_version)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy Rule
registry = util.GetRegistry(api_version)
response_policy_rule_ref = registry.Parse(
args.response_policy_rule,
util.GetParamsForRegistry(api_version, args, parent='responsePolicies'),
collection='dns.responsePolicyRules')
response_policy_rule_name = response_policy_rule_ref.Name()
delete_request = messages.DnsResponsePolicyRulesDeleteRequest(
responsePolicy=args.response_policy,
project=response_policy_rule_ref.project,
responsePolicyRule=response_policy_rule_name)
if api_version == 'v2':
delete_request.location = args.location
result = client.responsePolicyRules.Delete(delete_request)
log.DeletedResource(response_policy_rule_ref, kind='ResponsePolicyRule')
return result

View File

@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Describe(base.DescribeCommand):
r"""Shows details about a Cloud DNS response policy rule.
## EXAMPLES
To show details about a response policy rule, run:
$ {command} --response-policy=myresponsepolicy rulename
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
api_version = util.GetApiFromTrack(cls.ReleaseTrack())
resource_args.AddResponsePolicyRuleArg(
parser, verb='to describe', api_version=api_version)
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy Rule
registry = util.GetRegistry(api_version)
response_policy_rule_ref = registry.Parse(
args.response_policy_rule,
util.GetParamsForRegistry(api_version, args, parent='responsePolicies'),
collection='dns.responsePolicyRules')
response_policy_rule_name = response_policy_rule_ref.Name()
request = messages.DnsResponsePolicyRulesGetRequest(
responsePolicy=args.response_policy,
responsePolicyRule=response_policy_rule_name,
project=properties.VALUES.core.project.GetOrFail())
if api_version == 'v2':
request.location = args.location
return client.responsePolicyRules.Get(request)

View File

@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
r"""Displays the list of all a Cloud DNS response policy rules.
## EXAMPLES
To list response policie rules in Global Cloud DNS server (default), run:
$ {command} myresponsepolicy
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
resource_args.AddResponsePolicyResourceArg(
parser,
verb='to list',
api_version=util.GetApiFromTrack(cls.ReleaseTrack()))
flags.GetLocationArg().AddToParser(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy
registry = util.GetRegistry(api_version)
response_policy_ref = registry.Parse(
args.response_policies,
util.GetParamsForRegistry(api_version, args),
collection='dns.responsePolicies')
list_request = messages.DnsResponsePolicyRulesListRequest(
responsePolicy=response_policy_ref.Name(),
project=response_policy_ref.project)
if api_version == 'v2':
list_request.location = args.location
return list_pager.YieldFromList(
client.responsePolicyRules, list_request, field='responsePolicyRules')

View File

@@ -0,0 +1,154 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies rules update command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
def _AddArgsCommon(parser):
"""Adds the common arguments for all versions."""
flags.GetLocalDataResourceRecordSets().AddToParser(parser)
# TODO(b/215745011) use AddResponsePolicyRulesBehaviorFlag once switch to v2
flags.GetResponsePolicyRulesBehavior().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
parser.add_argument(
'--dns-name',
required=False,
help='DNS name (wildcard or exact) to apply this rule to.')
def _FetchResponsePolicyRule(response_policy, response_policy_rule, api_version,
args):
"""Get response policy rule to be Updated."""
client = util.GetApiClient(api_version)
m = apis.GetMessagesModule('dns', api_version)
get_request = m.DnsResponsePolicyRulesGetRequest(
responsePolicy=response_policy,
project=properties.VALUES.core.project.Get(),
responsePolicyRule=response_policy_rule)
if api_version == 'v2':
get_request.location = args.location
return client.responsePolicyRules.Get(get_request)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
r"""Updates a new Cloud DNS response policy rule.
This command updates a new Cloud DNS response policy rule.
## EXAMPLES
To update a new response policy rule with DNS name, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--dns-name="www.newzone.com." # pylint: disable=line-too-long
To update a new response policy rule with local data rrsets, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--local-data=name=www.zone.com.,type=A,ttl=21600,rrdatas=1.2.3.4
To update a new response policy rule with behavior, run:
$ {command} myresponsepolicyrule --response-policy="myresponsepolicy"
--behavior=bypassResponsePolicy
"""
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
_AddArgsCommon(parser)
resource_args.AddResponsePolicyRuleArg(
parser, verb='to update', api_version='v1')
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy Rule
response_policy_rule_ref = args.CONCEPTS.response_policy_rule.Parse()
response_policy_rule_name = response_policy_rule_ref.Name()
response_policy_rule = messages.ResponsePolicyRule(
ruleName=response_policy_rule_name)
response_policy = messages.ResponsePolicy(
responsePolicyName=args.response_policy)
to_update = _FetchResponsePolicyRule(response_policy.responsePolicyName,
response_policy_rule.ruleName,
api_version, args)
if not args.IsSpecified('dns_name') and not args.IsSpecified(
'local_data') and not args.IsSpecified('behavior'):
log.status.Print('Nothing to update.')
return to_update
if args.IsSpecified('dns_name'):
to_update.dnsName = args.dns_name
if args.IsSpecified('local_data'):
to_update.behavior = None
rrsets = []
for rrset in args.local_data:
resource_record_set = messages.ResourceRecordSet(
name=rrset.get('name'),
type=rrset.get('type'),
ttl=rrset.get('ttl'),
rrdatas=rrset.get('rrdatas').split('|'))
rrsets.append(resource_record_set)
to_update.localData = messages.ResponsePolicyRuleLocalData(
localDatas=rrsets)
if args.IsSpecified('behavior'):
to_update.localData = None
to_update.behavior = command_util.ParseResponsePolicyRulesBehavior(
args, api_version)
update_req = messages.DnsResponsePolicyRulesUpdateRequest(
responsePolicy=response_policy.responsePolicyName,
responsePolicyRule=response_policy_rule.ruleName,
responsePolicyRuleResource=to_update,
project=properties.VALUES.core.project.Get())
if api_version == 'v2':
update_req.location = args.location
updated_response_policy_rule = client.responsePolicyRules.Update(update_req)
log.UpdatedResource(updated_response_policy_rule.responsePolicyRule,
kind='ResponsePolicyRule')
return updated_response_policy_rule

View File

@@ -0,0 +1,142 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""gcloud dns response-policies update command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.dns import util
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.dns import flags
from googlecloudsdk.command_lib.dns import resource_args
from googlecloudsdk.command_lib.dns import util as command_util
from googlecloudsdk.core import log
def _AddArgsCommon(parser):
flags.GetResponsePolicyDescriptionArg().AddToParser(parser)
flags.GetResponsePolicyNetworksArg().AddToParser(parser)
flags.GetResponsePolicyGkeClustersArg().AddToParser(parser)
flags.GetLocationArg().AddToParser(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA, base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@base.UniverseCompatible
class Update(base.UpdateCommand):
r"""Updates a Cloud DNS response policy.
This command updates a Cloud DNS response policy.
## EXAMPLES
To update a response policy with minimal arguments, run:
$ {command} myresponsepolicy --description='My updated response policy.'
--networks=''
To update a response policy with all optional arguments, run:
$ {command} myresponsepolicy --description='My updated response policy.'
--networks=network1,network2
To update a new zonal response policy scoped to a GKE cluster in
us-central1-a, run:
$ {command} myresponsepolicy --description='My new response policy.'
--gkeclusters=cluster1 --location=us-central1-a
"""
def _FetchResponsePolicy(self, response_policy_ref, api_version, args):
"""Get response policy to be Updated."""
client = util.GetApiClient(api_version)
message_module = apis.GetMessagesModule('dns', api_version)
get_request = message_module.DnsResponsePoliciesGetRequest(
responsePolicy=response_policy_ref.Name(),
project=response_policy_ref.project)
if api_version == 'v2':
get_request.location = args.location
return client.responsePolicies.Get(get_request)
@classmethod
def _BetaOrAlpha(cls):
return cls.ReleaseTrack() in (base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
@classmethod
def Args(cls, parser):
resource_args.AddResponsePolicyResourceArg(
parser,
verb='to update',
api_version=util.GetApiFromTrack(cls.ReleaseTrack()))
_AddArgsCommon(parser)
parser.display_info.AddFormat('json')
def Run(self, args):
api_version = util.GetApiFromTrackAndArgs(self.ReleaseTrack(), args)
client = util.GetApiClient(api_version)
messages = apis.GetMessagesModule('dns', api_version)
# Get Response Policy
registry = util.GetRegistry(api_version)
response_policy_ref = registry.Parse(
args.response_policies,
util.GetParamsForRegistry(api_version, args),
collection='dns.responsePolicies',
)
to_update = self._FetchResponsePolicy(
response_policy_ref, api_version, args
)
if not (
args.IsSpecified('networks')
or args.IsSpecified('description')
or args.IsSpecified('gkeclusters')
):
log.status.Print('Nothing to update.')
return to_update
if args.IsSpecified('networks'):
if args.networks == ['']:
args.networks = []
to_update.networks = command_util.ParseResponsePolicyNetworks(
args.networks, response_policy_ref.project, api_version)
if args.IsSpecified('gkeclusters'):
gkeclusters = args.gkeclusters
to_update.gkeClusters = [
messages.ResponsePolicyGKECluster(gkeClusterName=name)
for name in gkeclusters
]
if args.IsSpecified('description'):
to_update.description = args.description
update_req = messages.DnsResponsePoliciesUpdateRequest(
responsePolicy=response_policy_ref.Name(),
responsePolicyResource=to_update,
project=response_policy_ref.project)
if api_version == 'v2':
update_req.location = args.location
updated_response_policy = client.responsePolicies.Update(update_req)
log.UpdatedResource(updated_response_policy.responsePolicy,
kind='ResponsePolicy')
return updated_response_policy