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,27 @@
# -*- 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.
"""The command group for roots."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Roots(base.Group):
"""Manage root certificate authorities.
"""

View File

@@ -0,0 +1,205 @@
# -*- 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.
"""Create a new root certificate authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope.concepts import deps
from googlecloudsdk.command_lib.privateca import create_utils
from googlecloudsdk.command_lib.privateca import flags
from googlecloudsdk.command_lib.privateca import iam
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import p4sa
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.command_lib.privateca import storage
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.command_lib.util.concepts import concept_parsers
from googlecloudsdk.command_lib.util.concepts import presentation_specs
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
# pylint: disable=line-too-long
r"""Create a new root certificate authority.
TIP: Consider setting a [project lien](https://cloud.google.com/resource-manager/docs/project-liens) on the project to prevent it from accidental deletion.
## EXAMPLES
To create a root CA that supports one layer of subordinates:
$ {command} prod-root \
--location=us-west1 --pool=my-pool \
--kms-key-version="projects/my-project-pki/locations/us-west1/keyRings/kr1/cryptoKeys/k1/cryptoKeyVersions/1" \
--subject="CN=Example Production Root CA, O=Google" \
--max-chain-length=1
To create a root CA that is based on an existing CA:
$ {command} prod-root \
--location=us-west1 --pool=my-pool \
--kms-key-version="projects/my-project-pki/locations/us-west1/keyRings/kr1/cryptoKeys/k1/cryptoKeyVersions/1" \
--from-ca=source-root
"""
def __init__(self, *args, **kwargs):
super(Create, self).__init__(*args, **kwargs)
self.client = privateca_base.GetClientInstance(api_version='v1')
self.messages = privateca_base.GetMessagesModule(api_version='v1')
@staticmethod
def Args(parser):
key_spec_group = parser.add_group(
mutex=True,
help='The key configuration used for the CA certificate. Defaults to a '
'managed key if not specified.')
x509_config_group = parser.add_group(
mutex=True,
required=False,
help='The X.509 configuration used for the CA certificate.')
concept_parsers.ConceptParser([
presentation_specs.ResourcePresentationSpec(
'CERTIFICATE_AUTHORITY',
resource_args.CreateCertAuthorityResourceSpec(
'Certificate Authority'),
'The name of the root CA to create.',
required=True),
presentation_specs.ResourcePresentationSpec(
'--kms-key-version',
resource_args.CreateKmsKeyVersionResourceSpec(),
'An existing KMS key version to back this CA.',
group=key_spec_group),
presentation_specs.ResourcePresentationSpec(
'--from-ca',
resource_args.CreateCertAuthorityResourceSpec(
'source CA',
location_fallthroughs=[
deps.ArgFallthrough('--location'),
resource_args.LOCATION_PROPERTY_FALLTHROUGH
],
pool_id_fallthroughs=[deps.ArgFallthrough('--pool')]),
'An existing CA from which to copy configuration values for the new CA. '
'You can still override any of those values by explicitly providing '
'the appropriate flags. The specified existing CA must be part of '
'the same pool as the one being created.',
flag_name_overrides={
'project': '',
'location': '',
'pool': '',
},
prefixes=True)
]).AddToParser(parser)
flags.AddSubjectFlags(parser, subject_required=False)
flags.AddKeyAlgorithmFlag(
key_spec_group, default='rsa-pkcs1-4096-sha256')
flags.AddValidityFlag(
parser,
resource_name='CA',
default_value='P10Y',
default_value_text='10 years')
labels_util.AddCreateLabelsFlags(parser)
flags.AddBucketFlag(parser)
flags.AddUsePresetProfilesFlag(x509_config_group)
# If max_chain_len is unspecified, no max length will be provided to the
# server on create, this allowing any number of subordinates.
flags.AddInlineX509ParametersFlags(
x509_config_group, is_ca_command=True, default_max_chain_length=None)
flags.AddAutoEnableFlag(parser)
flags.AddSubjectKeyIdFlag(parser)
flags.AddUserDefinedAccessUrlsFlags(parser)
def _EnableCertificateAuthority(self, ca_name):
"""Enables the given CA."""
enable_request = self.messages.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesEnableRequest(
name=ca_name,
enableCertificateAuthorityRequest=self.messages
.EnableCertificateAuthorityRequest(
requestId=request_utils.GenerateRequestId()))
operation = self.client.projects_locations_caPools_certificateAuthorities.Enable(
enable_request)
return operations.Await(operation, 'Enabling CA.', api_version='v1')
def _ShouldEnableCa(self, args, ca_ref):
"""Determines whether the CA should be enabled or not."""
if args.auto_enable:
return True
# Return false if there already is an enabled CA in the pool.
ca_pool_name = ca_ref.Parent().RelativeName()
list_response = self.client.projects_locations_caPools_certificateAuthorities.List(
self.messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesListRequest(
parent=ca_pool_name))
if create_utils.HasEnabledCa(
list_response.certificateAuthorities, self.messages):
return False
# Prompt the user if they would like to enable a CA in the pool.
return console_io.PromptContinue(
message='The CaPool [{}] has no enabled CAs and cannot issue any '
'certificates until at least one CA is enabled. Would you like to '
'also enable this CA?'.format(ca_ref.Parent().Name()), default=False)
def Run(self, args):
new_ca, ca_ref, _ = create_utils.CreateCAFromArgs(
args, is_subordinate=False)
pool_ref = ca_ref.Parent()
project_ref = pool_ref.Parent().Parent()
key_version_ref = args.CONCEPTS.kms_key_version.Parse()
kms_key_ref = key_version_ref.Parent() if key_version_ref else None
iam.CheckCreateCertificateAuthorityPermissions(project_ref, kms_key_ref)
bucket_ref = None
if args.IsSpecified('bucket'):
bucket_ref = storage.ValidateBucketForCertificateAuthority(args.bucket)
new_ca.gcsBucket = bucket_ref.bucket
# P4SA is needed only if user specifies any resource.
if bucket_ref or kms_key_ref:
p4sa.AddResourceRoleBindings(
p4sa.GetOrCreate(project_ref), kms_key_ref, bucket_ref)
operation = self.client.projects_locations_caPools_certificateAuthorities.Create(
self.messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesCreateRequest(
certificateAuthority=new_ca,
certificateAuthorityId=ca_ref.Name(),
parent=pool_ref.RelativeName(),
requestId=request_utils.GenerateRequestId()))
ca_response = operations.Await(operation, 'Creating Certificate Authority.', api_version='v1')
ca = operations.GetMessageFromResponse(ca_response,
self.messages.CertificateAuthority)
log.status.Print('Created Certificate Authority [{}].'.format(ca.name))
log.status.Print(
'TIP: To avoid accidental deletion, '
'please consider adding a project lien on this project. To find out '
'more, see the following doc: '
'https://cloud.google.com/resource-manager/docs/project-liens.'
)
if self._ShouldEnableCa(args, ca_ref):
self._EnableCertificateAuthority(ca_ref.RelativeName())

View File

@@ -0,0 +1,150 @@
# -*- 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.
"""Delete a root certificate authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from dateutil import tz
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.api_lib.util import waiter
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.privateca import flags
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
from googlecloudsdk.core.util import times
import six
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
r"""Delete a Root Certificate Authority.
Delete a Root Certificate Authority. Deleted Root Certificate Authorities
may be recovered with the `{parent_command} undelete` command within a grace
period of 30 days.
Use the --skip-grace-period flag to delete as soon as possible without the
30-day grace period to undelete.
Note that any user-managed KMS keys or Google Cloud Storage buckets
will not be affected by this operation. You will need to delete the user-
managed resources separately once the CA is deleted. Any Google-managed
resources will be cleaned up.
The CA specified in this command MUST:
1) be in the DISABLED or STAGED state.
2) have no un-revoked or un-expired certificates. Use the revoke command
to revoke any active certificates.
Use the `--ignore-active-certificates` flag to remove 2) as a requirement.
## EXAMPLES
To delete a root CA:
$ {command} prod-root --pool=my-pool --location=us-west1
To delete a CA while skipping the confirmation
input:
$ {command} prod-root --pool=my-pool --location=us-west1 --quiet
To undo the deletion for a root CA:
$ {parent_command} undelete prod-root --pool=my-pool --location=us-west1
"""
@staticmethod
def Args(parser):
resource_args.AddCertAuthorityPositionalResourceArg(parser, 'to delete')
flags.AddIgnoreActiveCertificatesFlag(parser)
flags.AddSkipGracePeriodFlag(parser)
flags.AddIgnoreDependentResourcesFlag(parser)
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
ca_ref = args.CONCEPTS.certificate_authority.Parse()
prompt_message = (
'You are about to delete Certificate Authority [{}].').format(
ca_ref.RelativeName())
if args.ignore_dependent_resources:
prompt_message += (
'\nThis deletion will happen without '
'checking if the CA\'s CA Pool is being used by another '
'resource, which may cause unintended and effects on any '
'dependent resource(s) since the CA Pool would not be '
'able to issue certificates.')
if args.skip_grace_period:
prompt_message += (
'\nThis deletion will happen as '
'soon as possible without a 30-day grace period where '
'undeletion would have been allowed. If you proceed, there '
'will be no way to recover this CA.')
if not console_io.PromptContinue(message=prompt_message, default=True):
log.status.Print('Aborted by user.')
return
current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
name=ca_ref.RelativeName()))
resource_args.CheckExpectedCAType(
messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
current_ca,
version='v1')
operation = client.projects_locations_caPools_certificateAuthorities.Delete(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesDeleteRequest(
name=ca_ref.RelativeName(),
ignoreActiveCertificates=args.ignore_active_certificates,
skipGracePeriod=args.skip_grace_period,
ignoreDependentResources=args.ignore_dependent_resources,
requestId=request_utils.GenerateRequestId()))
try:
ca_response = operations.Await(
operation, 'Deleting Root CA', api_version='v1')
except waiter.OperationError as e:
# API error message refers to the proto field name which is slightly
# different from the gcloud flag name.
raise operations.OperationError(
six.text_type(e).replace('`ignore_active_certificates` parameter',
'`--ignore-active-certificates` flag'))
ca = operations.GetMessageFromResponse(ca_response,
messages.CertificateAuthority)
formatted_expire_time = times.ParseDateTime(ca.expireTime).astimezone(
tz.tzutc()).strftime('%Y-%m-%dT%H:%MZ')
if args.skip_grace_period:
log.status.Print('Deleted Root CA [{}]. CA can not be undeleted.'.format(
ca_ref.RelativeName()))
else:
log.status.Print(
'Deleted Root CA [{}]. CA can be undeleted until {}.'.format(
ca_ref.RelativeName(), formatted_expire_time))

View File

@@ -0,0 +1,32 @@
- release_tracks: [GA]
help_text:
brief: |
Get metadata for a root Certificate Authority.
description: |
Returns metadata for the given Certificate Authority.
examples: |
To get metadata for the root CA 'prod-root' in location 'us-west1' and CA Pool 'my-pool':
$ {command} server-tls-1 \
--location=us-west1 --pool=my-pool
To download the PEM-encoded CA certificate chain for the 'prod-root'
CA in location 'us-west1' and CA Pool 'my-pool' to a file
called 'prod-root.crt':
$ {command} prod-root \
--location=us-west1 --pool=my-pool \
--format="value(pemCaCertificates)" > ./prod-root.crt
request:
collection: privateca.projects.locations.caPools.certificateAuthorities
api_version: v1
arguments:
resource:
help_text: The certificate authority for which to obtain metadata.
spec: !REF googlecloudsdk.command_lib.privateca.resources:cert_authority
response:
modify_response_hooks:
- googlecloudsdk.command_lib.privateca.hooks:CheckResponseRootTypeHook:version=v1

View File

@@ -0,0 +1,92 @@
# -*- 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.
"""Disable a root certificate authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.privateca import flags
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Disable(base.SilentCommand):
r"""Disable a root certificate authority.
Disables a root certificate authority. The root certificate authority
will not be allowed to issue certificates once disabled. It may still revoke
certificates and/or generate CRLs. The CA certfificate will still be
included in the FetchCaCertificates response for the parent CA Pool.
## EXAMPLES
To disable a root CA:
$ {command} prod-root --pool=prod-root-pool --location=us-west1
"""
@staticmethod
def Args(parser):
resource_args.AddCertAuthorityPositionalResourceArg(parser, 'to disable')
flags.AddIgnoreDependentResourcesFlag(parser)
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
ca_ref = args.CONCEPTS.certificate_authority.Parse()
if args.ignore_dependent_resources:
prompt_message = (
'You are about to disable Certificate Authority [{}] without '
'checking if the CA\'s CA Pool is being used by another '
'resource. If you proceed and this is the last enabled CA in '
'the CA Pool, there may be unintended and '
'unrecoverable effects on any dependent resource(s) since the '
'CA Pool would not be able to issue certificates'
).format(ca_ref.RelativeName())
if not console_io.PromptContinue(message=prompt_message, default=True):
log.status.Print('Aborted by user.')
return
current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
name=ca_ref.RelativeName()))
resource_args.CheckExpectedCAType(
messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
current_ca,
version='v1')
operation = client.projects_locations_caPools_certificateAuthorities.Disable(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesDisableRequest(
name=ca_ref.RelativeName(),
disableCertificateAuthorityRequest=messages
.DisableCertificateAuthorityRequest(
ignoreDependentResources=args.ignore_dependent_resources,
requestId=request_utils.GenerateRequestId())))
operations.Await(operation, 'Disabling Root CA', api_version='v1')
log.status.Print('Disabled Root CA [{}].'.format(ca_ref.RelativeName()))

View File

@@ -0,0 +1,73 @@
# -*- 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.
"""Enable a root certificate authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Enable(base.SilentCommand):
r"""Enable a root certificate authority.
Enables a root certificate authority. The root certificate authority will be
allowed to issue certificates once enabled.
## EXAMPLES
To enable a root CA:
$ {command} prod-root --location=us-west1 --pool=my-pool
"""
@staticmethod
def Args(parser):
resource_args.AddCertAuthorityPositionalResourceArg(parser, 'to enable')
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
ca_ref = args.CONCEPTS.certificate_authority.Parse()
current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
name=ca_ref.RelativeName()))
resource_args.CheckExpectedCAType(
messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
current_ca,
version='v1')
operation = client.projects_locations_caPools_certificateAuthorities.Enable(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesEnableRequest(
name=ca_ref.RelativeName(),
enableCertificateAuthorityRequest=messages
.EnableCertificateAuthorityRequest(
requestId=request_utils.GenerateRequestId())))
operations.Await(operation, 'Enabling Root CA', api_version='v1')
log.status.Print('Enabled Root CA [{}].'.format(ca_ref.RelativeName()))

View File

@@ -0,0 +1,115 @@
# -*- 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.
"""List the root certificate authorities within a project."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import resource_utils
from googlecloudsdk.api_lib.util import common_args
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.privateca import response_utils
from googlecloudsdk.command_lib.privateca import text_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List root certificate authorities.
List the root certificate authorities within a project.
## EXAMPLES
To list all root certificate authorities in a projects:
$ {command}
To list all root certificate authorities within a project and location
'us-central1':
$ {command} --location=us-central1
To list all root certificate authorities within a CA Pool in location
'us-central1':
$ {command} --pool=my-pool --location=us-central1
"""
@staticmethod
def Args(parser):
base.Argument(
'--location',
help='Location of the certificate authorities. If ommitted, root CAs across all regions will be listed.'
).AddToParser(parser)
base.Argument(
'--pool',
help='ID of the CA Pool where the certificate authorities reside. If ommitted, root CAs across all CA pools will be listed.'
).AddToParser(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, 100)
base.FILTER_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat("""
table(
name.basename(),
name.scope().segment(-5):label=LOCATION,
name.scope().segment(-3):label=POOL,
state,
state.regex("ENABLED","YES","NO"):label=INCLUDED_IN_POOL_ISSUANCE,
ca_certificate_descriptions[0].subject_description.not_before_time():label=NOT_BEFORE,
ca_certificate_descriptions[0].subject_description.not_after_time():label=NOT_AFTER)
""")
parser.display_info.AddTransforms({
'not_before_time': text_utils.TransformNotBeforeTime,
'not_after_time': text_utils.TransformNotAfterTime
})
parser.display_info.AddUriFunc(
resource_utils.MakeGetUriFunc(
'privateca.projects.locations.caPools.certificateAuthorities'))
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
location = args.location if args.IsSpecified('location') else '-'
ca_pool_id = args.pool if args.IsSpecified('pool') else '-'
if location == '-' and ca_pool_id != '-':
raise exceptions.InvalidArgumentException(
'--location',
'If a pool id is specified, you must also specify the location of that pool.'
)
parent_resource = 'projects/{}/locations/{}/caPools/{}'.format(
properties.VALUES.core.project.GetOrFail(), location, ca_pool_id)
request = messages.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesListRequest(
parent=parent_resource,
filter='type:SELF_SIGNED',
orderBy=common_args.ParseSortByArg(args.sort_by))
return list_pager.YieldFromList(
client.projects_locations_caPools_certificateAuthorities,
request,
field='certificateAuthorities',
limit=args.limit,
batch_size_attribute='pageSize',
batch_size=args.page_size,
get_field_func=response_utils.GetFieldAndLogUnreachable)

View File

@@ -0,0 +1,74 @@
# -*- 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.
"""Undelete a root Certificate Authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Undelete(base.SilentCommand):
r"""Undelete a root Certificate Authority.
Restores a root Certificate Authority that has been deleted. A Certificate
Authority can be undeleted within 30 days of being deleted. Use this command
to halt the deletion process. An undeleted CA will move to DISABLED state.
## EXAMPLES
To undelete a root CA:
$ {command} prod-root --location=us-west1 --pool=my-pool
"""
@staticmethod
def Args(parser):
resource_args.AddCertAuthorityPositionalResourceArg(parser, 'to undelete')
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
ca_ref = args.CONCEPTS.certificate_authority.Parse()
current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
name=ca_ref.RelativeName()))
resource_args.CheckExpectedCAType(
messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
current_ca,
version='v1')
operation = client.projects_locations_caPools_certificateAuthorities.Undelete(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesUndeleteRequest(
name=ca_ref.RelativeName(),
undeleteCertificateAuthorityRequest=messages
.UndeleteCertificateAuthorityRequest(
requestId=request_utils.GenerateRequestId())))
operations.Await(operation, 'Undeleting Root CA', api_version='v1')
log.status.Print('Undeleted Root CA [{}].'.format(ca_ref.RelativeName()))

View File

@@ -0,0 +1,77 @@
# -*- 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.
"""Update a root certificate authority."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.command_lib.privateca import update_utils
from googlecloudsdk.command_lib.util.args import labels_util
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Update(base.UpdateCommand):
r"""Update an existing root certificate authority.
## EXAMPLES
To update labels on a root CA:
$ {command} prod-root \
--location=us-west1 \
--pool=my-pool \
--update-labels=foo=bar
"""
@staticmethod
def Args(parser):
resource_args.AddCertAuthorityPositionalResourceArg(parser, 'to update')
labels_util.AddUpdateLabelsFlags(parser)
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
ca_ref = args.CONCEPTS.certificate_authority.Parse()
ca_name = ca_ref.RelativeName()
current_ca = client.projects_locations_caPools_certificateAuthorities.Get(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesGetRequest(
name=ca_name))
resource_args.CheckExpectedCAType(
messages.CertificateAuthority.TypeValueValuesEnum.SELF_SIGNED,
current_ca,
version='v1')
ca_to_update, update_mask = update_utils.UpdateCAFromArgs(
args, current_ca.labels)
# Patch is the REST client method associated with updating a CA.
operation = client.projects_locations_caPools_certificateAuthorities.Patch(
messages
.PrivatecaProjectsLocationsCaPoolsCertificateAuthoritiesPatchRequest(
name=ca_name,
certificateAuthority=ca_to_update,
updateMask=','.join(update_mask),
requestId=request_utils.GenerateRequestId()))
return operations.Await(operation, 'Updating Root CA.', api_version='v1')