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,26 @@
# -*- 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 templates."""
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 Templates(base.Group):
"""Manage certificate templates."""

View File

@@ -0,0 +1,33 @@
- release_tracks: [GA]
help_text:
brief: |
Add IAM policy binding for a certificate template.
description: |
Adds a policy binding to the IAM policy of a certificate template. One binding
consists of a member and a role.
See https://cloud.google.com/iam/docs/managing-policies for details of
the policy file format and contents.
examples: |
To add an IAM policy binding for the role of 'roles/privateca.templateUser' for the user
'test-user@gmail.com' on the certificate template 'mtls-template' with the location 'us-west1', run:
$ {command} mtls-template \
--location='us-west1' \
--member='user:test-user@gmail.com' \
--role='roles/privateca.templateUser'
request:
collection: privateca.projects.locations.certificateTemplates
api_version: v1
arguments:
resource:
help_text: The certificate template for which to add the IAM policy binding.
spec: !REF googlecloudsdk.command_lib.privateca.resources:certificate_template
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,114 @@
# -*- 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 certificate template."""
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.command_lib.util.args import labels_util
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
r"""Create a new certificate template."""
detailed_help = {
'DESCRIPTION':
"""\
Create a certificate template that enforces policy restrictions on
certificate requestors. Using a certificate template, you can define
restrictions on the kinds of Subjects/SANs and x509 extensions allowed
from certificate requestors as well as a default set of x509
extensions that should be applied to all certificates using that
template. These templates can be binded to IAM identities such that
certain groups of requestors must use particular templates, allowing
for fine-grained policy enforcements based on identity.
For more information and examples, see https://cloud.google.com/certificate-authority-service/docs/creating-certificate-template.
""",
'EXAMPLES':
"""\
To create a template that prohibits any x509 extension from a requester,
but permits custom subjects/SANs and defines the default x509
extensions, run:
$ {command} restricted-template --location=us-west1 --copy-subject --copy-sans --predefined-values-file=x509_parameters.yaml
To create a template that allows requesters to specify only DNS names
from requesters, use a custom CEL expression with a SAN only restriction:
$ {command} dns-only-template --location=us-west1 --description="Restricts certificates to DNS SANs." --no-copy-subject --copy-sans --identity-cel-expression="subject_alt_names.all(san, san.type == DNS)"
To create a template that permits a requestor to specify extensions by
OIDs, and subjects (but not SANs), with default x509 exensions:
$ {command} mtls-only-extensions --location=us-west1 --copy-subject --no-copy-sans --predefined-values-file=mtls_cert_exts.yaml --copy-extensions-by-oid=1.3.6.1.5.5.7.3.2,1.3.6.1.5.5.7.3.1
""",
}
@staticmethod
def Args(parser):
resource_args.AddCertificateTemplatePositionalResourceArg(parser,
'to create')
base.Argument(
'--description',
help='A text description for the Certificate Template.').AddToParser(
parser)
flags.AddPredefinedValuesFileFlag(parser)
flags.AddIdentityConstraintsFlags(parser)
flags.AddExtensionConstraintsFlags(parser)
flags.AddMaximumLifetimeFlag(parser)
labels_util.AddCreateLabelsFlags(parser)
def Run(self, args):
client = privateca_base.GetClientInstance('v1')
messages = privateca_base.GetMessagesModule('v1')
cert_template_ref = args.CONCEPTS.certificate_template.Parse()
flags.ValidateIdentityConstraints(args)
new_cert_template = messages.CertificateTemplate(
predefinedValues=flags.ParsePredefinedValues(args),
identityConstraints=flags.ParseIdentityConstraints(args),
passthroughExtensions=flags.ParseExtensionConstraints(args),
description=args.description
if args.IsSpecified('description')
else None,
maximumLifetime=flags.ParseMaximumLifetime(args),
)
operation = client.projects_locations_certificateTemplates.Create(
messages.PrivatecaProjectsLocationsCertificateTemplatesCreateRequest(
parent=cert_template_ref.Parent().RelativeName(),
certificateTemplateId=cert_template_ref.Name(),
certificateTemplate=new_cert_template,
requestId=request_utils.GenerateRequestId()))
cert_template_response = operations.Await(
operation, 'Creating Certificate Template.', api_version='v1')
cert_template = operations.GetMessageFromResponse(
cert_template_response, messages.CertificateTemplate)
log.status.Print('Created Certificate Template [{}].'.format(
cert_template.name))

View File

@@ -0,0 +1,74 @@
# -*- 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.
"""Delete a certificate template."""
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
from googlecloudsdk.core.console import console_io
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Delete(base.DeleteCommand):
r"""Delete a certificate template.
## EXAMPLES
To delete a certificate template:
$ {command} my-template --location=us-west1
To delete a certificate template while skipping the confirmation input:
$ {command} my-template --location=us-west1 --quiet
"""
@staticmethod
def Args(parser):
resource_args.AddCertificateTemplatePositionalResourceArg(
parser, 'to delete')
def Run(self, args):
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
template_ref = args.CONCEPTS.certificate_template.Parse()
template_name = template_ref.RelativeName()
if not console_io.PromptContinue(
message='You are about to delete the certificate template [{}]'.format(
template_ref.RelativeName()),
default=True):
log.status.Print('Aborted by user.')
return
operation = client.projects_locations_certificateTemplates.Delete(
messages
.PrivatecaProjectsLocationsCertificateTemplatesDeleteRequest(
name=template_name,
requestId=request_utils.GenerateRequestId()))
operations.Await(
operation, 'Deleting Certificate Template', api_version='v1')
log.status.Print(
'Deleted Certificate Template [{}].'.format(template_name))

View File

@@ -0,0 +1,18 @@
- release_tracks: [GA]
help_text:
brief: Show details about a certificate template.
description: Show details about a certificate template.
examples: |
To show details about a certificate template, run:
$ {command} my-template --location=us-central1
request:
collection: privateca.projects.locations.certificateTemplates
api_version: v1
arguments:
resource:
help_text: The certificate template you want to describe.
spec: !REF googlecloudsdk.command_lib.privateca.resources:certificate_template

View File

@@ -0,0 +1,27 @@
- release_tracks: [GA]
help_text:
brief: Get the IAM policy for a certificate template.
description: |
Gets the IAM policy for the given certificate template.
Returns an empty policy if the resource does not have a policy
set.
examples: |
To get the IAM policy for the certificate template 'mtls-template' with the location 'us-west1', run:
$ {command} mtls-template --location=us-west1
request:
collection: privateca.projects.locations.certificateTemplates
api_version: v1
arguments:
resource:
help_text: The certificate template for which to display the IAM policy.
spec: !REF googlecloudsdk.command_lib.privateca.resources:certificate_template
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""List certificate templates 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.command_lib.privateca import response_utils
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List certificate templates within a project."""
detailed_help = {
'DESCRIPTION':
'List certificate templates.',
'EXAMPLES':
"""\
To list all certificate templates in a project across all locations, run:
$ {command}
To list all certificate templates in a project and location 'us-central1',
run:
$ {command} --location=us-central1""",
}
@staticmethod
def Args(parser):
base.Argument(
'--location',
help=('The location you want to list the certificate templates for. '
'Set this to "-" to list certificate templates across all '
'locations.'),
default='-').AddToParser(parser)
base.PAGE_SIZE_FLAG.SetDefault(parser, 100)
base.SORT_BY_FLAG.SetDefault(parser, 'name')
parser.display_info.AddFormat("""
table(
name.scope("certificateTemplates"):label=NAME,
name.scope("locations").segment(0):label=LOCATION,
description
)""")
parser.display_info.AddUriFunc(
resource_utils.MakeGetUriFunc(
'privateca.projects.locations.certificateTemplates'))
def Run(self, args):
"""Runs the command."""
client = privateca_base.GetClientInstance(api_version='v1')
messages = privateca_base.GetMessagesModule(api_version='v1')
parent = 'projects/{}/locations/{}'.format(
properties.VALUES.core.project.GetOrFail(), args.location)
request = messages.PrivatecaProjectsLocationsCertificateTemplatesListRequest(
parent=parent,
orderBy=common_args.ParseSortByArg(args.sort_by),
filter=args.filter)
return list_pager.YieldFromList(
client.projects_locations_certificateTemplates,
request,
field='certificateTemplates',
limit=args.limit,
batch_size_attribute='pageSize',
batch_size=args.page_size,
get_field_func=response_utils.GetFieldAndLogUnreachable)

View File

@@ -0,0 +1,33 @@
- release_tracks: [GA]
help_text:
brief: |
Remove IAM policy binding for a certificate template.
description: |
Removes a policy binding to the IAM policy of a certificate template. One binding
consists of a member and a role.
See https://cloud.google.com/iam/docs/managing-policies for details of
the policy file format and contents.
examples: |
To remove an IAM policy binding for the role of 'roles/privateca.templateUser' for the user
'test-user@gmail.com' on the certificate template 'my-template' with the location 'us-west1', run:
$ {command} my-template \
--location=us-west1 \
--member='user:test-user@gmail.com' \
--role='roles/privateca.templateUser'
request:
collection: privateca.projects.locations.certificateTemplates
api_version: v1
arguments:
resource:
help_text: The certificate template for which to remove the IAM policy binding.
spec: !REF googlecloudsdk.command_lib.privateca.resources:certificate_template
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,203 @@
# -*- 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.
"""Replicate a certificate template to multiple regions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as api_exceptions
from googlecloudsdk.api_lib.privateca import base as privateca_base
from googlecloudsdk.api_lib.privateca import locations
from googlecloudsdk.api_lib.privateca import request_utils
from googlecloudsdk.calliope import arg_parsers
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
import six
class ReplicationError(Exception):
"""Represents an error that occurred while replicating a resource to a given location."""
def __init__(self, location, message):
self._message = 'Failed to replicate to location [{}]: {}'.format(
location, message)
super(ReplicationError, self).__init__(self._message)
def __str__(self):
return self._message
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Replicate(base.SilentCommand):
"""Replicate a certificate template to multiple locations."""
detailed_help = {
'DESCRIPTION':
'Replicate a certificate template to multiple locations.',
'EXAMPLES':
"""\
To replicate a certificate templates to all supported locations, run:
$ {command} my-template --location=us-west1 --all-locations
To replicate a certificate template to 'us-west2' and 'us-east1', run:
$ {command} my-template --location=us-west1 --target-locations=us-west2,us-east1
To overwrite existing templates with the same resource ID in the target
locations, use the --overwrite flag:
$ {command} my-template --location=us-west1 --target-locations=us-west2,us-east1 --overwrite
To continue replicating templates in other locations in the event of a
failure in one or more locations, use the --continue-on-error flag:
$ {command} my-template --location=us-west1 --all-locations --continue-on-error""",
}
@staticmethod
def Args(parser):
resource_args.AddCertificateTemplatePositionalResourceArg(
parser, 'to replicate')
target_locations_group = base.ArgumentGroup(
mutex=True,
required=True,
help='Specify where the certificate template should be replicated.'
).AddToParser(parser)
base.Argument(
'--all-locations',
action='store_const',
const=True,
help='Replicate this template to all supported locations.').AddToParser(
target_locations_group)
base.Argument(
'--target-locations',
help='Replicate this template to the given locations.',
type=arg_parsers.ArgList(
element_type=lambda x: six.text_type(x).strip()),
metavar='LOCATION').AddToParser(target_locations_group)
base.Argument(
'--overwrite',
help=('Overwrite any existing templates with the same name, '
'if they exist.'),
action='store_const',
const=True,
default=False).AddToParser(parser)
base.Argument(
'--continue-on-error',
help=('Continue replicating the template to other locations '
'even if an error is encountered. If this is set, an '
'error in one location will be logged but will not '
'prevent replication to other locations.'),
action='store_const',
const=True,
default=False).AddToParser(parser)
def _CreateOrUpdateTemplate(self, project, location, template_id, template,
overwrite):
"""Returns an LRO for a Create or Update operation for the given template.
Args:
project: str, the project ID or number for the new template.
location: str, the location for the new template.
template_id: str, the resource ID for the new template.
template: object, the body of the new template.
overwrite: bool, whether to overwrite existing templates with the same ID.
Raises:
ReplicationError, if the template could not be replicated to this
location.
"""
parent = 'projects/{}/locations/{}'.format(project, location)
resource_name = '{}/certificateTemplates/{}'.format(parent, template_id)
try:
return self.client.projects_locations_certificateTemplates.Create(
self.messages
.PrivatecaProjectsLocationsCertificateTemplatesCreateRequest(
parent=parent,
certificateTemplateId=template_id,
certificateTemplate=template,
requestId=request_utils.GenerateRequestId()))
except api_exceptions.HttpConflictError as e:
if not overwrite:
raise ReplicationError(
location,
'Certificate template [{}] already exists and the --overwrite flag '
'was not set.'.format(resource_name))
return self.client.projects_locations_certificateTemplates.Patch(
self.messages
.PrivatecaProjectsLocationsCertificateTemplatesPatchRequest(
name=resource_name,
certificateTemplate=template,
# Always copy all fields. Mask value of '*' doesn't seem to be
# currently supported by CCFE.
updateMask='predefined_values,identity_constraints,passthrough_extensions,description,labels',
requestId=request_utils.GenerateRequestId()))
except api_exceptions.HttpError as e:
raise ReplicationError(location, six.text_type(e))
def Run(self, args):
"""Runs the command."""
self.client = privateca_base.GetClientInstance(api_version='v1')
self.messages = privateca_base.GetMessagesModule(api_version='v1')
template_ref = args.CONCEPTS.certificate_template.Parse()
template = self.client.projects_locations_certificateTemplates.Get(
self.messages.PrivatecaProjectsLocationsCertificateTemplatesGetRequest(
name=template_ref.RelativeName()))
# Name is output-only and will be different for each location.
template.name = ''
success_count = 0
target_locations = args.target_locations
if args.all_locations:
target_locations = [
location for location in locations.GetSupportedLocations('v1')
if location != template_ref.locationsId
]
for location in target_locations:
location = location.strip()
if location == template_ref.locationsId:
log.warning(
'Skipping location [{}] since it is the source location.'.format(
location))
continue
try:
operation = self._CreateOrUpdateTemplate(template_ref.projectsId,
location, template_ref.Name(),
template, args.overwrite)
operations.Await(
operation,
'Replicating template to [{}]'.format(location),
api_version='v1')
success_count += 1
except ReplicationError as e:
if args.continue_on_error:
log.warning(six.text_type(e))
continue
raise e
log.status.Print(
'Replicated template [{}] to {} out of {} locations.'.format(
template_ref.RelativeName(), success_count, len(target_locations)))

View File

@@ -0,0 +1,29 @@
- release_tracks: [GA]
help_text:
brief: |
Set the IAM policy for a certificate template.
description: |
Sets the IAM policy for the given certificate template as defined in a JSON or YAML file.
See https://cloud.google.com/iam/docs/managing-policies for details of
the policy file format and contents.
examples: |
The following command will read an IAM policy defined in a JSON file
'policy.json' and set it for the certificate template 'my-template' with the location
'us-west1':
$ {command} my-template --location=us-west1 policy.json
request:
collection: privateca.projects.locations.certificateTemplates
api_version: v1
arguments:
resource:
help_text: The certificate template for which to update the IAM policy.
spec: !REF googlecloudsdk.command_lib.privateca.resources:certificate_template
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,198 @@
# -*- 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 new certificate template."""
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 exceptions as privateca_exceptions
from googlecloudsdk.command_lib.privateca import flags
from googlecloudsdk.command_lib.privateca import operations
from googlecloudsdk.command_lib.privateca import resource_args
from googlecloudsdk.command_lib.util.args import labels_util
from googlecloudsdk.core import log
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Create(base.CreateCommand):
r"""Update a certificate template."""
detailed_help = {
'DESCRIPTION': """Update a certificate template.""",
'EXAMPLES': """\
To update a template named "dns-restricted" with new default x509 extensions:
$ {command} dns-restricted --location=us-west1 --predefined-values-file=x509_parameters.yaml
To update a template named "dns-restricted" to allow requestors to specify subject:
$ {command} dns-restricted --location=us-west1 --copy-subject
To update a template named "dns-restricted" with allowed extension
'base-key-usage' to allow requestors to specify additional x509 extension 'extended-key-usage':
$ {command} dns-restricted --location=us-west1 --copy-known-extensions=base-key-usage,extended-key-usage
To update a template named "mtls-restricted" with allowed OID
'1.1' to allow requestors to specify alternative OIDS '2.2,3.3':
$ {command} mtls-restricted --location=us-west1 --copy-extensions-by-oid=2.2,3.3
""",
}
def _UpdateCertificateTemplateFromArgs(self, args, current_labels):
"""Creates a Certificate template object and update mask from Certificate template update flags.
Requires that args has 'description', 'copy-sans', 'copy-subject',
'predefined-values-file', 'copy-known-extensions', 'copy-extensions-by-oid',
and update labels flags registered.
Args:
args: The parser that contains the flag values.
current_labels: The current set of labels for the Certificate Template.
Returns:
A tuple with the Certificate template object to update with and the list
of
strings representing the update mask, respectively.
"""
messages = privateca_base.GetMessagesModule('v1')
template_to_update = messages.CertificateTemplate()
update_mask = []
# We'll parse the identity constraints if any of the flags are specified,
# but only include the paths in the update masks of the flags that were
# explicitly specified.
if (
args.IsSpecified('copy_sans')
or args.IsSpecified('copy_subject')
or args.IsSpecified('identity_cel_expression')
):
template_to_update.identityConstraints = flags.ParseIdentityConstraints(
args
)
if args.IsSpecified('copy_sans'):
update_mask.append(
'identity_constraints.allow_subject_alt_names_passthrough'
)
if args.IsSpecified('copy_subject'):
update_mask.append('identity_constraints.allow_subject_passthrough')
if args.IsSpecified('identity_cel_expression'):
update_mask.append('identity_constraints.cel_expression')
if args.IsSpecified('predefined_values_file'):
template_to_update.predefinedValues = flags.ParsePredefinedValues(args)
update_mask.append('predefined_values')
if args.IsSpecified('description'):
template_to_update.description = args.description
update_mask.append('description')
known_exts_flags = args.IsSpecified(
'copy_known_extensions'
) or args.IsSpecified('drop_known_extensions')
oid_exts_flags = args.IsSpecified(
'copy_extensions_by_oid'
) or args.IsSpecified('drop_oid_extensions')
if known_exts_flags or oid_exts_flags:
# Parse all extension flags into a CertificateExtensionConstraints
# message.
template_to_update.passthroughExtensions = (
flags.ParseExtensionConstraints(args)
)
if known_exts_flags:
update_mask.append('passthrough_extensions.known_extensions')
if oid_exts_flags:
update_mask.append('passthrough_extensions.additional_extensions')
labels_diff = labels_util.Diff.FromUpdateArgs(args)
labels_update = labels_diff.Apply(
messages.CaPool.LabelsValue, current_labels
)
if labels_update.needs_update:
template_to_update.labels = labels_update.labels
update_mask.append('labels')
if not update_mask:
raise privateca_exceptions.NoUpdateException(
'No updates found for the requested certificate template.'
)
return template_to_update, update_mask
@staticmethod
def Args(parser):
resource_args.AddCertificateTemplatePositionalResourceArg(
parser, 'to update'
)
base.Argument(
'--description', help='A text description for the Certificate Template.'
).AddToParser(parser)
flags.AddPredefinedValuesFileFlag(parser)
flags.AddIdentityConstraintsFlags(parser, require_passthrough_flags=False)
flags.AddExtensionConstraintsFlagsForUpdate(parser)
labels_util.AddUpdateLabelsFlags(parser)
def Run(self, args):
client = privateca_base.GetClientInstance('v1')
messages = privateca_base.GetMessagesModule('v1')
cert_template_ref = args.CONCEPTS.certificate_template.Parse()
template_name = cert_template_ref.RelativeName()
current_cert_template = client.projects_locations_certificateTemplates.Get(
messages.PrivatecaProjectsLocationsCertificateTemplatesGetRequest(
name=template_name
)
)
cert_template_to_update, update_mask = (
self._UpdateCertificateTemplateFromArgs(
args, current_cert_template.labels
)
)
# Confirm that the result of this update is intended to be identity
# reflection, if applicable.
flags.ValidateIdentityConstraints(
args,
existing_copy_subj=current_cert_template.identityConstraints.allowSubjectPassthrough,
existing_copy_sans=current_cert_template.identityConstraints.allowSubjectAltNamesPassthrough,
for_update=True,
)
operation = client.projects_locations_certificateTemplates.Patch(
messages.PrivatecaProjectsLocationsCertificateTemplatesPatchRequest(
name=template_name,
certificateTemplate=cert_template_to_update,
updateMask=','.join(update_mask),
requestId=request_utils.GenerateRequestId(),
)
)
cert_template_response = operations.Await(
operation, 'Updating Certificate Template.', api_version='v1'
)
cert_template = operations.GetMessageFromResponse(
cert_template_response, messages.CertificateTemplate
)
log.status.Print(
'Updated Certificate Template [{}].'.format(cert_template.name)
)