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,50 @@
# -*- 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.
"""Commands for reading and manipulating backend buckets."""
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.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class BackendBuckets(base.Group):
"""Read and manipulate backend buckets.
Backend buckets define Cloud Storage buckets that can serve content.
URL maps define which requests are sent to which backend buckets. For more
information, see:
https://cloud.google.com/load-balancing/docs/https/ext-load-balancer-backend-buckets.
"""
BackendBuckets.category = base.LOAD_BALANCING_CATEGORY
BackendBuckets.detailed_help = {
'DESCRIPTION': """
Read and manipulate backend buckets. Backend buckets define Cloud
Storage buckets that can serve content. URL maps define which
requests are sent to which backend buckets.
For more information about backend buckets, see the
[backend buckets documentation](https://cloud.google.com/load-balancing/docs/https/ext-load-balancer-backend-buckets).
See also: [Backend buckets API](https://cloud.google.com/compute/docs/reference/rest/v1/backendBuckets).
""",
}

View File

@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 to set IAM policy for a resource."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class AddIamPolicyBinding(base.Command):
"""Add an IAM policy binding to a Compute Engine backend bucket."""
@staticmethod
def Args(parser):
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.AddArgument(parser)
iam_util.AddArgsForAddIamPolicyBinding(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket_ref = (
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client)))
policy = backend_buckets_utils.GetIamPolicy(backend_bucket_ref, client)
iam_util.AddBindingToIamPolicy(
client.messages.Binding, policy, args.member, args.role
)
return backend_buckets_utils.SetIamPolicy(
backend_bucket_ref, client, policy
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class AddIamPolicyBindingAlpha(AddIamPolicyBinding):
"""Add an IAM policy binding to a Compute Engine backend bucket."""
AddIamPolicyBinding.detailed_help = {
'brief':
'Add an IAM policy binding to a Compute Engine backend bucket.',
'DESCRIPTION':
"""\
Add an IAM policy binding to a Compute Engine backend bucket. """,
'EXAMPLES':
"""\
To add an IAM policy binding for the role of
'compute.loadBalancerServiceUser' for the user 'test-user@gmail.com' with
backend bucket 'my-backend-bucket' and region 'REGION', run:
$ {command} my-backend-bucket --region=REGION \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
To add an IAM policy binding for the role of
'compute.loadBalancerServiceUser' for the user 'test-user@gmail.com' with
global backend bucket 'my-backend-bucket', run either of the following:
$ {command} my-backend-bucket --global \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
$ {command} my-backend-bucket \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
""",
'API REFERENCE': """\
This command uses the compute API. The full documentation for this
API can be found at: https://cloud.google.com/compute/""",
}

View File

@@ -0,0 +1,35 @@
release_tracks: [GA]
help_text:
brief: Add an IAM policy binding to a Compute Engine backend bucket.
description: |
Add an IAM policy binding to a Compute Engine backend bucket.
examples: |
To add an IAM policy binding for the role of 'compute.loadBalancerServiceUser'
for the user 'test-user@gmail.com' with backend bucket 'my-backend-bucket' run:
$ {command} my-backend-bucket --member='user:test-user@gmail.com' --role='roles/compute.loadBalancerServiceUser'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: compute.backendBuckets
use_relative_name: false
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
iam:
set_iam_policy_request_path: globalSetPolicyRequest
message_type_overrides:
policy: Policy
set_iam_policy_request: ComputeBackendBucketsSetIamPolicyRequest
arguments:
resource:
help_text: The backend bucket for which to add the IAM policy to.
spec: !REF googlecloudsdk.command_lib.compute.resources:backend_bucket
override_resource_collection: true

View File

@@ -0,0 +1,91 @@
# -*- 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.
"""Command to add a Cloud CDN Signed URL key to a backend bucket."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.operations import poller
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import signed_url_flags
from googlecloudsdk.command_lib.compute.backend_buckets import flags
from googlecloudsdk.core.util import files
@base.UniverseCompatible
class AddSignedUrlKey(base.UpdateCommand):
"""Add Cloud CDN Signed URL key to a backend bucket.
*{command}* is used to add a new Cloud CDN Signed URL key to a backend bucket.
Cloud CDN Signed URLs give you a way to serve responses from the
globally distributed CDN cache, even if the request needs to be
authorized.
Signed URLs are a mechanism to temporarily give a client access to a
private resource without requiring additional authorization. To achieve
this, the full request URL that should be allowed is hashed
and cryptographically signed. By using the signed URL you give it, that
one request will be considered authorized to receive the requested
content.
Generally, a signed URL can be used by anyone who has it. However, it
is usually only intended to be used by the client that was directly
given the URL. To mitigate this, they expire at a time chosen by the
issuer. To minimize the risk of a signed URL being shared, it is recommended
that the signed URL be set to expire as soon as possible.
A 128-bit secret key is used for signing the URLs.
"""
@staticmethod
def Args(parser):
"""Set up arguments for this command."""
AddSignedUrlKey.BACKEND_BUCKET_ARG = flags.BackendBucketArgument()
AddSignedUrlKey.BACKEND_BUCKET_ARG.AddArgument(
parser, operation_type='add CDN signed URL key to')
signed_url_flags.AddCdnSignedUrlKeyName(parser, required=True)
signed_url_flags.AddCdnSignedUrlKeyFile(parser, required=True)
def Run(self, args):
"""Issues the request to add Signed URL key to the backend service."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
api_client = holder.client.apitools_client
messages = holder.client.messages
service = api_client.backendBuckets
backend_bucket_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
key_value = files.ReadFileContents(args.key_file).rstrip()
request = messages.ComputeBackendBucketsAddSignedUrlKeyRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name(),
signedUrlKey=messages.SignedUrlKey(
keyName=args.key_name, keyValue=key_value))
operation = service.AddSignedUrlKey(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.globalOperations')
operation_poller = poller.Poller(service)
return waiter.WaitFor(operation_poller, operation_ref,
'Adding Cloud CDN Signed URL key to [{0}]'.format(
backend_bucket_ref.Name()))

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 Compute Engine backend bucket 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 Compute Engine backend bucket configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Compute Engine backend bucket.
description: |
*{command}* exports the configuration for a Compute Engine backend bucket.
Backend bucket 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
backend buckets within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a backend bucket, run:
$ {command} my-backend-bucket
To export the configuration for a backend bucket to a file, run:
$ {command} my-backend-bucket --path=/path/to/dir/
To export the configuration for a backend bucket in Terraform
HCL format, run:
$ {command} my-backend-bucket --resource-format=terraform
To export the configurations for all backend buckets within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Backend bucket to export the configuration for.
spec: !REF googlecloudsdk.command_lib.compute.resources:backend_bucket

View File

@@ -0,0 +1,244 @@
# -*- 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.
"""Command for creating backend buckets."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import cdn_flags_utils as cdn_flags
from googlecloudsdk.command_lib.compute import exceptions as compute_exceptions
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import resource_manager_tags_utils
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute import signed_url_flags
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags as backend_buckets_flags
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Create(base.CreateCommand):
"""Create a backend bucket.
*{command}* is used to create backend buckets. Backend buckets
define Google Cloud Storage buckets that can serve content. URL
maps define which requests are sent to which backend buckets.
"""
BACKEND_BUCKET_ARG = None
_support_regional_statera_load_balancers = False
@classmethod
def Args(cls, parser):
"""Set up arguments for this command."""
parser.display_info.AddFormat(backend_buckets_flags.DEFAULT_LIST_FORMAT)
backend_buckets_flags.AddUpdatableArgs(
cls, parser, 'create', cls._support_regional_statera_load_balancers
)
backend_buckets_flags.REQUIRED_GCS_BUCKET_ARG.AddArgument(parser)
parser.display_info.AddCacheUpdater(
backend_buckets_flags.BackendBucketsCompleter)
signed_url_flags.AddSignedUrlCacheMaxAge(parser, required=False)
cdn_flags.AddCdnPolicyArgs(parser, 'backend bucket')
backend_buckets_flags.AddCacheKeyExtendedCachingArgs(parser)
backend_buckets_flags.AddCompressionMode(parser)
backend_buckets_flags.AddLoadBalancingScheme(
parser, cls._support_regional_statera_load_balancers
)
backend_buckets_flags.AddResourceManagerTags(parser)
def CreateBackendBucket(self, args):
"""Creates and returns the backend bucket."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_buckets_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL)
enable_cdn = args.enable_cdn or False
backend_bucket = client.messages.BackendBucket(
description=args.description,
name=backend_buckets_ref.Name(),
bucketName=args.gcs_bucket_name,
enableCdn=enable_cdn,
)
backend_buckets_utils.ApplyCdnPolicyArgs(client, args, backend_bucket)
if args.custom_response_header is not None:
backend_bucket.customResponseHeaders = args.custom_response_header
if (
backend_bucket.cdnPolicy is not None
and backend_bucket.cdnPolicy.cacheMode
and args.enable_cdn is not False # pylint: disable=g-bool-id-comparison
):
backend_bucket.enableCdn = True
if args.compression_mode is not None:
backend_bucket.compressionMode = (
client.messages.BackendBucket.CompressionModeValueValuesEnum(
args.compression_mode
)
)
if args.load_balancing_scheme is not None:
backend_bucket.loadBalancingScheme = (
client.messages.BackendBucket.LoadBalancingSchemeValueValuesEnum(
args.load_balancing_scheme
)
)
return backend_bucket
def Run(self, args):
"""Issues the request necessary for creating a backend bucket."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket = self.CreateBackendBucket(args)
if self._support_regional_statera_load_balancers:
ref = backend_buckets_flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL
)
if ref.Collection() == 'compute.backendBuckets':
requests = self._CreateGlobalRequests(backend_bucket, ref)
elif ref.Collection() == 'compute.regionBackendBuckets':
requests = self._CreateRegionalRequests(args, backend_bucket, ref)
self._ApplyResourceManagerTags(args, backend_bucket, ref, client)
return client.MakeRequests(requests)
if args.resource_manager_tags is not None:
backend_bucket.params = self._CreateBackendBucketParams(
client.messages, args.resource_manager_tags
)
backend_buckets_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args, holder.resources)
return client.MakeRequests(
self._CreateGlobalRequests(backend_bucket, backend_buckets_ref)
)
def _ApplyResourceManagerTags(self, args, backend_bucket, ref, client):
if args.resource_manager_tags is None:
return
if ref.Collection() == 'compute.backendBuckets':
backend_bucket.params = self._CreateBackendBucketParams(
client.messages, args.resource_manager_tags
)
elif ref.Collection() == 'compute.regionBackendBuckets':
raise compute_exceptions.ArgumentError(
'--resource-manager-tags',
'Resource Manager tags are not supported for regional backend'
' buckets.',
)
def _CreateBackendBucketParams(self, messages, resource_manager_tags):
resource_manager_tags_map = (
resource_manager_tags_utils.GetResourceManagerTags(
resource_manager_tags
)
)
params = messages.BackendBucketParams
additional_properties = [
params.ResourceManagerTagsValue.AdditionalProperty(key=key, value=value)
for key, value in sorted(resource_manager_tags_map.items())
]
return params(
resourceManagerTags=params.ResourceManagerTagsValue(
additionalProperties=additional_properties
)
)
def _CreateGlobalRequests(self, backend_bucket, backend_buckets_ref):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
request = client.messages.ComputeBackendBucketsInsertRequest(
backendBucket=backend_bucket, project=backend_buckets_ref.project
)
return [(client.apitools_client.backendBuckets, 'Insert', request)]
def _CreateRegionalRequests(self, args, backend_bucket, backend_buckets_ref):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
request = client.messages.ComputeRegionBackendBucketsInsertRequest(
backendBucket=backend_bucket,
project=backend_buckets_ref.project,
region=args.region,
)
return [(client.apitools_client.regionBackendBuckets, 'Insert', request)]
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class CreateBeta(Create):
"""Create a backend bucket.
*{command}* is used to create backend buckets. Backend buckets
define Google Cloud Storage buckets that can serve content. URL
maps define which requests are sent to which backend buckets.
To create a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To create a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_statera_load_balancers = True
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class CreateAlpha(CreateBeta):
"""Create a backend bucket.
*{command}* is used to create backend buckets. Backend buckets
define Google Cloud Storage buckets that can serve content. URL
maps define which requests are sent to which backend buckets.
To create a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To create a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_statera_load_balancers = True

View File

@@ -0,0 +1,148 @@
# -*- 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.
"""Command for deleting backend buckets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import flags
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Delete(base.DeleteCommand):
"""Delete backend buckets.
*{command}* deletes one or more backend buckets.
"""
BACKEND_BUCKET_ARG = None
_support_regional_global_flags = False
@classmethod
def Args(cls, parser):
if cls._support_regional_global_flags:
cls.BACKEND_BUCKET_ARG = flags.GLOBAL_REGIONAL_MULTI_BACKEND_BUCKET_ARG
cls.BACKEND_BUCKET_ARG.AddArgument(
parser, operation_type='delete'
)
else:
cls.BACKEND_BUCKET_ARG = flags.BackendBucketArgument(plural=True)
cls.BACKEND_BUCKET_ARG.AddArgument(parser, operation_type='delete')
parser.display_info.AddCacheUpdater(flags.BackendBucketsCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
if self._support_regional_global_flags:
backend_bucket_refs = (
self.BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
)
else:
backend_bucket_refs = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
)
utils.PromptForDeletion(backend_bucket_refs)
requests = []
for backend_bucket_ref in backend_bucket_refs:
if (
self._support_regional_global_flags
and backend_bucket_ref.Collection() == 'compute.regionBackendBuckets'
):
requests.append((
client.apitools_client.regionBackendBuckets,
'Delete',
client.messages.ComputeRegionBackendBucketsDeleteRequest(
**backend_bucket_ref.AsDict()
),
))
else:
requests.append((
client.apitools_client.backendBuckets,
'Delete',
client.messages.ComputeBackendBucketsDeleteRequest(
**backend_bucket_ref.AsDict()
),
))
return client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class DeleteBeta(Delete):
"""Delete backend buckets.
*{command}* deletes one or more backend buckets.
To delete a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To delete a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_global_flags = True
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class DeleteAlpha(DeleteBeta):
"""Delete backend buckets.
*{command}* deletes one or more backend buckets.
To delete a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To delete a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_global_flags = True

View File

@@ -0,0 +1,87 @@
# -*- 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.
"""Command to delete a Cloud CDN Signed URL key from a backend bucket."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute.operations import poller
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import signed_url_flags
from googlecloudsdk.command_lib.compute.backend_buckets import flags
class DeleteSignedUrlKey(base.UpdateCommand):
"""Delete Cloud CDN Signed URL key from a backend bucket.
*{command}* deletes an existing Cloud CDN Signed URL key from a backend
bucket.
Cloud CDN Signed URLs give you a way to serve responses from the
globally distributed CDN cache, even if the request needs to be
authorized.
Signed URLs are a mechanism to temporarily give a client access to a
private resource without requiring additional authorization. To achieve
this, the full request URL that should be allowed is hashed
and cryptographically signed. By using the signed URL you give it, that
one request will be considered authorized to receive the requested
content.
Generally, a signed URL can be used by anyone who has it. However, it
is usually only intended to be used by the client that was directly
given the URL. To mitigate this, they expire at a time chosen by the
issuer. To minimize the risk of a signed URL being shared, it is recommended
that the signed URL be set to expire as soon as possible.
A 128-bit secret key is used for signing the URLs.
"""
@staticmethod
def Args(parser):
"""Set up arguments for this command."""
DeleteSignedUrlKey.BACKEND_BUCKET_ARG = flags.BackendBucketArgument()
DeleteSignedUrlKey.BACKEND_BUCKET_ARG.AddArgument(
parser, operation_type='delete CDN signed URL key from')
signed_url_flags.AddCdnSignedUrlKeyName(parser, required=True)
def Run(self, args):
"""Issues the request to delete Signed URL key from the backend service."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
api_client = holder.client.apitools_client
messages = holder.client.messages
service = api_client.backendBuckets
backend_bucket_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client))
request = messages.ComputeBackendBucketsDeleteSignedUrlKeyRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name(),
keyName=args.key_name)
operation = service.DeleteSignedUrlKey(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.globalOperations')
operation_poller = poller.Poller(service)
return waiter.WaitFor(operation_poller, operation_ref,
'Deleting Cloud CDN Signed URL key from [{0}]'.format(
backend_bucket_ref.Name()))

View File

@@ -0,0 +1,128 @@
# -*- 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.
"""Command for describing backend buckets."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import flags
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.DefaultUniverseOnly
class Describe(base.DescribeCommand):
"""Describe a backend bucket.
*{command}* displays all data associated with a backend bucket in a
project.
"""
BACKEND_BUCKET_ARG = None
_support_regional_global_flags = False
@classmethod
def Args(cls, parser):
cls.BACKEND_BUCKET_ARG = (
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG
if cls._support_regional_global_flags
else flags.BackendBucketArgument()
)
cls.BACKEND_BUCKET_ARG.AddArgument(parser, operation_type='describe')
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
requests = []
if backend_bucket_ref.Collection() == 'compute.backendBuckets':
requests = [(
client.apitools_client.backendBuckets,
'Get',
client.messages.ComputeBackendBucketsGetRequest(
**backend_bucket_ref.AsDict()
),
)]
elif backend_bucket_ref.Collection() == 'compute.regionBackendBuckets':
requests = [(
client.apitools_client.regionBackendBuckets,
'Get',
client.messages.ComputeRegionBackendBucketsGetRequest(
**backend_bucket_ref.AsDict()
),
)]
return client.MakeRequests(requests)[0]
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class DescribeBeta(Describe):
"""Describe a backend bucket.
*{command}* displays all data associated with a backend bucket in a
project.
To describe a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To describe a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_global_flags = True
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class DescribeAlpha(DescribeBeta):
"""Describe a backend bucket.
*{command}* displays all data associated with a backend bucket in a
project.
To describe a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--global
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
To describe a regional backend bucket, run the following:
$ {command} my-backend-bucket
--gcs-bucket-name gcs-bucket-1
--region=us-central1
"""
_support_regional_global_flags = True

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 to get IAM policy for a resource."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for a Compute Engine backend bucket."""
@staticmethod
def Args(parser):
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.AddArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket_ref = (
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
)
)
return backend_buckets_utils.GetIamPolicy(backend_bucket_ref, client)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class GetIamPolicyAlpha(GetIamPolicy):
"""Get the IAM policy for a Compute Engine backend bucket."""
GetIamPolicy.detailed_help = {
'brief': 'Get the IAM policy for a Compute Engine backend bucket.',
'DESCRIPTION': """\
*{command}* displays the IAM policy associated with a
Compute Engine backend bucket in a project. If formatted as JSON,
the output can be edited and used as a policy file for
set-iam-policy. The output includes an "etag" field
identifying the version emitted and allowing detection of
concurrent policy updates; see
$ {parent} set-iam-policy for additional details. """,
'EXAMPLES':
"""\
To print the IAM policy for a given regional backend bucket, run:
$ {command} my-backend-bucket --region=REGION
To print the IAM policy for a given global backend bucket, run either of
the following:
$ {command} my-backend-bucket --global
$ {command} my-backend-bucket
""",
'API REFERENCE':
"""\
This command uses the compute API. The full documentation for this
API can be found at: https://cloud.google.com/compute/""",
}

View File

@@ -0,0 +1,30 @@
release_tracks: [GA]
help_text:
brief: Get the IAM policy for a Compute Engine backend bucket.
description: |
*{command}* displays the IAM policy associated with a
Compute Engine backend bucket in a project. If formatted as JSON,
the output can be edited and used as a policy file for
set-iam-policy. The output includes an "etag" field
identifying the version emitted and allowing detection of
concurrent policy updates; see
$ {parent} set-iam-policy for additional details.
examples: |
To print the IAM policy for a given backend bucket, run:
$ {command} my-backend-bucket
request:
collection: compute.backendBuckets
use_relative_name: false
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
arguments:
resource:
help_text: The network to display the IAM policy for.
spec: !REF googlecloudsdk.command_lib.compute.resources:backend_bucket

View File

@@ -0,0 +1,88 @@
# -*- 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.
"""Command for listing backend buckets."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import lister
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import completers
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import flags
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class List(base.ListCommand):
"""List backend buckets."""
_support_regional_global_flags = False
@classmethod
def Args(cls, parser):
if cls._support_regional_global_flags:
List.detailed_help = base_classes.GetGlobalRegionalListerHelp(
'backend buckets'
)
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
if cls._support_regional_global_flags:
lister.AddMultiScopeListerFlags(
parser, zonal=False, regional=True, global_=True
)
else:
lister.AddBaseListerArgs(parser)
parser.display_info.AddCacheUpdater(completers.InstancesCompleter)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
if self._support_regional_global_flags:
request_data = lister.ParseMultiScopeFlags(
args,
holder.resources,
default_scope_set=compute_scope.ScopeEnum.GLOBAL,
)
list_implementation = lister.MultiScopeLister(
client,
regional_service=client.apitools_client.regionBackendBuckets,
global_service=client.apitools_client.backendBuckets,
)
else:
request_data = lister.ParseNamesAndRegexpFlags(args, holder.resources)
list_implementation = lister.GlobalLister(
client, client.apitools_client.backendBuckets
)
return lister.Invoke(request_data, list_implementation)
List.detailed_help = base_classes.GetGlobalListerHelp('backend buckets')
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.UniverseCompatible
class ListBeta(List):
"""List backend buckets."""
_support_regional_global_flags = True
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.UniverseCompatible
class ListAlpha(ListBeta):
"""List backend buckets."""
_support_regional_global_flags = True

View File

@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 to remove IAM policy for a backend bucket."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class RemoveIamPolicyBinding(base.Command):
"""Remove an IAM policy binding from a Compute Engine backend bucket."""
@staticmethod
def Args(parser):
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.AddArgument(parser)
iam_util.AddArgsForRemoveIamPolicyBinding(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_service_ref = (
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
)
)
policy = backend_buckets_utils.GetIamPolicy(backend_service_ref, client)
iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
return backend_buckets_utils.SetIamPolicy(
backend_service_ref, client, policy
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class RemoveIamPolicyBindingAlpha(RemoveIamPolicyBinding):
"""Remove an IAM policy binding from a Compute Engine backend bucket."""
RemoveIamPolicyBinding.detailed_help = {
'brief': (
'Remove an IAM policy binding from a Compute Engine backend bucket.'
),
'DESCRIPTION': """\
Remove an IAM policy binding from a Compute Engine backend bucket. """,
'EXAMPLES': """\
To remove an IAM policy binding for the role of
'roles/compute.loadBalancerServiceUser' for the user 'test-user@gmail.com'
with backend bucket 'my-backend-bucket' and region 'REGION', run:
$ {command} my-backend-bucket --region=REGION \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
To remove an IAM policy binding for the role of
'roles/compute.loadBalancerServiceUser' for the user 'test-user@gmail.com'
with globalbackend bucket 'my-backend-bucket', run either of the following:
$ {command} my-backend-bucket --global \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
$ {command} my-backend-bucket \
--member='user:test-user@gmail.com' \
--role='roles/compute.loadBalancerServiceUser'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
""",
'API REFERENCE': """\
This command uses the compute API. The full documentation for this
API can be found at: https://cloud.google.com/compute/""",
}

View File

@@ -0,0 +1,36 @@
release_tracks: [GA]
help_text:
brief: Remove an IAM policy binding from a Compute Engine backend bucket.
description: |
Remove an IAM policy binding from a Compute Engine backend bucket.
examples: |
To remove an IAM policy binding for the role of 'roles/compute.loadBalancerServiceUser'
for the user 'test-user@gmail.com' with backend bucket 'my-backend-bucket' run:
$ {command} my-backend-bucket --member='user:test-user@gmail.com' --role='roles/compute.loadBalancerServiceUser'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: compute.backendBuckets
use_relative_name: false
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
iam:
set_iam_policy_request_path: globalSetPolicyRequest
message_type_overrides:
policy: Policy
set_iam_policy_request: ComputeBackendBucketsSetIamPolicyRequest
arguments:
resource:
help_text: The backend bucket for which to remove the IAM policy from.
spec: !REF googlecloudsdk.command_lib.compute.resources:backend_bucket
override_resource_collection: true

View File

@@ -0,0 +1,90 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 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 to set IAM policy for a resource."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags
from googlecloudsdk.command_lib.iam import iam_util
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.DefaultUniverseOnly
class SetIamPolicy(base.Command):
"""Set the IAM policy binding for a Compute Engine backend bucket."""
@staticmethod
def Args(parser):
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.AddArgument(
parser, operation_type='setIamPolicy'
)
iam_util.AddArgForPolicyFile(parser)
def Run(self, args):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
backend_bucket_ref = (
flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG_IAM.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.GLOBAL,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
)
)
policy = iam_util.ParsePolicyFile(args.policy_file, client.messages.Policy)
policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION
return backend_buckets_utils.SetIamPolicy(
backend_bucket_ref, client, policy
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.DefaultUniverseOnly
class SetIamPolicyAlpha(SetIamPolicy):
"""Set the IAM policy binding for a Compute Engine backend bucket."""
SetIamPolicy.detailed_help = {
'brief': 'Set the IAM policy binding for a Compute Engine backend bucket.',
'DESCRIPTION': """\
Sets the IAM policy for the given backend bucket as defined in a
JSON or YAML file. """,
'EXAMPLES': """\
The following command will read an IAM policy defined in a JSON file
'policy.json' and set it for the regionalbackend bucket `my-backend-bucket`:
$ {command} my-backend-bucket policy.json --region=REGION
The following commands will read an IAM policy defined in a JSON file
'policy.json' and set it for the global backend bucket `my-backend-bucket`:
$ {command} my-backend-bucket policy.json --global
$ {command} my-backend-bucket policy.json
See https://cloud.google.com/iam/docs/managing-policies for details of the
policy file format and contents.
""",
'API REFERENCE': """\
This command uses the compute API. The full documentation for this
API can be found at: https://cloud.google.com/compute/""",
}

View File

@@ -0,0 +1,37 @@
release_tracks: [GA]
help_text:
brief: Set the IAM policy binding for a Compute Engine backend bucket.
description: |
Sets the IAM policy for the given backend bucket as defined in a JSON or YAML file.
examples: |
The following command reads an IAM policy defined in a JSON file called 'policy.json' and sets it for the backend bucket called 'my-backend-bucket':
$ {command} my-backend-bucket policy.json
See https://cloud.google.com/iam/docs/managing-policies for details of the
policy file format and contents.
request:
collection: compute.backendBuckets
use_relative_name: false
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:UseMaxRequestedPolicyVersion:api_field=globalSetPolicyRequest.policy.version
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
iam:
set_iam_policy_request_path: globalSetPolicyRequest
message_type_overrides:
policy: Policy
set_iam_policy_request: ComputeBackendBucketsSetIamPolicyRequest
arguments:
resource:
help_text: The backend bucket to set the IAM policy for.
spec: !REF googlecloudsdk.command_lib.compute.resources:backend_bucket
override_resource_collection: true

View File

@@ -0,0 +1,306 @@
# -*- 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.
"""Commands for updating backend buckets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import encoding
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import cdn_flags_utils as cdn_flags
from googlecloudsdk.command_lib.compute import exceptions
from googlecloudsdk.command_lib.compute import flags as compute_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute import signed_url_flags
from googlecloudsdk.command_lib.compute.backend_buckets import backend_buckets_utils
from googlecloudsdk.command_lib.compute.backend_buckets import flags as backend_buckets_flags
from googlecloudsdk.command_lib.compute.security_policies import (
flags as security_policy_flags)
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Update(base.UpdateCommand):
"""Update a backend bucket.
*{command}* is used to update backend buckets.
"""
BACKEND_BUCKET_ARG = None
EDGE_SECURITY_POLICY_ARG = None
support_regional_global_flags = False
@classmethod
def Args(cls, parser):
"""Set up arguments for this command."""
backend_buckets_flags.AddUpdatableArgs(
cls, parser, 'update', cls.support_regional_global_flags
)
backend_buckets_flags.GCS_BUCKET_ARG.AddArgument(parser)
signed_url_flags.AddSignedUrlCacheMaxAge(
parser, required=False, unspecified_help='')
cdn_flags.AddCdnPolicyArgs(parser, 'backend bucket', update_command=True)
cls.EDGE_SECURITY_POLICY_ARG = (
security_policy_flags.EdgeSecurityPolicyArgumentForTargetResource(
resource='backend bucket'))
cls.EDGE_SECURITY_POLICY_ARG.AddArgument(parser)
backend_buckets_flags.AddCacheKeyExtendedCachingArgs(parser)
backend_buckets_flags.AddCompressionMode(parser)
def AnyArgsSpecified(self, args):
"""Returns true if any args for updating backend bucket were specified."""
return (args.IsSpecified('description') or
args.IsSpecified('gcs_bucket_name') or
args.IsSpecified('enable_cdn') or
args.IsSpecified('edge_security_policy') or
args.IsSpecified('cache_key_include_http_header') or
args.IsSpecified('cache_key_query_string_whitelist') or
args.IsSpecified('compression_mode'))
def AnyFlexibleCacheArgsSpecified(self, args):
"""Returns true if any Flexible Cache args for updating backend bucket were specified."""
return any(
(args.IsSpecified('cache_mode'), args.IsSpecified('client_ttl'),
args.IsSpecified('no_client_ttl'), args.IsSpecified('default_ttl'),
args.IsSpecified('no_default_ttl'), args.IsSpecified('max_ttl'),
args.IsSpecified('no_max_ttl'),
args.IsSpecified('custom_response_header'),
args.IsSpecified('no_custom_response_headers'),
args.IsSpecified('negative_caching'),
args.IsSpecified('negative_caching_policy'),
args.IsSpecified('no_negative_caching_policies'),
args.IsSpecified('serve_while_stale'),
args.IsSpecified('no_serve_while_stale'),
args.IsSpecified('bypass_cache_on_request_headers'),
args.IsSpecified('no_bypass_cache_on_request_headers')))
def GetGetRequest(self, client, backend_bucket_ref):
"""Returns a request to retrieve the backend bucket."""
if backend_bucket_ref.Collection() == 'compute.regionBackendBuckets':
return (
client.apitools_client.regionBackendBuckets,
'Get',
client.messages.ComputeRegionBackendBucketsGetRequest(
project=backend_bucket_ref.project,
region=backend_bucket_ref.region,
backendBucket=backend_bucket_ref.Name(),
),
)
return (client.apitools_client.backendBuckets, 'Get',
client.messages.ComputeBackendBucketsGetRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name()))
def GetSetRequest(self, client, backend_bucket_ref, replacement):
"""Returns a request to update the backend bucket."""
if backend_bucket_ref.Collection() == 'compute.regionBackendBuckets':
return (
client.apitools_client.regionBackendBuckets,
'Patch',
client.messages.ComputeRegionBackendBucketsPatchRequest(
project=backend_bucket_ref.project,
region=backend_bucket_ref.region,
backendBucket=backend_bucket_ref.Name(),
backendBucketResource=replacement,
),
)
return (client.apitools_client.backendBuckets, 'Patch',
client.messages.ComputeBackendBucketsPatchRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name(),
backendBucketResource=replacement))
def GetSetEdgeSecurityPolicyRequest(self, client, backend_bucket_ref,
security_policy_ref):
"""Returns a request to set the edge policy for the backend bucket."""
if backend_bucket_ref.Collection() == 'compute.regionBackendBuckets':
raise exceptions.ArgumentError(
'Regional backend buckets do not support edge security policies.')
return (client.apitools_client.backendBuckets, 'SetEdgeSecurityPolicy',
client.messages.ComputeBackendBucketsSetEdgeSecurityPolicyRequest(
project=backend_bucket_ref.project,
backendBucket=backend_bucket_ref.Name(),
securityPolicyReference=client.messages.SecurityPolicyReference(
securityPolicy=security_policy_ref)))
def Modify(self, args, existing):
"""Modifies and returns the updated backend bucket."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
replacement = encoding.CopyProtoMessage(existing)
cleared_fields = []
if args.IsSpecified('description'):
replacement.description = args.description
if args.gcs_bucket_name:
replacement.bucketName = args.gcs_bucket_name
if args.enable_cdn is not None:
replacement.enableCdn = args.enable_cdn
backend_buckets_utils.ApplyCdnPolicyArgs(
client,
args,
replacement,
is_update=True,
cleared_fields=cleared_fields)
if args.custom_response_header is not None:
replacement.customResponseHeaders = args.custom_response_header
if args.no_custom_response_headers:
replacement.customResponseHeaders = []
if not replacement.customResponseHeaders:
cleared_fields.append('customResponseHeaders')
if (replacement.cdnPolicy is not None and
replacement.cdnPolicy.cacheMode and args.enable_cdn is not False): # pylint: disable=g-bool-id-comparison
replacement.enableCdn = True
if args.compression_mode is not None:
replacement.compressionMode = (
client.messages.BackendBucket.CompressionModeValueValuesEnum(
args.compression_mode))
if not replacement.description:
cleared_fields.append('description')
return replacement, cleared_fields
def MakeRequests(self, args):
"""Makes the requests for updating the backend bucket."""
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
if self.support_regional_global_flags:
backend_bucket_ref = backend_buckets_flags.GLOBAL_REGIONAL_BACKEND_BUCKET_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
else:
backend_bucket_ref = self.BACKEND_BUCKET_ARG.ResolveAsResource(
args, holder.resources
)
get_request = self.GetGetRequest(client, backend_bucket_ref)
objects = client.MakeRequests([get_request])
new_object, cleared_fields = self.Modify(args, objects[0])
# If existing object is equal to the proposed object or if
# Modify() returns None, then there is no work to be done, so we
# print the resource and return.
if objects[0] == new_object:
# Only skip update if edge_security_policy is not set.
if getattr(args, 'edge_security_policy', None) is None:
log.status.Print(
'No change requested; skipping update for [{0}].'.format(
objects[0].name))
return objects
backend_bucket_result = []
else:
with client.apitools_client.IncludeFields(cleared_fields):
backend_bucket_result = client.MakeRequests(
[self.GetSetRequest(client, backend_bucket_ref, new_object)])
# Empty string is a valid value.
if getattr(args, 'edge_security_policy', None) is not None:
if backend_bucket_ref.Collection() == 'compute.regionBackendBuckets':
raise exceptions.ArgumentError(
'argument --edge-security-policy: Regional backend buckets do not'
' support edge security policies.'
)
if getattr(args, 'edge_security_policy', None):
security_policy_ref = self.EDGE_SECURITY_POLICY_ARG.ResolveAsResource(
args, holder.resources).SelfLink()
# If security policy is an empty string we should clear the current policy
else:
security_policy_ref = None
edge_security_policy_request = self.GetSetEdgeSecurityPolicyRequest(
client, backend_bucket_ref, security_policy_ref)
edge_security_policy_result = client.MakeRequests(
[edge_security_policy_request])
else:
edge_security_policy_result = []
return backend_bucket_result + edge_security_policy_result
def Run(self, args):
"""Issues the request necessary for updating a backend bucket."""
if (not self.AnyArgsSpecified(args) and
not args.IsSpecified('signed_url_cache_max_age') and
not args.IsSpecified('request_coalescing') and
not self.AnyFlexibleCacheArgsSpecified(args)):
raise exceptions.UpdatePropertyError(
'At least one property must be modified.')
return self.MakeRequests(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
@base.UniverseCompatible
class UpdateBeta(Update):
"""Update a backend bucket.
*{command}* is used to update backend buckets.
To delete a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--no-enable-cdn
--global
$ {command} my-backend-bucket
--no-enable-cdn
To delete a regional backend bucket, run the following:
$ {command} my-backend-bucket --region=us-central1
--no-enable-cdn
"""
support_regional_global_flags = True
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.UniverseCompatible
class UpdateAlpha(UpdateBeta):
"""Update a backend bucket.
*{command}* is used to update backend buckets.
To delete a global backend bucket, run either of the following:
$ {command} my-backend-bucket
--no-enable-cdn
--global
$ {command} my-backend-bucket
--no-enable-cdn
To delete a regional backend bucket, run the following:
$ {command} my-backend-bucket --region=us-central1
--no-enable-cdn
"""
support_regional_global_flags = True