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,38 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands for creating and manipulating service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.UniverseCompatible
class ServiceAccounts(base.Group):
"""Create and manipulate service accounts.
Create and manipulate IAM service accounts. A service account is a special
Google account that belongs to your application or a VM, instead of to an
individual end user. Your application uses the service account to call the
Google API of a service, so that the users aren't directly involved.
Note: Service accounts use client quotas for tracking usage.
More information on service accounts can be found at:
https://cloud.google.com/iam/docs/service-accounts
"""

View File

@@ -0,0 +1,50 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Add an IAM policy binding to an IAM service account.
description: |
Add an IAM policy binding to an IAM service account. A binding consists
of at least one member, a role, and an optional condition. Adding a binding to a service account grants the specified member the specified role on the service account.
When managing IAM roles, you can treat a service account either as a
resource or as an identity. This command adds an IAM policy binding to a
service account resource. There are other gcloud commands to manage IAM
policies for other types of resources. For example, to manage IAM policies
on a project, use the $ gcloud projects commands.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To add an IAM policy binding for the role of 'roles/editor' for the user 'test-user@gmail.com'
on a service account with identifier 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='user:test-user@gmail.com' --role='roles/editor'
To add an IAM policy binding for the role of 'roles/editor' to the service
account 'test-proj1@example.domain.com', run:
$ {command} test-proj1@example.domain.com --member='serviceAccount:test-proj1@example.domain.com' --role='roles/editor'
To add an IAM policy binding for the role of 'roles/editor' for all authenticated users on a
service account with identifier 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='allAuthenticatedUsers' --role='roles/editor'
To add an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/iam.serviceAccountAdmin' and the user 'test-user@gmail.com' on a service account with identifier 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='user:test-user@gmail.com' --role='roles/iam.serviceAccountAdmin' --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: iam.projects.serviceAccounts
arguments:
resource:
help_text: The service account to which the IAM policy binding is being added. Note that the user, group or service account in the --member flag is being granted access to this service account.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for managing Iam service account configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Iam service account configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Iam service account.
description: |
*{command}* exports the configuration for a Iam service account.
Service account configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
service accounts within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a service account, run:
$ {command} my-service-account
To export the configuration for a service account to a file, run:
$ {command} my-service-account --path=/path/to/dir/
To export the configuration for a service account in Terraform
HCL format, run:
$ {command} my-service-account --resource-format=terraform
To export the configurations for all service accounts within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Service account to export the configuration for.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create a service account for a project."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Create(base.CreateCommand):
"""Create a service account for a project.
This command creates a service account with the provided name. For
subsequent commands regarding service accounts, this service account should
be referred to by the email account in the response.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""
To create a service account for your project, run:
$ {command} some-account-name --display-name="My Service Account"
To work with this service account in subsequent IAM commands, use the
email resulting from this call as the IAM_ACCOUNT argument.
"""),
}
@staticmethod
def Args(parser):
parser.add_argument(
'--display-name', help='A textual name to display for the account.')
parser.add_argument(
'--description', help='A textual description for the account.')
parser.add_argument(
'name',
metavar='NAME',
help='The internal name of the new service account. '
'Used to generate an IAM_ACCOUNT (an IAM internal '
'email address used as an identifier of service '
'account), which must be passed to subsequent '
'commands.')
def Run(self, args):
project = properties.VALUES.core.project.Get(required=True)
client, messages = util.GetClientAndMessages()
result = client.projects_serviceAccounts.Create(
messages.IamProjectsServiceAccountsCreateRequest(
name=iam_util.ProjectToProjectResourceName(project),
createServiceAccountRequest=messages.CreateServiceAccountRequest(
accountId=args.name,
serviceAccount=messages.ServiceAccount(
displayName=args.display_name,
description=args.description))))
log.CreatedResource(args.name, kind='service account')
return result

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for deleting service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.api_lib.smart_guardrails import smart_guardrails
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
class Delete(base.DeleteCommand):
"""Delete a service account from a project.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""
To delete an service account from your project, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com
"""),
}
@classmethod
def Args(cls, parser):
iam_util.AddServiceAccountNameArg(
parser, action='to delete')
if cls.ReleaseTrack() != base.ReleaseTrack.GA:
iam_util.AddServiceAccountRecommendArg(parser, action='deletion')
def Run(self, args):
prompt_message = 'You are about to delete service account [{0}]'.format(
args.service_account
)
client, messages = util.GetClientAndMessages()
sa_resource_name = iam_util.EmailToAccountResourceName(args.service_account)
if self.ReleaseTrack() != base.ReleaseTrack.GA and args.recommend:
# Add deletion risk message to the prompt.
service_account = client.projects_serviceAccounts.Get(
messages.IamProjectsServiceAccountsGetRequest(name=sa_resource_name)
)
# Parent command group explicitly disables user project quota.
# Call with user project quota enabled, so that
# default project can be used as quota project.
base.EnableUserProjectQuota()
risk = smart_guardrails.GetServiceAccountDeletionRisk(
self.ReleaseTrack(),
service_account.projectId,
args.service_account,
)
base.DisableUserProjectQuota()
if risk:
prompt_message += '\n\n{0}'.format(risk)
console_io.PromptContinue(message=prompt_message, cancel_on_no=True)
client.projects_serviceAccounts.Delete(
messages.IamProjectsServiceAccountsDeleteRequest(name=sa_resource_name)
)
log.status.Print('deleted service account [{0}]'.format(
args.service_account))

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for getting service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
class Describe(base.DescribeCommand):
"""Show metadata for a service account from a project."""
detailed_help = {
'DESCRIPTION': textwrap.dedent("""
This command shows metadata for a service account.
This call can fail for the following reasons:
* The specified service account does not exist. In this case, you
receive a `PERMISSION_DENIED` error.
* The active user does not have permission to access the given
service account.
"""),
'EXAMPLES': textwrap.dedent("""
To print metadata for a service account from your project, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com
"""),
}
@staticmethod
def Args(parser):
iam_util.AddServiceAccountNameArg(
parser, action='to describe')
def Run(self, args):
client, messages = util.GetClientAndMessages()
return client.projects_serviceAccounts.Get(
messages.IamProjectsServiceAccountsGetRequest(
name=iam_util.EmailToAccountResourceName(args.service_account)))

View File

@@ -0,0 +1,30 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Disable an IAM service account.
description: |
Disable an IAM service account. After the service account is disabled, credential generation
and API requests using this service account will fail. Using `gcloud iam service-accounts
enable` to re-enable it.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To disable a service account from your project, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com
request:
collection: iam.projects.serviceAccounts
method: disable
response:
modify_response_hooks:
- googlecloudsdk.command_lib.iam.hooks:DisableIamAccountConfirmation
output:
format: none
arguments:
resource:
help_text: The IAM service account to disable.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Enable an IAM service account.
description: |
Enable an IAM service account.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To enable a service account from your project, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com
arguments:
resource:
help_text: The IAM service account to enable.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account
response:
modify_response_hooks:
- googlecloudsdk.command_lib.iam.hooks:EnableIamAccountConfirmation
output:
format: none
request:
collection: iam.projects.serviceAccounts
method: enable

View File

@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for getting IAM policies for service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
class GetIamPolicy(base.ListCommand):
"""Get the IAM policy for a service account.
This command gets the IAM policy for a service account. 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
$ gcloud iam service-accounts set-iam-policy for additional details.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""
To print the IAM policy for a given service account, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com
"""),
'DESCRIPTION': '\n\n'.join([
'{description}',
iam_util.GetHintForServiceAccountResource('get the iam policy of')])
}
@staticmethod
def Args(parser):
iam_util.AddServiceAccountNameArg(
parser,
action='whose policy to get')
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client, messages = util.GetClientAndMessages()
return client.projects_serviceAccounts.GetIamPolicy(
messages.IamProjectsServiceAccountsGetIamPolicyRequest(
resource=iam_util.EmailToAccountResourceName(args.service_account),
options_requestedPolicyVersion=
iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION))

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 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 creating and managing service account identity bindings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class IdentityBindings(base.Group):
"""Manage service account identity bindings."""

View File

@@ -0,0 +1,144 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create service account identity bindings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
import six
def _EncodeAttributeTranslatorCEL(cel_map, messages):
if not cel_map:
return None
attribute_translator_cels = [
messages.AttributeTranslatorCEL.AttributesValue.AdditionalProperty(
key=key, value=value) for key, value in six.iteritems(cel_map)
]
return messages.AttributeTranslatorCEL(
attributes=messages.AttributeTranslatorCEL.AttributesValue(
additionalProperties=attribute_translator_cels))
def _CreateRequest(args, messages):
"""_CreateRequest creates CreateServiceAccountIdentityBindingRequests."""
req = messages.CreateServiceAccountIdentityBindingRequest(
acceptanceFilter=args.acceptance_filter,
cel=_EncodeAttributeTranslatorCEL(args.attribute_translator_cel,
messages),
oidc=messages.IDPReferenceOIDC(
audience=args.oidc_audience,
maxTokenLifetimeSeconds=args.oidc_max_token_lifetime,
url=args.oidc_issuer_url,
),
)
return messages.IamProjectsServiceAccountsIdentityBindingsCreateRequest(
createServiceAccountIdentityBindingRequest=req,
name=iam_util.EmailToAccountResourceName(args.service_account))
class Create(base.CreateCommand):
"""Create a service account identity binding."""
@staticmethod
def Args(parser):
parser.add_argument(
'--service-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='The service account for which to create an identity binding.')
parser.add_argument(
'--acceptance-filter',
default=None,
help="""\
A CEL expression that is evaluated to determine whether a credential
should be accepted. To accept any credential, specify
`--acceptance-filter=true`.
This field supports a subset of the CEL functionality to select fields
and evaluate boolean expressions based on the input (no functions or
arithmetics). See
link:https://github.com/google/cel-spec[the CEL specification] for more
details.
The values for input claims are available using
``inclaim.attribute_name'' or ``inclaim["attribute_name"]''.
The values for output attributes calculated by the translator are
available using ``outclaim.attribute_name'' or
``outclaim["attribute_name"]''.
""")
parser.add_argument(
'--attribute-translator-cel',
type=arg_parsers.ArgDict(min_length=1),
default={},
metavar='OUT_ATTR=IN_ATTR',
action=arg_parsers.StoreOnceAction,
help="""\
Specifies a list of output attribute names and the corresponding input
attribute to use for that output attribute. Each defined output
attribute is populated with the value of the specified input attribute.
Each entry specifies the desired output attribute and a CEL field
selector expression for the corresponding input to read.
This field supports a subset of the CEL functionality to select fields
from the input (no boolean expressions, functions or arithmetics).
Output attributes must match `(google.sub|[a-z_][a-z0-9_]*)`.
The output attribute google.sub is interpreted to be the "identity" of
the requesting user.
For example, to copy the inbound attribute "sub" into the output
"google.sub" add the translation google.sub -> inclaim.sub (or
google.sub -> inclaim["sub"]). For example:
``--attribute-translator-cel="google.sub=inclaim.sub"''
See link:https://github.com/google/cel-spec[the CEL specification] for
more details.
If the input does not exist the output attribute will be null.
""")
oidc_group = parser.add_group(help='OIDC Identity Provider')
oidc_group.add_argument(
'--oidc-issuer-url',
required=True,
help='The OpenID Provider Issuer URL.')
oidc_group.add_argument(
'--oidc-audience',
default=None,
help='The acceptable audience. '
'Default is the numeric ID of the service account.')
oidc_group.add_argument(
'--oidc-max-token-lifetime',
default=None,
type=arg_parsers.BoundedInt(1), # Must be > 0
help='The maximum lifetime for tokens, in seconds. '
'The default is 3600 (1 hour).')
def Run(self, args):
client, messages = util.GetClientAndMessages()
req = _CreateRequest(args, messages)
result = client.projects_serviceAccounts_identityBindings.Create(req)
log.CreatedResource(result.name, kind='service account identity binding')
return result

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to describe service account identity bindings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core.console import console_io
class Delete(base.DeleteCommand):
"""Delete a service account identity binding."""
@staticmethod
def Args(parser):
parser.add_argument(
'binding_id',
metavar='BINDING-ID',
help='The ID of the identity binding.')
parser.add_argument(
'--service-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='The service account with the identity binding.')
def Run(self, args):
client, messages = util.GetClientAndMessages()
req = messages.IamProjectsServiceAccountsIdentityBindingsDeleteRequest(
name=iam_util.EmailAndIdentityBindingToResourceName(
args.service_account, args.binding_id))
console_io.PromptContinue(
message='You are about to delete identity binding [{0}] on service '
'account [{1}].'.format(args.binding_id, args.service_account),
cancel_on_no=True)
client.projects_serviceAccounts_identityBindings.Delete(req)
log.status.Print(
'Deleted identity binding [{0}] on service account [{1}]'.format(
args.binding_id, args.service_account))

View File

@@ -0,0 +1,46 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to describe service account identity bindings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
class Describe(base.DescribeCommand):
"""Describe a service account identity binding."""
@staticmethod
def Args(parser):
parser.add_argument(
'binding_id',
metavar='BINDING-ID',
help='The ID of the identity binding.')
parser.add_argument(
'--service-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='The service account with the identity binding.')
def Run(self, args):
client, messages = util.GetClientAndMessages()
req = messages.IamProjectsServiceAccountsIdentityBindingsGetRequest(
name=iam_util.EmailAndIdentityBindingToResourceName(
args.service_account, args.binding_id))
return client.projects_serviceAccounts_identityBindings.Get(req)

View File

@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to list service account identity bindings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
class List(base.ListCommand):
"""List identity bindings on a service account."""
@staticmethod
def Args(parser):
parser.add_argument(
'--service-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='The service account to list identity bindings for.')
def Run(self, args):
client, messages = util.GetClientAndMessages()
req = messages.IamProjectsServiceAccountsIdentityBindingsListRequest(
name=iam_util.EmailToAccountResourceName(args.service_account))
return client.projects_serviceAccounts_identityBindings.List(req)

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands for managing service account keys."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Keys(base.Group):
"""Manage service account keys."""

View File

@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for managing Iam key configurations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class Config(base.Group):
"""Manage Iam key configurations."""

View File

@@ -0,0 +1,38 @@
release_tracks: [ALPHA]
command_type: CONFIG_EXPORT
help_text:
brief: Export the configuration for a Iam key.
description: |
*{command}* exports the configuration for a Iam key.
Key configurations can be exported in
Kubernetes Resource Model (krm) or Terraform HCL formats. The
default format is `krm`.
Specifying `--all` allows you to export the configurations for all
keys within the project.
Specifying `--path` allows you to export the configuration(s) to
a local directory.
examples: |
To export the configuration for a key, run:
$ {command} my-key
To export the configuration for a key to a file, run:
$ {command} my-key --path=/path/to/dir/
To export the configuration for a key in Terraform
HCL format, run:
$ {command} my-key --resource-format=terraform
To export the configurations for all keys within a
project, run:
$ {command} --all
arguments:
resource:
help_text: Key to export the configuration for.
spec: !REF googlecloudsdk.command_lib.iam.resources:iam_key

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create service account keys."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
class Create(base.Command):
"""Create a service account key.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'NOTES': textwrap.dedent("""
The option --key-file-type=p12 is available here only for legacy
reasons; all new use cases are encouraged to use the default 'json'
format.
"""),
'EXAMPLES': textwrap.dedent("""
To create a new service account key and save the private
portion of the key locally, run:
$ {command} key.json --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
"""),
}
@staticmethod
def Args(parser):
parser.add_argument('--key-file-type',
choices=['json', 'p12'],
default='json',
help='The type of key to create.')
parser.add_argument('--iam-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help="""\
The service account for which to create a key.
To list all service accounts in the project, run:
$ gcloud iam service-accounts list
""")
parser.add_argument('output',
metavar='OUTPUT-FILE',
type=iam_util.GetIamOutputFileValidator(),
help='The path where the resulting private key should '
'be written. File system write permission will be '
'checked on the specified path prior to the key '
'creation.')
def Run(self, args):
client, messages = util.GetClientAndMessages()
result = client.projects_serviceAccounts_keys.Create(
messages.IamProjectsServiceAccountsKeysCreateRequest(
name=iam_util.EmailToAccountResourceName(args.iam_account),
createServiceAccountKeyRequest=
messages.CreateServiceAccountKeyRequest(
privateKeyType=iam_util.KeyTypeToCreateKeyType(
iam_util.KeyTypeFromString(args.key_file_type)))))
# Only the creating user has access. Set file permission to "-rw-------".
log.WriteToFileOrStdout(
args.output, content=result.privateKeyData, binary=True, private=True)
log.status.Print(
'created key [{0}] of type [{1}] as [{2}] for [{3}]'.format(
iam_util.GetKeyIdFromResourceName(result.name),
iam_util.KeyTypeToString(result.privateKeyType),
args.output,
args.iam_account))

View File

@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for deleting a service account key."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core import resources
from googlecloudsdk.core.console import console_io
class Delete(base.Command):
"""Delete a service account key.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""
To delete a key with ID `b4f1037aeef9ab37deee9` for the service
account `my-iam-account@my-project.iam.gserviceaccount.com`, run:
$ {command} b4f1037aeef9ab37deee9 --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
"""),
}
@staticmethod
def Args(parser):
parser.add_argument('--iam-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help="""\
The service account from which to delete a key.
To list all service accounts in the project, run:
$ gcloud iam service-accounts list
""")
parser.add_argument('key',
metavar='KEY-ID',
help='The key to delete.')
def Run(self, args):
key_ref = resources.REGISTRY.Parse(
args.key,
collection='iam.projects.serviceAccounts.keys',
params={
'serviceAccountsId': args.iam_account,
'projectsId': '-'
})
key = key_ref.keysId
console_io.PromptContinue(
message='You are about to delete key [{0}] for service '
'account [{1}].'.format(args.key, args.iam_account),
cancel_on_no=True)
client, messages = util.GetClientAndMessages()
client.projects_serviceAccounts_keys.Delete(
messages.IamProjectsServiceAccountsKeysDeleteRequest(
name=key_ref.RelativeName()))
log.status.Print('deleted key [{1}] for service account [{0}]'.format(
args.iam_account, key))

View File

@@ -0,0 +1,30 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Disable a service account key.
description: |
Disable a service account key.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To disable a key with ID `b4f1037aeef9ab37deee9` for the service
account `my-iam-account@my-project.iam.gserviceaccount.com`, run:
{command} b4f1037aeef9ab37deee9 --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.iam.resources:iam_key
is_positional: true
help_text: |
The id of the key to disable.
request:
collection: iam.projects.serviceAccounts.keys
method: disable
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:EraseProjectHook
response:
modify_response_hooks:
- googlecloudsdk.command_lib.iam.hooks:DisableIamKeyConfirmation

View File

@@ -0,0 +1,31 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Enable a service account key.
description: |
Enable a service account key.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To enable a key with ID `b4f1037aeef9ab37deee9` for the service
account `my-iam-account@my-project.iam.gserviceaccount.com`, run:
{command} b4f1037aeef9ab37deee9 --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.iam.resources:iam_key
is_positional: true
help_text: |
The id of the key to disable.
request:
collection: iam.projects.serviceAccounts.keys
method: enable
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:EraseProjectHook
response:
modify_response_hooks:
- googlecloudsdk.command_lib.iam.hooks:EnableIamKeyConfirmation

View File

@@ -0,0 +1,89 @@
# -*- 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 listing service account keys."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA)
class GetPublicKey(base.Command):
"""Get the public key for a service account key pair.
Get the public key for a service account key pair in pem or raw format.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""
To get the public key for some key ID for some service account
(to validate a blob or JWT signature, for example), run:
$ {command} keyid --output-file=key-file --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
"""),
}
@staticmethod
def Args(parser):
parser.add_argument('key', metavar='KEY-ID', help='The key to get.')
parser.add_argument(
'--output-file',
required=True,
help='The output file to write the public key.')
parser.add_argument(
'--iam-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='A textual name to display for the account.')
parser.add_argument(
'--type',
choices=['pem', 'raw'],
default='pem',
help='The type of the public key to get.')
parser.display_info.AddFormat(iam_util.SERVICE_ACCOUNT_KEY_FORMAT)
def Run(self, args):
key_ref = resources.REGISTRY.Parse(
args.key,
collection='iam.projects.serviceAccounts.keys',
params={
'serviceAccountsId': args.iam_account,
'projectsId': '-'
})
key = key_ref.keysId
client, messages = util.GetClientAndMessages()
result = client.projects_serviceAccounts_keys.Get(
messages.IamProjectsServiceAccountsKeysGetRequest(
name=key_ref.RelativeName(),
publicKeyType=iam_util.PublicKeyTypeFromString(args.type)))
log.WriteToFileOrStdout(
args.output_file, content=result.publicKeyData, binary=True)
log.status.Print('written key [{0}] for [{2}] as [{1}]'.format(
key, args.output_file, args.iam_account))

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for listing service account keys."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core.util import times
class List(base.ListCommand):
"""List the keys for a service account.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""
To list all user-managed keys created before noon on July 19th, 2015
(to perform key rotation, for example), run:
$ {command} --iam-account=my-iam-account@my-project.iam.gserviceaccount.com --managed-by=user --created-before=2015-07-19T12:00:00Z
"""),
}
@staticmethod
def Args(parser):
parser.add_argument('--managed-by',
choices=['user', 'system', 'any'],
default='any',
help='The types of keys to list.')
parser.add_argument(
'--created-before',
type=arg_parsers.Datetime.Parse,
help=('Return only keys created before the specified time. '
'Common time formats are accepted. This is equivalent to '
'--filter="validAfterTime<DATE_TIME". See '
'$ gcloud topic datetimes for information on time formats.'))
parser.add_argument('--iam-account',
required=True,
type=iam_util.GetIamAccountFormatValidator(),
help='A textual name to display for the account.')
parser.display_info.AddFormat(iam_util.SERVICE_ACCOUNT_KEY_FORMAT)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client, messages = util.GetClientAndMessages()
result = client.projects_serviceAccounts_keys.List(
messages.IamProjectsServiceAccountsKeysListRequest(
name=iam_util.EmailToAccountResourceName(args.iam_account),
keyTypes=iam_util.ManagedByFromString(args.managed_by)))
keys = result.keys
if args.created_before:
ts = args.created_before
keys = [
key for key in keys if times.ParseDateTime(key.validAfterTime) < ts
]
return keys

View File

@@ -0,0 +1,34 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Upload a public key for an IAM service account.
description: |
Upload a public key for an IAM service account.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
The following command uploads a public key certificate to a service account:
{command} test_data/public_key.cert --iam-account=my-iam-account@my-project.iam.gserviceaccount.com
arguments:
resource:
help_text: The service account for which to upload a key.
spec: !REF googlecloudsdk.command_lib.iam.resources:iam_account
is_positional: false
is_parent_resource: true
params:
- arg_name: public_key_file
api_field: uploadServiceAccountKeyRequest.publicKeyData
required: true
is_positional: true
help_text: |
Path of the file containing the public key. Note that only public key data in the format of
RSA_X509_PEM is supported. See https://cloud.google.com/iot/docs/concepts/device-security#public_key_format
for more information.
processor: googlecloudsdk.command_lib.iam.hooks:GeneratePublicKeyDataFromFile
request:
collection: iam.projects.serviceAccounts.keys
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:EraseProjectHook
- googlecloudsdk.command_lib.iam.hooks:SetServiceAccountResource
method: upload

View File

@@ -0,0 +1,67 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for to list all of a project's service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.iam import exceptions
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import properties
class List(base.ListCommand):
"""List all of a project's service accounts."""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""
To list all service accounts in the current project, run:
$ {command}
"""),
}
@staticmethod
def Args(parser):
base.ASYNC_FLAG.RemoveFromParser(parser)
base.PAGE_SIZE_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat(iam_util.SERVICE_ACCOUNT_FORMAT)
parser.display_info.AddUriFunc(iam_util.ServiceAccountsUriFunc)
def Run(self, args):
if args.limit is not None:
if args.limit < 1:
raise exceptions.InvalidArgumentException('Limit size must be >=1')
project = properties.VALUES.core.project.Get(required=True)
client, messages = util.GetClientAndMessages()
for item in list_pager.YieldFromList(
client.projects_serviceAccounts,
messages.IamProjectsServiceAccountsListRequest(
name=iam_util.ProjectToProjectResourceName(project)),
field='accounts',
limit=args.limit,
batch_size_attribute='pageSize'):
item.disabled = bool(item.disabled)
yield item

View File

@@ -0,0 +1,46 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Remove IAM policy binding from a service account.
description: |
Remove an IAM policy binding from the IAM policy of a service account. A binding consists of at
least one member, a role, and an optional condition.
When managing IAM roles, you can treat a service account either as a
resource or as an identity. This command is to remove a policy binding from
a service account resource. There are other gcloud commands to manage IAM
policies for other types of resources. For example, to manage IAM policies
on a project, use the $ gcloud projects commands.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To remove an IAM policy binding for the role of 'roles/editor' for the user 'test-user@gmail.com'
on a service account with identifier 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='user:test-user@gmail.com' --role='roles/editor'
To remove an IAM policy binding for the role of 'roles/editor' from all
authenticated users on service account 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='allAuthenticatedUsers' --role='roles/editor'
To remove an IAM policy binding which expires at the end of the year 2018 for the role of
'roles/iam.serviceAccountAdmin' and the user 'test-user@gmail.com' on a service account with identifier 'my-iam-account@my-project.iam.gserviceaccount.com', run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --member='user:test-user@gmail.com' --role='roles/iam.serviceAccountAdmin' --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: iam.projects.serviceAccounts
arguments:
resource:
help_text: The service account to remove the IAM policy binding from. Note that the user, group or service account in the --member flag is having its access revoked.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: options_requestedPolicyVersion

View File

@@ -0,0 +1,71 @@
# -*- 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.
"""Command for setting IAM policies for service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
class SetIamPolicy(base.Command):
"""Set the IAM policy for a service account.
This command replaces the existing IAM policy for a service account, given
an IAM_ACCOUNT and a file encoded in JSON or YAML that contains the IAM
policy. If the given policy file specifies an "etag" value, then the
replacement will succeed only if the policy already in place matches that
etag. (An etag obtained via $ gcloud iam service-accounts get-iam-policy will
prevent the replacement if the policy for the service account has been
subsequently updated.) A policy file that does not contain an etag value will
replace any existing policy for the service account.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = iam_util.GetDetailedHelpForSetIamPolicy(
'service account', 'my-iam-account@my-project.iam.gserviceaccount.com')
detailed_help['DESCRIPTION'] += '\n\n' + (
iam_util.GetHintForServiceAccountResource(
'set the iam policy of'))
@staticmethod
def Args(parser):
iam_util.AddServiceAccountNameArg(
parser,
action='whose policy to set')
parser.add_argument(
'policy_file',
metavar='POLICY_FILE',
help='Path to a local JSON or YAML formatted file '
'containing a valid policy.')
def Run(self, args):
client, messages = util.GetClientAndMessages()
policy = iam_util.ParsePolicyFile(args.policy_file, messages.Policy)
policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION
result = client.projects_serviceAccounts.SetIamPolicy(
messages.IamProjectsServiceAccountsSetIamPolicyRequest(
resource=iam_util.EmailToAccountResourceName(args.service_account),
setIamPolicyRequest=messages.SetIamPolicyRequest(
policy=policy)))
iam_util.LogSetIamPolicy(args.service_account, 'service account')
return result

View File

@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*- #
# Copyright 2015 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for signing blobs for service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core.util import files
class SignBlob(base.Command):
"""Sign a blob with a managed service account key.
This command signs a file containing arbitrary binary data (a blob) using a
system-managed service account key.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""
To sign a blob file with a system-managed service account key,
run:
$ {command} --iam-account=my-iam-account@my-project.iam.gserviceaccount.com input.bin output.bin
"""),
'SEE ALSO': textwrap.dedent("""
For more information on how this command ties into the wider cloud
infrastructure, please see
[](https://cloud.google.com/appengine/docs/java/appidentity/)
"""),
}
@staticmethod
def Args(parser):
parser.add_argument('--iam-account',
required=True,
help='The service account to sign as.')
parser.add_argument('input',
metavar='INPUT-FILE',
help='A path to the blob file to be signed.')
parser.add_argument('output',
metavar='OUTPUT-FILE',
help='A path the resulting signed blob will be '
'written to.')
def Run(self, args):
client, messages = util.GetIamCredentialsClientAndMessages()
response = client.projects_serviceAccounts.SignBlob(
messages.IamcredentialsProjectsServiceAccountsSignBlobRequest(
name=iam_util.EmailToAccountResourceName(args.iam_account),
signBlobRequest=messages.SignBlobRequest(
payload=files.ReadBinaryFileContents(args.input))))
log.WriteToFileOrStdout(
args.output, content=response.signedBlob, binary=True)
log.status.Print(
'signed blob [{0}] as [{1}] for [{2}] using key [{3}]'.format(
args.input, args.output, args.iam_account, response.keyId))

View File

@@ -0,0 +1,86 @@
# -*- 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 signing jwts for service accounts."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.core import log
from googlecloudsdk.core.util import files
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class SignJwt(base.Command):
"""Sign a JWT with a managed service account key.
This command signs a JWT using a system-managed service account key.
If the service account does not exist, this command returns a
`PERMISSION_DENIED` error.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""
To create a sign JWT with a system-managed service account key, run:
$ {command} --iam-account=my-iam-account@my-project.iam.gserviceaccount.com input.json output.jwt
"""),
'SEE ALSO':
textwrap.dedent("""
For more information on how this command ties into the wider cloud
infrastructure, please see
[](https://cloud.google.com/appengine/docs/java/appidentity/).
"""),
}
@staticmethod
def Args(parser):
parser.add_argument(
'--iam-account', required=True, help='The service account to sign as.')
parser.add_argument(
'input',
metavar='INPUT-FILE',
help='A path to the file containing the JSON'
' JWT Claim set to be signed.')
parser.add_argument(
'output',
metavar='OUTPUT-FILE',
help='A path the resulting signed JWT will be '
'written to.')
def Run(self, args):
client, messages = util.GetIamCredentialsClientAndMessages()
response = client.projects_serviceAccounts.SignJwt(
messages.IamcredentialsProjectsServiceAccountsSignJwtRequest(
name=iam_util.EmailToAccountResourceName(args.iam_account),
signJwtRequest=messages.SignJwtRequest(
payload=files.ReadFileContents(args.input,))))
log.WriteToFileOrStdout(
args.output, content=response.signedJwt, binary=False, private=True)
log.status.Print(
'signed jwt [{0}] as [{1}] for [{2}] using key [{3}]'.format(
args.input, args.output, args.iam_account, response.keyId))

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Undelete a service account for a project.
description: |
Undelete a service account for a project.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
The following command undeletes a service account with unique id
`103271949540120710052`:
$ {command} 103271949540120710052
arguments:
params:
- arg_name: account_id
api_field: name
required: true
is_positional: true
help_text: |
The deleted service account's unique ID must be provided when using the undelete command.
Unique IDs are a 21 digit number, such as 103271949540120710052.
processor: googlecloudsdk.command_lib.iam.hooks:CreateFullServiceAccountNameFromId
request:
collection: iam.projects.serviceAccounts
disable_resource_check: true
method: undelete

View File

@@ -0,0 +1,34 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Update an IAM service account.
description: |
Update an IAM service account.
If the service account does not exist, this command returns a `PERMISSION_DENIED` error.
examples: |
To update the description and display name for a service account, run:
$ {command} my-iam-account@my-project.iam.gserviceaccount.com --description="Updated description." --display-name="Updated Name"
arguments:
resource:
help_text: |-
The service account to update. The account should be formatted either as a numeric service account ID or as an email, like this: 123456789876543212345 or my-iam-account@somedomain.com.
spec: !REF googlecloudsdk.command_lib.iam.resources:service_account
params:
- arg_name: display-name
api_field: patchServiceAccountRequest.serviceAccount.displayName
help_text: |
The new textual name to display for the account.
- arg_name: description
api_field: patchServiceAccountRequest.serviceAccount.description
help_text: |
The new textual description for the account.
request:
collection: iam.projects.serviceAccounts
parse_resource_into_request: false
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:SetServiceAccountResource
- googlecloudsdk.command_lib.iam.hooks:ValidateUpdateFieldMask