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,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,
)