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,42 @@
# -*- 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.
"""Commands for reading and manipulating snapshots."""
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 Snapshots(base.Group):
"""List, describe, and delete Compute Engine snapshots."""
Snapshots.category = base.INSTANCES_CATEGORY
Snapshots.detailed_help = {
'DESCRIPTION': """
List, describe, and delete Compute Engine snapshots.
For more information about snapshots, see the
[snapshots documentation](https://cloud.google.com/compute/docs/disks/create-snapshots).
See also: [Snapshots API](https://cloud.google.com/compute/docs/reference/rest/v1/snapshots).
""",
}

View File

@@ -0,0 +1,44 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Add IAM policy binding to a Compute Engine snapshot.
description: |
Add an IAM policy binding to the IAM policy of a Compute Engine snapshot. One binding consists of a member,
a role, and an optional condition.
examples: |
To add an IAM policy binding for the role of 'roles/compute.securityAdmin' for the user 'test-user@gmail.com'
with snapshot 'my-snapshot', run:
$ {command} my-snapshot --member='user:test-user@gmail.com' --role='roles/compute.securityAdmin'
To add an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/compute.securityAdmin' and the user 'test-user@gmail.com' with snapshot 'my-snapshot', run:
$ {command} my-snapshot --member='user:test-user@gmail.com' --role='roles/compute.securityAdmin' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: compute.snapshots
use_relative_name: false
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
arguments:
resource:
help_text: The snapshot for which to add IAM policy binding to.
spec: !REF googlecloudsdk.command_lib.compute.resources:snapshot
iam:
set_iam_policy_request_path: globalSetPolicyRequest
message_type_overrides:
policy: Policy
set_iam_policy_request: ComputeSnapshotsSetIamPolicyRequest
enable_condition: true
hide_special_member_types: true
policy_version: 3
get_iam_policy_version_path: optionsRequestedPolicyVersion

View File

@@ -0,0 +1,198 @@
# -*- 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 for adding labels to snapshots."""
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 labels_doc_helper
from googlecloudsdk.command_lib.compute import labels_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.snapshots import flags as snapshots_flags
from googlecloudsdk.command_lib.util.args import labels_util
def _GAArgs(parser):
"""A helper function to build args for GA API version."""
SnapshotsAddLabels.SnapshotArg = snapshots_flags.MakeSnapshotArg()
SnapshotsAddLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForAddLabels(parser)
def _BetaArgs(parser):
"""A helper function to build args for Beta API version."""
SnapshotsAddLabels.SnapshotArg = (
snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
)
SnapshotsAddLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForAddLabels(parser)
def _AlphaArgs(parser):
"""A helper function to build args for Alpha API version."""
SnapshotsAddLabels.SnapshotArg = (
snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
)
SnapshotsAddLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForAddLabels(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class SnapshotsAddLabels(base.UpdateCommand):
"""Add labels to Compute Engine snapshots.
*{command}* adds labels to a Compute Engine snapshot.
For example, running:
$ {command} example-snapshot --labels=k0=v0,k1=v1
will add key-value pairs ``k0''=``v0'' and ``k1''=``v1'' to
'example-snapshot'.
Labels can be used to identify the snapshot and to filter them as in
$ {parent_command} list --filter='labels.k1:value2'
To list existing labels
$ {parent_command} describe example-snapshot --format="default(labels)"
"""
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client.apitools_client
messages = holder.client.messages
snapshot_ref = SnapshotsAddLabels.SnapshotArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
if (
support_region
and snapshot_ref.Collection() == 'compute.regionSnapshots'
):
add_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
regional_snapshot = client.regionSnapshots.Get(
messages.ComputeRegionSnapshotsGetRequest(**snapshot_ref.AsDict())
)
labels_update = labels_util.Diff(additions=add_labels).Apply(
messages.RegionSetLabelsRequest.LabelsValue,
regional_snapshot.labels)
if not labels_update.needs_update:
return regional_snapshot
request = messages.ComputeRegionSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
region=snapshot_ref.region,
regionSetLabelsRequest=
messages.RegionSetLabelsRequest(
labelFingerprint=regional_snapshot.labelFingerprint,
labels=labels_update.labels,
))
operation = client.regionSnapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.regionOperations')
operation_poller = poller.Poller(client.regionSnapshots)
return waiter.WaitFor(
operation_poller, operation_ref,
'Updating labels of snapshot [{0}]'.format(
snapshot_ref.Name()))
else:
add_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
snapshot = client.snapshots.Get(
messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict()))
labels_update = labels_util.Diff(additions=add_labels).Apply(
messages.GlobalSetLabelsRequest.LabelsValue,
snapshot.labels)
if not labels_update.needs_update:
return snapshot
request = messages.ComputeSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
globalSetLabelsRequest=
messages.GlobalSetLabelsRequest(
labelFingerprint=snapshot.labelFingerprint,
labels=labels_update.labels))
operation = client.snapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.globalOperations')
operation_poller = poller.Poller(client.snapshots)
return waiter.WaitFor(
operation_poller, operation_ref,
'Updating labels of snapshot [{0}]'.format(
snapshot_ref.Name()))
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class SnapshotsAddLabelsBeta(SnapshotsAddLabels):
"""Add labels to Compute Engine snapshots."""
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class SnapshotsAddLabelsAlpha(SnapshotsAddLabels):
"""Add labels to Compute Engine snapshots."""
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
SnapshotsAddLabels.detailed_help = (
labels_doc_helper.GenerateDetailedHelpForAddLabels('snapshot'))

View File

@@ -0,0 +1,304 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for creating snapshots."""
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 csek_utils
from googlecloudsdk.api_lib.compute import kms_utils
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
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.snapshots import flags as snap_flags
from googlecloudsdk.command_lib.kms import resource_args as kms_resource_args
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
def _GAArgs(parser):
"""Set Args based on Release Track."""
# GA specific args
parser.add_argument('name', help='The name of the snapshot.')
snap_flags.AddChainArg(parser)
snap_flags.AddSourceDiskCsekKey(parser)
flags.AddGuestFlushFlag(
parser,
'snapshot',
custom_help="""
Create an application-consistent snapshot by informing the OS
to prepare for the snapshot process. Currently only supported
for creating snapshots of disks attached to Windows instances.
""",
)
flags.AddStorageLocationFlag(parser, 'snapshot')
labels_util.AddCreateLabelsFlags(parser)
csek_utils.AddCsekKeyArgs(parser, flags_about_creation=False)
base.ASYNC_FLAG.AddToParser(parser)
parser.add_argument(
'--description', help='Text to describe the new snapshot.'
)
snap_flags.SOURCE_DISK_ARG.AddArgument(parser)
snap_flags.AddSnapshotType(parser)
snap_flags.SOURCE_DISK_FOR_RECOVERY_CHECKPOINT_ARG.AddArgument(parser)
snap_flags.SOURCE_INSTANT_SNAPSHOT_ARG.AddArgument(parser)
snap_flags.AddSourceInstantSnapshotCsekKey(parser)
def _BetaArgs(parser):
_GAArgs(parser)
snap_flags.AddScopeArg(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser, 'snapshot', region_fallthrough=True
)
def _AlphaArgs(parser):
_GAArgs(parser)
snap_flags.AddMaxRetentionDays(parser)
snap_flags.AddScopeArg(parser)
kms_resource_args.AddKmsKeyResourceArg(
parser, 'snapshot', region_fallthrough=True
)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Create(base.CreateCommand):
"""Create snapshots of Google Compute Engine persistent disks."""
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(
self,
args,
support_max_retention_days=False,
support_scope_arg=False,
support_kms=False,
):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client.apitools_client
messages = holder.client.messages
if support_scope_arg and args.region:
snap_ref = holder.resources.Parse(
args.name,
params={
'project': properties.VALUES.core.project.GetOrFail,
'region': args.region,
},
collection='compute.regionSnapshots',
)
snapshot_message = messages.Snapshot(
name=snap_ref.Name(),
description=args.description,
region=snap_ref.region,
)
else:
snap_ref = holder.resources.Parse(
args.name,
params={
'project': properties.VALUES.core.project.GetOrFail,
},
collection='compute.snapshots',
)
snapshot_message = messages.Snapshot(
name=snap_ref.Name(),
description=args.description,
)
# This feature is only exposed in alpha/beta
allow_rsa_encrypted = self.ReleaseTrack() in [
base.ReleaseTrack.ALPHA,
base.ReleaseTrack.BETA,
]
if args.source_disk:
disk_ref = snap_flags.SOURCE_DISK_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=flags.GetDefaultScopeLister(holder.client),
)
snapshot_message.sourceDisk = disk_ref.SelfLink()
if args.source_disk_key_file:
source_keys = csek_utils.CsekKeyStore.FromFile(
args.source_disk_key_file, allow_rsa_encrypted
)
disk_key_or_none = csek_utils.MaybeLookupKeyMessage(
source_keys, disk_ref, client
)
snapshot_message.sourceDiskEncryptionKey = disk_key_or_none
if args.source_disk_for_recovery_checkpoint:
source_disk_for_recovery_checkpoint_ref = (
snap_flags.SOURCE_DISK_FOR_RECOVERY_CHECKPOINT_ARG.ResolveAsResource(
args,
holder.resources,
default_scope=compute_scope.ScopeEnum.REGION,
)
)
snapshot_message.sourceDiskForRecoveryCheckpoint = (
source_disk_for_recovery_checkpoint_ref.SelfLink()
)
if args.csek_key_file:
csek_keys = csek_utils.CsekKeyStore.FromArgs(args, allow_rsa_encrypted)
snap_key_or_none = csek_utils.MaybeLookupKeyMessage(
csek_keys, snap_ref, client
)
snapshot_message.snapshotEncryptionKey = snap_key_or_none
if support_kms and args.kms_key:
kms_key_or_none = kms_utils.MaybeGetKmsKey(
args, messages, snapshot_message.snapshotEncryptionKey
)
if kms_key_or_none:
snapshot_message.snapshotEncryptionKey = kms_key_or_none
if hasattr(args, 'labels') and args.IsSpecified('labels'):
snapshot_message.labels = labels_util.ParseCreateArgs(
args, messages.Snapshot.LabelsValue
)
if args.storage_location:
snapshot_message.storageLocations = [args.storage_location]
if args.guest_flush:
snapshot_message.guestFlush = True
if args.chain_name:
snapshot_message.chainName = args.chain_name
if args.source_instant_snapshot:
iss_ref = snap_flags.SOURCE_INSTANT_SNAPSHOT_ARG.ResolveAsResource(
args,
holder.resources,
scope_lister=flags.GetDefaultScopeLister(holder.client),
)
snapshot_message.sourceInstantSnapshot = iss_ref.SelfLink()
if args.source_instant_snapshot_key_file:
source_keys = csek_utils.CsekKeyStore.FromFile(
args.source_instant_snapshot_key_file, allow_rsa_encrypted
)
instant_snapshot_key_or_none = csek_utils.MaybeLookupKeyMessage(
source_keys, iss_ref, client
)
snapshot_message.sourceInstantSnapshotEncryptionKey = (
instant_snapshot_key_or_none
)
if args.IsSpecified('snapshot_type'):
snapshot_message.snapshotType = (
snapshot_message.SnapshotTypeValueValuesEnum(args.snapshot_type)
)
if support_max_retention_days and args.IsSpecified('max_retention_days'):
snapshot_message.maxRetentionDays = int(args.max_retention_days)
if support_scope_arg and args.region:
request = messages.ComputeRegionSnapshotsInsertRequest(
snapshot=snapshot_message,
project=snap_ref.project,
region=snap_ref.region,
)
result = client.regionSnapshots.Insert(request)
operation_ref = resources.REGISTRY.Parse(
result.name,
params={
'project': snap_ref.project,
'region': snap_ref.region,
},
collection='compute.regionOperations',
)
else:
request = messages.ComputeSnapshotsInsertRequest(
snapshot=snapshot_message,
project=snap_ref.project,
)
result = client.snapshots.Insert(request)
operation_ref = resources.REGISTRY.Parse(
result.name,
params={'project': snap_ref.project},
collection='compute.globalOperations',
)
if args.async_:
log.UpdatedResource(
operation_ref,
kind='gce snapshot {0}'.format(snap_ref.Name()),
is_async=True,
details=(
'Use [gcloud compute operations describe] command '
'to check the status of this operation.'
),
)
return result
if support_scope_arg and args.region:
operation_poller = poller.Poller(client.regionSnapshots, snap_ref)
else:
operation_poller = poller.Poller(client.snapshots, snap_ref)
return waiter.WaitFor(
operation_poller,
operation_ref,
'Creating gce snapshot {0}'.format(snap_ref.Name()),
)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class CreateBeta(Create):
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_scope_arg=True,
support_kms=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreateAlpha(Create):
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_max_retention_days=True,
support_scope_arg=True,
support_kms=True,
)
Create.detailed_help = {
'brief': 'Create Compute Engine snapshots',
'DESCRIPTION': """\
*{command}* creates snapshot of persistent disk. Snapshots are useful for
backing up persistent disk data and for creating custom images.
For more information, see https://cloud.google.com/compute/docs/disks/create-snapshots.
""",
'EXAMPLES': """\
To create a snapshot 'my-snap' from a disk 'my-disk' in zone 'us-east1-a', run:
$ {command} my-snap --source-disk=my-disk --source-disk-zone=us-east1-a
""",
}

View File

@@ -0,0 +1,151 @@
# -*- 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.
"""Command for deleting snapshots."""
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.snapshots import flags
REGIONAL_SNAPSHOT_COLLECTION = 'compute.regionSnapshots'
DELETE = 'Delete'
DETAILED_HELP = {
'EXAMPLES':
"""\
To delete Compute Engine snapshots with the names 'snapshot-1'
and 'snapshot-2', run:
$ {command} snapshot-1 snapshot-2
To list all snapshots that were created before a specific date, use
the --filter flag with the `{parent_command} list` command.
$ {parent_command} list --filter="creationTimestamp<'2017-01-01'"
For more information on how to use --filter with the list command,
run $ gcloud topic filters.
""",
}
def _GAArgs(parser):
"""A helper function to build args for GA API version."""
Delete.SnapshotArg = flags.MakeSnapshotArg(plural=True)
Delete.SnapshotArg.AddArgument(parser, operation_type='delete')
def _BetaArgs(parser):
"""A helper function to build args for Beta API version."""
Delete.SnapshotArg = flags.MakeSnapshotArgForRegionalSnapshots(plural=True)
Delete.SnapshotArg.AddArgument(parser, operation_type='delete')
def _AlphaArgs(parser):
"""A helper function to build args for Alpha API version."""
Delete.SnapshotArg = flags.MakeSnapshotArgForRegionalSnapshots(plural=True)
Delete.SnapshotArg.AddArgument(parser, operation_type='delete')
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Delete(base.DeleteCommand):
"""Delete Compute Engine snapshots.
*{command}* deletes one or more Compute Engine snapshots.
"""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
snapshot_refs = Delete.SnapshotArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
utils.PromptForDeletion(snapshot_refs)
requests = []
for snapshot_ref in snapshot_refs:
if (
support_region
and snapshot_ref.Collection() == REGIONAL_SNAPSHOT_COLLECTION
):
requests.append((
client.apitools_client.regionSnapshots,
DELETE,
client.messages.ComputeRegionSnapshotsDeleteRequest(
project=snapshot_ref.project,
snapshot=snapshot_ref.snapshot,
region=snapshot_ref.region,
),
))
else:
requests.append((
client.apitools_client.snapshots,
DELETE,
client.messages.ComputeSnapshotsDeleteRequest(
project=snapshot_ref.project, snapshot=snapshot_ref.snapshot
),
))
return client.MakeRequests(requests)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DeleteBeta(Delete):
"""Delete Compute Engine snapshots."""
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DeleteAlpha(Delete):
"""Delete Compute Engine snapshots."""
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)

View File

@@ -0,0 +1,152 @@
# -*- 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.
"""Command for describing snapshots."""
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.snapshots import flags
def _GAArgs(parser):
"""Set Args based on Release Track."""
Describe.SnapshotArg = flags.MakeSnapshotArg()
Describe.SnapshotArg.AddArgument(parser, operation_type='describe')
def _BetaArgs(parser):
Describe.SnapshotArg = flags.MakeSnapshotArgForRegionalSnapshots()
Describe.SnapshotArg.AddArgument(parser, operation_type='describe')
def _AlphaArgs(parser):
Describe.SnapshotArg = flags.MakeSnapshotArgForRegionalSnapshots()
Describe.SnapshotArg.AddArgument(parser, operation_type='describe')
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Describe(base.DescribeCommand):
"""Describe a Compute Engine snapshot."""
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
messages = client.messages
snapshot_ref = Describe.SnapshotArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
if (
support_region
and snapshot_ref.Collection() == 'compute.regionSnapshots'
):
request = messages.ComputeRegionSnapshotsGetRequest(
**snapshot_ref.AsDict(),
)
return client.MakeRequests(
[(client.apitools_client.regionSnapshots, 'Get', request)]
)[0]
request = messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict())
return client.MakeRequests(
[(client.apitools_client.snapshots, 'Get', request)]
)[0]
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class DescribeBeta(Describe):
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribeAlpha(Describe):
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
Describe.detailed_help = {
'brief': 'Describe a Compute Engine snapshot',
'DESCRIPTION': """
*{command}* displays all data associated with a Compute Engine snapshot
in a project.
Given an existing snapshot is queried, successful output of this command
looks like the following:
```
creationTimestamp: '2018-05-07T10:45:46.988-07:00'
diskSizeGb: '500'
id: '1234567891234567890'
kind: compute#snapshot
labelFingerprint: 12345abcdWW=
name: zs9utdhb8r1x
selfLink: https://www.googleapis.com/compute/v1/projects/test-project-name/global/snapshots/snapshot-number
sourceDisk: https://www.googleapis.com/compute/v1/projects/test-project-name/zones/us-central1-c/disks/test
sourceDiskId: '1234567891234567890'
status: READY
storageBytes: '0'
storageBytesStatus: UP_TO_DATE
```
""",
'EXAMPLES': """
To run `{command}`, you'll need the name of a snapshot. To list existing
snapshots by name, run:
$ {parent_command} list
To display specific details of an existing Compute Engine snapshot (like
its creation time, status, and storage details), run:
$ {command} SNAPSHOT_NAME --format="table(creationTimestamp, status, storageBytesStatus)"
""",
}

View File

@@ -0,0 +1,31 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Get the IAM policy for a Compute Engine snapshot.
description: |
*{command}* displays the IAM policy associated with a snapshot.
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 snapshot, run:
$ {command} my-snapshot
request:
collection: compute.snapshots
use_relative_name: false
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:UseMaxRequestedPolicyVersion:api_field=optionsRequestedPolicyVersion
BETA:
api_version: beta
ALPHA:
api_version: alpha
arguments:
resource:
help_text: The snapshot to display the IAM policy for.
spec: !REF googlecloudsdk.command_lib.compute.resources:snapshot

View File

@@ -0,0 +1,125 @@
# -*- 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.
"""Command for listing snapshots."""
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 lister
from googlecloudsdk.calliope import base
def _GAArgs(parser):
"""Set Args for GA."""
parser.display_info.AddFormat("""\
table(
name,
diskSizeGb,
sourceDisk.scope():label=SRC_DISK,
status
)""")
lister.AddBaseListerArgs(parser)
def _BetaArgs(parser):
"""Set Args based on Release Track."""
parser.display_info.AddFormat("""\
table(
name,
location().yesno(no="GLOBAL"):label=LOCATION,
diskSizeGb,
sourceDisk.scope():label=SRC_DISK,
status
)""")
lister.AddMultiScopeListerFlags(parser, global_=True, regional=True)
def _AlphaArgs(parser):
"""Set Args based on Release Track."""
parser.display_info.AddFormat("""\
table(
name,
location().yesno(no="GLOBAL"):label=LOCATION,
diskSizeGb,
sourceDisk.scope():label=SRC_DISK,
status
)""")
lister.AddMultiScopeListerFlags(parser, global_=True, regional=True)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class List(base.ListCommand):
"""List Compute Engine snapshots."""
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client
if support_region:
request_data = lister.ParseMultiScopeFlags(args, holder.resources)
list_implementation = lister.MultiScopeLister(
client,
global_service=client.apitools_client.snapshots,
regional_service=client.apitools_client.regionSnapshots,
aggregation_service=client.apitools_client.snapshots,
)
return lister.Invoke(request_data, list_implementation)
else:
request_data = lister.ParseNamesAndRegexpFlags(args, holder.resources)
list_implementation = lister.GlobalLister(
client, client.apitools_client.snapshots
)
return lister.Invoke(request_data, list_implementation)
List.detailed_help = base_classes.GetGlobalListerHelp('snapshots')
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(List):
"""List Compute Engine snapshots."""
@classmethod
def Args(cls, parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(args, support_region=True)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(List):
"""List Compute Engine snapshots."""
@classmethod
def Args(cls, parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(args, support_region=True)

View File

@@ -0,0 +1,44 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Remove IAM policy binding from a Compute Engine snapshot.
description: |
Remove an IAM policy binding from the IAM policy of a Compute Engine snapshot. One binding consists of a member,
a role, and an optional condition.
examples: |
To remove an IAM policy binding for the role of 'roles/compute.securityAdmin' for the user 'test-user@gmail.com'
with snapshot 'my-snapshot', run:
$ {command} my-snapshot --member='user:test-user@gmail.com' --role='roles/compute.securityAdmin'
To remove an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/compute.securityAdmin' and the user 'test-user@gmail.com' with snapshot 'my-snapshot', run:
$ {command} my-snapshot --member='user:test-user@gmail.com' --role='roles/compute.securityAdmin' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: compute.snapshots
use_relative_name: false
api_version: v1
BETA:
api_version: beta
ALPHA:
api_version: alpha
arguments:
resource:
help_text: The snapshot for which to remove IAM policy binding from.
spec: !REF googlecloudsdk.command_lib.compute.resources:snapshot
iam:
set_iam_policy_request_path: globalSetPolicyRequest
message_type_overrides:
policy: Policy
set_iam_policy_request: ComputeSnapshotsSetIamPolicyRequest
enable_condition: true
hide_special_member_types: true
policy_version: 3
get_iam_policy_version_path: optionsRequestedPolicyVersion

View File

@@ -0,0 +1,189 @@
# -*- 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 for adding labels to snapshots."""
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 labels_doc_helper
from googlecloudsdk.command_lib.compute import labels_flags
from googlecloudsdk.command_lib.compute import scope as compute_scope
from googlecloudsdk.command_lib.compute.snapshots import flags as snapshots_flags
from googlecloudsdk.command_lib.util.args import labels_util
def _GAArgs(parser):
"""A helper function to build args for GA API version."""
SnapshotsRemoveLabels.SnapshotArg = snapshots_flags.MakeSnapshotArg()
SnapshotsRemoveLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForRemoveLabels(parser)
def _BetaArgs(parser):
"""A helper function to build args for Beta API version."""
SnapshotsRemoveLabels.SnapshotArg = (
snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
)
SnapshotsRemoveLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForRemoveLabels(parser)
def _AlphaArgs(parser):
"""A helper function to build args for Alpha API version."""
SnapshotsRemoveLabels.SnapshotArg = (
snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
)
SnapshotsRemoveLabels.SnapshotArg.AddArgument(parser)
labels_flags.AddArgsForRemoveLabels(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class SnapshotsRemoveLabels(base.UpdateCommand):
"""Remove labels to Compute Engine snapshots."""
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client.apitools_client
messages = holder.client.messages
snapshot_ref = SnapshotsRemoveLabels.SnapshotArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
default_scope=compute_scope.ScopeEnum.GLOBAL,
)
if (
support_region
and snapshot_ref.Collection() == 'compute.regionSnapshots'
):
remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
regional_snapshot = client.regionSnapshots.Get(
messages.ComputeRegionSnapshotsGetRequest(**snapshot_ref.AsDict()))
if args.all:
# removing all existing labels from the snapshot.
remove_labels = {}
if regional_snapshot.labels:
for label in regional_snapshot.labels.additionalProperties:
remove_labels[label.key] = label.value
labels_update = labels_util.Diff(subtractions=remove_labels).Apply(
messages.RegionSetLabelsRequest.LabelsValue,
regional_snapshot.labels)
if not labels_update.needs_update:
return regional_snapshot
request = messages.ComputeRegionSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
region=snapshot_ref.region,
regionSetLabelsRequest=
messages.RegionSetLabelsRequest(
labelFingerprint=regional_snapshot.labelFingerprint,
labels=labels_update.labels))
operation = client.regionSnapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.regionOperations')
operation_poller = poller.Poller(client.regionSnapshots)
return waiter.WaitFor(
operation_poller, operation_ref,
'Updating labels of snapshot [{0}]'.format(
snapshot_ref.Name()))
else:
remove_labels = labels_util.GetUpdateLabelsDictFromArgs(args)
snapshot = client.snapshots.Get(
messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict()))
if args.all:
# removing all existing labels from the snapshot.
remove_labels = {}
if snapshot.labels:
for label in snapshot.labels.additionalProperties:
remove_labels[label.key] = label.value
labels_update = labels_util.Diff(subtractions=remove_labels).Apply(
messages.GlobalSetLabelsRequest.LabelsValue,
snapshot.labels)
if not labels_update.needs_update:
return snapshot
request = messages.ComputeSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
globalSetLabelsRequest=
messages.GlobalSetLabelsRequest(
labelFingerprint=snapshot.labelFingerprint,
labels=labels_update.labels))
operation = client.snapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.globalOperations')
operation_poller = poller.Poller(client.snapshots)
return waiter.WaitFor(
operation_poller, operation_ref,
'Updating labels of snapshot [{0}]'.format(
snapshot_ref.Name()))
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class SnapshotsRemoveLabelsBeta(SnapshotsRemoveLabels):
"""Remove labels to Compute Engine snapshots."""
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class SnapshotsRemoveLabelsAlpha(SnapshotsRemoveLabels):
"""Remove labels to Compute Engine snapshots."""
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
SnapshotsRemoveLabels.detailed_help = (
labels_doc_helper.GenerateDetailedHelpForRemoveLabels('snapshot'))

View File

@@ -0,0 +1,37 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Set the IAM policy for a Compute Engine snapshot.
description: |
Sets the IAM policy for the given snapshot as defined in a JSON or YAML file.
examples: |
The following command will read am IAM policy defined in a JSON file
'policy.json' and set it for the snapshot `my-snapshot`:
$ {command} my-snapshot policy.json
See https://cloud.google.com/iam/docs/managing-policies for details of the
policy file format and contents.
request:
collection: compute.snapshots
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: ComputeSnapshotsSetIamPolicyRequest
arguments:
resource:
help_text: The snapshot to set the IAM policy for.
spec: !REF googlecloudsdk.command_lib.compute.resources:snapshot

View File

@@ -0,0 +1,196 @@
# -*- 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 for labels update to snapshots."""
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 scope as compute_scope
from googlecloudsdk.command_lib.compute.snapshots import flags as snapshots_flags
from googlecloudsdk.command_lib.util.args import labels_util
DETAILED_HELP = {
'EXAMPLES':
"""\
To update labels ``k0'' and ``k1'' and remove labels with key ``k3'', run:
$ {command} example-snapshot --update-labels=k0=value1,k1=value2 --remove-labels=k3
``k0'' and ``k1'' will be added as new labels if not already present.
Labels can be used to identify the snapshot and to filter them like:
$ {parent_command} list --filter='labels.k1:value2'
To list only the labels when describing a resource, use --format:
$ {parent_command} describe example-snapshot --format="default(labels)"
""",
}
def _GAArgs(parser):
"""Set Args based on Release Track."""
Update.SnapshotArg = snapshots_flags.MakeSnapshotArg()
Update.SnapshotArg.AddArgument(parser, operation_type='update')
labels_util.AddUpdateLabelsFlags(parser)
def _BetaArgs(parser):
"""Set Args based on Release Track."""
Update.SnapshotArg = snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
Update.SnapshotArg.AddArgument(parser, operation_type='update')
labels_util.AddUpdateLabelsFlags(parser)
def _AlphaArgs(parser):
"""Set Args based on Release Track."""
Update.SnapshotArg = snapshots_flags.MakeSnapshotArgForRegionalSnapshots()
Update.SnapshotArg.AddArgument(parser, operation_type='update')
labels_util.AddUpdateLabelsFlags(parser)
@base.ReleaseTracks(base.ReleaseTrack.GA)
@base.UniverseCompatible
class Update(base.UpdateCommand):
r"""Update a Compute Engine snapshot.
*{command}* updates labels for a Compute Engine snapshot.
"""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
_GAArgs(parser)
def Run(self, args):
return self._Run(args)
def _Run(self, args, support_region=False):
holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
client = holder.client.apitools_client
messages = holder.client.messages
snapshot_ref = Update.SnapshotArg.ResolveAsResource(
args,
holder.resources,
scope_lister=compute_flags.GetDefaultScopeLister(holder.client),
default_scope=compute_scope.ScopeEnum.GLOBAL,)
if (
support_region
and snapshot_ref.Collection() == 'compute.regionSnapshots'
):
labels_diff = labels_util.GetAndValidateOpsFromArgs(args)
regional_snapshot = client.regionSnapshots.Get(
messages.ComputeRegionSnapshotsGetRequest(**snapshot_ref.AsDict())
)
labels_update = labels_diff.Apply(
messages.RegionSetLabelsRequest.LabelsValue, regional_snapshot.labels
)
if not labels_update.needs_update:
return regional_snapshot
request = messages.ComputeRegionSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
region=snapshot_ref.region,
regionSetLabelsRequest=messages.RegionSetLabelsRequest(
labelFingerprint=regional_snapshot.labelFingerprint,
labels=labels_update.labels,
),
)
operation = client.regionSnapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.regionOperations'
)
operation_poller = poller.Poller(client.regionSnapshots)
return waiter.WaitFor(
operation_poller,
operation_ref,
'Updating labels of snapshot [{0}]'.format(snapshot_ref.Name()),
)
else:
labels_diff = labels_util.GetAndValidateOpsFromArgs(args)
snapshot = client.snapshots.Get(
messages.ComputeSnapshotsGetRequest(**snapshot_ref.AsDict())
)
labels_update = labels_diff.Apply(
messages.GlobalSetLabelsRequest.LabelsValue, snapshot.labels
)
if not labels_update.needs_update:
return snapshot
request = messages.ComputeSnapshotsSetLabelsRequest(
project=snapshot_ref.project,
resource=snapshot_ref.snapshot,
globalSetLabelsRequest=
messages.GlobalSetLabelsRequest(
labelFingerprint=snapshot.labelFingerprint,
labels=labels_update.labels))
operation = client.snapshots.SetLabels(request)
operation_ref = holder.resources.Parse(
operation.selfLink, collection='compute.globalOperations')
operation_poller = poller.Poller(client.snapshots)
return waiter.WaitFor(
operation_poller, operation_ref,
'Updating labels of snapshot [{0}]'.format(
snapshot_ref.Name()))
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateBeta(Update):
"""Update a Compute Engine snapshot."""
@staticmethod
def Args(parser):
_BetaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAlpha(Update):
"""Update a Compute Engine snapshot."""
@staticmethod
def Args(parser):
_AlphaArgs(parser)
def Run(self, args):
return self._Run(
args,
support_region=True,
)

View File

@@ -0,0 +1,91 @@
# -*- 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 for updating the KMS key of a persistent snapshot."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.snapshots import flags as snapshots_flags
DETAILED_HELP = {
'brief': 'Update the KMS key of a Compute Engine snapshot.',
'DESCRIPTION': """
* {command}* updates the KMS key of a Compute Engine persistent snapshot.
""",
'EXAMPLES': """
To update the KMS key of a snapshot named example-snapshot-1, run:
$ {command} example-snapshot-1
""",
}
def _CommonArgs(parser):
"""Add arguments used for parsing in all command tracks."""
snapshots_flags.MakeSnapshotArg(plural=False).AddArgument(
parser, operation_type='update the KMS key for'
)
parser.add_argument(
'--region',
help='The region of the snapshot to update.',
required=False,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
@base.UniverseCompatible
class UpdateKmsKey(base.Command):
"""Update the KMS key of a persistent snapshot."""
@classmethod
def Args(cls, parser):
_CommonArgs(parser)
@classmethod
def _GetApiHolder(cls, no_http=False):
return base_classes.ComputeApiHolder(cls.ReleaseTrack(), no_http)
def Run(self, args):
compute_holder = self._GetApiHolder()
client = compute_holder.client
messages = client.messages
if args.region:
snapshot_ref = snapshots_flags.MakeSnapshotArgForRegionalSnapshots(
plural=False
).ResolveAsResource(args, compute_holder.resources)
else:
snapshot_ref = snapshots_flags.MakeSnapshotArg(
plural=False
).ResolveAsResource(args, compute_holder.resources)
if snapshot_ref.Collection() == 'compute.snapshots':
service = client.apitools_client.snapshots
request = messages.ComputeSnapshotsUpdateKmsKeyRequest(
project=snapshot_ref.project,
snapshot=snapshot_ref.Name(),
)
return client.MakeRequests([(service, 'UpdateKmsKey', request)])
elif snapshot_ref.Collection() == 'compute.regionSnapshots':
service = client.apitools_client.regionSnapshots
request = messages.ComputeRegionSnapshotsUpdateKmsKeyRequest(
project=snapshot_ref.project,
region=snapshot_ref.region,
snapshot=snapshot_ref.Name(),
)
return client.MakeRequests([(service, 'UpdateKmsKey', request)])
UpdateKmsKey.detailed_help = DETAILED_HELP