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,181 @@
# -*- coding: utf-8 -*- #
# Copyright 2013 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 super-group for the Cloud CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import actions
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.util.args import common_args
from googlecloudsdk.core import properties
class Gcloud(base.Group):
"""Manage Google Cloud resources and developer workflow.
The `gcloud` CLI manages authentication, local configuration, developer
workflow, and interactions with the Google Cloud APIs.
For a quick introduction to the `gcloud` CLI, a list of commonly
used commands, and a look at how these commands are structured, run
`gcloud cheat-sheet` or see the
[`gcloud` CLI cheat sheet](https://cloud.google.com/sdk/docs/cheatsheet).
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--account',
metavar='ACCOUNT',
category=base.COMMONLY_USED_FLAGS,
help='Google Cloud user account to use for invocation.',
action=actions.StoreProperty(properties.VALUES.core.account))
parser.add_argument(
'--universe-domain',
metavar='UNIVERSE_DOMAIN',
category=base.COMMONLY_USED_FLAGS,
help='Universe domain to target.',
hidden=True,
action=actions.StoreProperty(properties.VALUES.core.universe_domain))
# TODO(b/459796385): Clean up hasattr check a suitable period after bug has
# been fixed. Due to a latent bug introduced in gcloud version 524.0.0,
# updates on macOS will fail when surface code in latest version references
# new functions/attributes not present in cached modules from previous
# version. In this case, when updating from any version between 524.0.0 and
# 546.0.0, attempting to access properties.VALUES.regional here will result
# in a crash.
if (
hasattr(properties.VALUES, 'regional')
and hasattr(properties.VALUES.regional, 'GLOBAL')
and hasattr(properties.VALUES.regional, 'REGIONAL')
and hasattr(properties.VALUES.regional, 'REGIONAL_PREFERRED')
and hasattr(properties.VALUES.regional, 'endpoint_mode')
):
parser.add_argument(
'--force-endpoint-mode',
metavar='ENDPOINT_MODE',
choices=[
properties.VALUES.regional.GLOBAL,
properties.VALUES.regional.REGIONAL,
properties.VALUES.regional.REGIONAL_PREFERRED,
],
help='Regional endpoint mode to use.',
hidden=True,
action=actions.StoreProperty(
properties.VALUES.regional.endpoint_mode))
# Ideally this would be on the alpha group (since it's alpha) but there are
# a bunch of problems with doing that. Global flags are treated differently
# than other flags and flags on the Alpha group are not treated as global.
# The result is that the flag shows up on every man page as if it was part
# of the individual command (which is undesirable and breaks every surface
# spec).
parser.add_argument(
'--impersonate-service-account',
metavar='SERVICE_ACCOUNT_EMAILS',
help="""\
For this `gcloud` invocation, all API requests will be
made as the given service account or target service account in an
impersonation delegation chain instead of the currently selected
account. You can specify either a single service account as the
impersonator, or a comma-separated list of service accounts to
create an impersonation delegation chain. The impersonation is done
without needing to create, download, and activate a key for the
service account or accounts.
In order to make API requests as a service account, your
currently selected account must have an IAM role that includes
the `iam.serviceAccounts.getAccessToken` permission for the
service account or accounts.
The `roles/iam.serviceAccountTokenCreator` role has
the `iam.serviceAccounts.getAccessToken permission`. You can
also create a custom role.
You can specify a list of service accounts, separated with
commas. This creates an impersonation delegation chain in which
each service account delegates its permissions to the next
service account in the chain. Each service account in the list
must have the `roles/iam.serviceAccountTokenCreator` role on the
next service account in the list. For example, when
`--impersonate-service-account=`
``SERVICE_ACCOUNT_1'',``SERVICE_ACCOUNT_2'',
the active account must have the
`roles/iam.serviceAccountTokenCreator` role on
``SERVICE_ACCOUNT_1'', which must have the
`roles/iam.serviceAccountTokenCreator` role on
``SERVICE_ACCOUNT_2''.
``SERVICE_ACCOUNT_1'' is the impersonated service
account and ``SERVICE_ACCOUNT_2'' is the delegate.
""",
action=actions.StoreProperty(
properties.VALUES.auth.impersonate_service_account))
parser.add_argument(
'--access-token-file',
metavar='ACCESS_TOKEN_FILE',
help="""\
A file path to read the access token. Use this flag to
authenticate `gcloud` with an access token. The credentials of
the active account (if exists) will be ignored. The file should
only contain an access token with no other information.
""",
action=actions.StoreProperty(properties.VALUES.auth.access_token_file))
common_args.ProjectArgument().AddToParser(parser)
parser.add_argument(
'--billing-project',
metavar='BILLING_PROJECT',
category=base.COMMONLY_USED_FLAGS,
help="""\
The Google Cloud project that will be charged quota for
operations performed in `gcloud`. If you need to operate on one
project, but need quota against a different project, you can use
this flag to specify the billing project. If both
`billing/quota_project` and `--billing-project` are specified,
`--billing-project` takes precedence.
Run `$ gcloud config set --help` to see more information about
`billing/quota_project`.
""",
action=actions.StoreProperty(
properties.VALUES.billing.quota_project))
# Must have a None default so properties are not always overridden when the
# arg is not provided.
parser.add_argument(
'--quiet',
'-q',
default=None,
category=base.COMMONLY_USED_FLAGS,
action=actions.StoreConstProperty(
properties.VALUES.core.disable_prompts, True),
help="""\
Disable all interactive prompts when running `gcloud` commands. If input
is required, defaults will be used, or an error will be raised.
Overrides the default core/disable_prompts property value for this
command invocation. This is equivalent to setting the environment
variable `CLOUDSDK_CORE_DISABLE_PROMPTS` to 1.
""")
trace_group = parser.add_mutually_exclusive_group()
trace_group.add_argument(
'--trace-token',
default=None,
action=actions.StoreProperty(properties.VALUES.core.trace_token),
help='Token used to route traces of service requests for investigation'
' of issues.')

View File

@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for Access Approval."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class AccessApproval(base.Group):
"""Manage Access Approval requests and settings.
Access Approval enables customers to require explicit approval whenever
Google support and engineering needs to access customer data.
"""
category = base.IDENTITY_AND_SECURITY_CATEGORY

View File

@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for Access Approval requests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class AccessApproval(base.Group):
"""Manage Access Approval requests.
Approval requests are created by Google personnel to request approval from
Access Approval customers prior to making administrative accesses to their
resources. Customers can act on these requests using the commands in this
command group.
"""

View File

@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for approving an access approval request."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import requests
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import request_name
class Approve(base.Command):
"""Approve an Access Approval request.
Approve an Access Approval request. This will raise an error if the request
does not exist or is not in a pending state.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To approve an approval request using its name (e.g. projects/12345/approvalRequests/abc123), run:
$ {command} projects/12345/approvalRequests/abc123
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
request_name.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
return requests.Approve(request_name.GetName(args))

View File

@@ -0,0 +1,60 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for dismissing and access approval request."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import requests
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import request_name
class Dismiss(base.Command):
"""Dismiss an Access Approval request.
Dismiss an Access Approval request. Note: this does not deny access to the
resource if another request has been made and approved for the same resource.
This will raise an error if the request does not exist.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To dismiss an approval request using its name (e.g. projects/12345/approvalRequests/abc123), run:
$ {command} projects/12345/approvalRequests/abc123
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
request_name.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
return requests.Dismiss(request_name.GetName(args))

View File

@@ -0,0 +1,58 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to get an access approval request."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import requests
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import request_name
class Get(base.DescribeCommand):
"""Get an Access Approval request.
Get an Access Approval Request. Raise error if the request does not exist.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To get an approval request using its name (e.g. projects/my-project-123/approvalRequests/abc123), run:
$ {command} projects/my-project-123/approvalRequests/abc123
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
request_name.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
return requests.Get(request_name.GetName(args))

View File

@@ -0,0 +1,59 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 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 invalidating an access approval request."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import requests
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import request_name
class Invalidate(base.Command):
"""Invalidate an Access Approval request.
Invalidate an Access Approval request. This will raise an error if the request
does not exist or is not in an approved state.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To invalidate an approval request using its name (e.g. projects/12345/approvalRequests/abc123), run:
$ {command} projects/12345/approvalRequests/abc123
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
request_name.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
return requests.Invalidate(request_name.GetName(args))

View File

@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for access approval list requests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import requests
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import parent
class List(base.ListCommand):
"""List Access Approval requests.
List Access Approval requests by parent (project/folder/organization).
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To list all approval requests owned by project my-project-123, run:
$ {command} --project=my-project-123 --state=all
To list pending approval requests owned by organization 999, run:
$ {command} --organization=999
or
$ {command} --organization=999 --state=pending
Note that the user needs to have permission
accessapproval.requests.list on the project/folder/organization
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
parent.Args(parser)
parser.add_argument(
'--state',
default='pending',
help='filter for request state')
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
p = parent.GetParent(args)
return requests.List(parent=p, filter=(
args.state.upper() if args.state else None))

View File

@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 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 Access Approval settings."""
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 AccessApproval(base.Group):
"""Manage Access Approval service account.
Access Approval uses a unique service account when accessing custom keys for
signing approvals for a project, folder, or organization.
"""

View File

@@ -0,0 +1,69 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 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 access approval settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import service_account
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import parent
@base.ReleaseTracks(base.ReleaseTrack.GA)
class Get(base.DescribeCommand):
"""Get Access Approval service account.
Retrieves the service account that is used by Access Approval to access KMS
keys for signing approved approval requests.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To get the service account for the current project use
$ {command}
To get the service account for folder f1 use
$ {command} --folder=f1
To get the service account for organization org1 use
$ {command} --organization=org1
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
parent.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
p = parent.GetParent(args)
return service_account.Get(name=('%s/serviceAccount' % p))

View File

@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command group for managing Access Approval settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class AccessApproval(base.Group):
"""Manage Access Approval settings.
Access Approval settings can be set on projects, folders, or
organizations. The settings apply hierarchically. For example, enabling
Access Approval at the organization level enables it for all folders and
projects under the organization.
"""

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for deleting access approval settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import settings
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import parent
class Delete(base.UpdateCommand):
"""Delete Access Approval settings.
Delete the Access Approval settings associated with a project, a folder, or
organization.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To delete the settings for the current project use
$ {command}
To delete the settings for folder f1 use
$ {command} --folder=f1
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
parent.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
p = parent.GetParent(args)
return settings.Delete(name=('%s/accessApprovalSettings' % p))

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for getting access approval settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import settings
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.access_approval import parent
class Get(base.DescribeCommand):
"""Get Access Approval settings.
Get the Access Approval settings associated with a project, a folder, or
organization.
"""
detailed_help = {
'EXAMPLES':
textwrap.dedent("""\
To get the settings for the current project use
$ {command}
To get the settings for folder f1 use
$ {command} --folder=f1
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
parent.Args(parser)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
p = parent.GetParent(args)
return settings.Get(name=('%s/accessApprovalSettings' % p))

View File

@@ -0,0 +1,297 @@
# -*- coding: utf-8 -*- #
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for deleting access approval settings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import textwrap
from googlecloudsdk.api_lib.access_approval import settings
from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.access_approval import parent
_PREFERENCES = ('ORGANIZATION', 'FOLDER', 'PROJECT')
_APPROVAL_POLICY_PREFERENCES = (
'transparency',
'streamlined-support',
'access-approval',
'inherit-policy-from-parent',
)
@base.UniverseCompatible
class Update(base.Command):
"""Update Access Approval settings.
Update the Access Approval settings associated with a project, a folder, or
organization. Partial updates are supported (for example, you can update the
notification emails without modifying the enrolled services).
"""
detailed_help = {
'EXAMPLES': textwrap.dedent("""\
Update notification emails associated with project `p1`, run:
$ {command} --project=p1 --notification_emails='foo@example.com, bar@example.com'
Enable Access Approval enforcement for folder `f1`:
$ {command} --folder=f1 --enrolled_services=all
Enable Access Approval enforcement for organization `org1` for only Cloud Storage and Compute
products and set the notification emails at the same time:
$ {command} --organization=org1 --enrolled_services='storage.googleapis.com,compute.googleapis.com' --notification_emails='security_team@example.com'
Update active key version for project `p1`:
$ {command} --project=p1 --active_key_version='projects/p1/locations/global/keyRings/signing-keys/cryptoKeys/signing-key/cryptoKeyVersions/1'
Update preferred request expiration days for project `p1`:
$ {command} --project=p1 --preferred_request_expiration_days=5
Enable prefer no broad approval requests for project `p1`:
$ {command} --project=p1 --prefer_no_broad_approval_requests=true
Update notification pubsub topic for project `p1`:
$ {command} --project=p1 --notification_pubsub_topic='exampleTopic'
Update request scope max width preference for project `p1`:
$ {command} --project=p1 --request_scope_max_width_preference=PROJECT
Update approval policy for project `p1`:
$ {command} --project=p1 --approval_policy=transparency
"""),
}
@staticmethod
def Args(parser):
"""Add command-specific args."""
parent.Args(parser)
parser.add_argument(
'--notification_emails',
help=(
'Comma-separated list of email addresses to which notifications'
" relating to approval requests should be sent or '' to clear all"
' saved notification emails.'
),
)
parser.add_argument(
'--enrolled_services',
help=(
'Comma-separated list of services to enroll for Access Approval or'
" 'all' for all supported services. Note for project and folder"
" enrollments, only 'all' is supported. Use '' to clear all"
' enrolled services.'
),
)
parser.add_argument(
'--active_key_version',
help=(
'The asymmetric crypto key version to use for signing approval'
" requests. Use '' to remove the custom signing key."
),
)
parser.add_argument(
'--preferred_request_expiration_days',
type=int,
help=(
'The default expiration time for approval requests. This value must'
' be between 1 and 30. Note that this can be overridden at time of'
' Approval Request creation and modified by the customer at'
' approval time.'
),
)
parser.add_argument(
'--prefer_no_broad_approval_requests',
type=bool,
help=(
'If set to true it will communicate the preference to Google'
' personnel to request access with as targeted a resource scope as'
' possible.'
),
)
parser.add_argument(
'--notification_pubsub_topic',
help=(
'The pubsub topic to publish notifications to when approval'
' requests are made.'
),
)
parser.add_argument(
'--request_scope_max_width_preference',
choices=_PREFERENCES,
help=(
'The preference for the broadest scope of access for access'
' requests without a specific method.'
),
)
parser.add_argument(
'--require_customer_visible_justification',
type=bool,
help=(
'The preference to configure if a customer visible justification'
' (i.e. Vector Case) is required for a Googler to create an Access'
' Ticket to send to the customer when attempting to access customer'
' resources.'
),
)
parser.add_argument(
'--approval_policy',
choices=_APPROVAL_POLICY_PREFERENCES,
help=(
'The preference to configure the approval policy for access'
' requests.'
),
)
def Run(self, args):
"""This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
Some value that we want to have printed later.
"""
p = parent.GetParent(args)
if (
args.notification_emails is None
and args.enrolled_services is None
and args.active_key_version is None
and args.preferred_request_expiration_days is None
and args.prefer_no_broad_approval_requests is None
and args.notification_pubsub_topic is None
and args.request_scope_max_width_preference is None
and args.require_customer_visible_justification is None
and args.approval_policy is None
):
raise exceptions.MinimumArgumentException(
[
'--notification_emails',
'--enrolled_services',
'--active_key_version',
'--preferred_request_expiration_days',
'--prefer_no_broad_approval_requests',
'--notification_pubsub_topic',
'--request_scope_max_width_preference',
'--require_customer_visible_justification',
'--approval_policy',
],
'must specify at least one of these flags',
)
update_mask = []
emails_list = []
if args.notification_emails is not None:
update_mask.append('notification_emails')
if args.notification_emails:
emails_list = args.notification_emails.split(',')
emails_list = [i.strip() for i in emails_list]
services_list = []
if args.enrolled_services is not None:
update_mask.append('enrolled_services')
if args.enrolled_services:
services_list = args.enrolled_services.split(',')
services_list = [i.strip() for i in services_list]
if args.active_key_version is not None:
update_mask.append('active_key_version')
if args.preferred_request_expiration_days is not None:
update_mask.append('preferred_request_expiration_days')
if args.prefer_no_broad_approval_requests is not None:
update_mask.append('prefer_no_broad_approval_requests')
if args.notification_pubsub_topic is not None:
update_mask.append('notification_pubsub_topic')
msgs = apis.GetMessagesModule('accessapproval', 'v1')
request_scope_max_width_preference = None
if args.request_scope_max_width_preference is not None:
update_mask.append('request_scope_max_width_preference')
# Converts the string value of the RequestScopeMaxWidthPreference flag
# passed on the command line into the correct enum value.
preference_arg = args.request_scope_max_width_preference
if preference_arg == 'ORGANIZATION':
request_scope_max_width_preference = (
msgs.AccessApprovalSettings.RequestScopeMaxWidthPreferenceValueValuesEnum.ORGANIZATION
)
elif preference_arg == 'FOLDER':
request_scope_max_width_preference = (
msgs.AccessApprovalSettings.RequestScopeMaxWidthPreferenceValueValuesEnum.FOLDER
)
elif preference_arg == 'PROJECT':
request_scope_max_width_preference = (
msgs.AccessApprovalSettings.RequestScopeMaxWidthPreferenceValueValuesEnum.PROJECT
)
if args.require_customer_visible_justification is not None:
update_mask.append('require_customer_visible_justification')
if args.approval_policy is not None:
update_mask.append('approval_policy')
approval_policy_arg = args.approval_policy
if approval_policy_arg == 'transparency':
approval_policy = msgs.CustomerApprovalApprovalPolicy(
justificationBasedApprovalPolicy=msgs.CustomerApprovalApprovalPolicy.JustificationBasedApprovalPolicyValueValuesEnum.JUSTIFICATION_BASED_APPROVAL_ENABLED_ALL
)
elif (
approval_policy_arg
== 'streamlined-support'
):
approval_policy = msgs.CustomerApprovalApprovalPolicy(
justificationBasedApprovalPolicy=msgs.CustomerApprovalApprovalPolicy.JustificationBasedApprovalPolicyValueValuesEnum.JUSTIFICATION_BASED_APPROVAL_ENABLED_EXTERNAL_JUSTIFICATIONS
)
elif approval_policy_arg == 'access-approval':
approval_policy = msgs.CustomerApprovalApprovalPolicy(
justificationBasedApprovalPolicy=msgs.CustomerApprovalApprovalPolicy.JustificationBasedApprovalPolicyValueValuesEnum.JUSTIFICATION_BASED_APPROVAL_NOT_ENABLED
)
elif approval_policy_arg == 'inherit-policy-from-parent':
approval_policy = msgs.CustomerApprovalApprovalPolicy(
justificationBasedApprovalPolicy=msgs.CustomerApprovalApprovalPolicy.JustificationBasedApprovalPolicyValueValuesEnum.JUSTIFICATION_BASED_APPROVAL_INHERITED
)
else:
approval_policy = None
return settings.Update(
name=f'{p}/accessApprovalSettings',
notification_emails=emails_list,
enrolled_services=services_list,
active_key_version=args.active_key_version,
preferred_request_expiration_days=args.preferred_request_expiration_days,
prefer_no_broad_approval_requests=args.prefer_no_broad_approval_requests,
notification_pubsub_topic=args.notification_pubsub_topic,
request_scope_max_width_preference=request_scope_max_width_preference,
require_customer_visible_justification=args.require_customer_visible_justification,
approval_policy=approval_policy,
update_mask=','.join(update_mask),
)

View File

@@ -0,0 +1,38 @@
# -*- 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.
"""The command group for the Access Context Manager CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class AccessContextManager(base.Group):
"""Manage Access Context Manager resources.
Policy API for configuring context aware access features and access zones.
"""
category = base.IDENTITY_AND_SECURITY_CATEGORY
def Filter(self, context, args):
# TODO(b/190522787): Determine if command group works with project number
base.RequireProjectID(args)
del context, args

View File

@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 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 the Access Context Manager authorized organizations description CLI.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class AuthorizedOrgsDescs(base.Group):
"""Manage Access Context Manager authorized organizations descriptions.
An authorized organizations description describes a list of organizations (1)
that have been authorized to use certain asset (for example, device) data
owned by different organizations at the enforcement points, or (2) with
certain asset (for example, device) have been authorized to access the
resources in another organization at the enforcement points.
"""

View File

@@ -0,0 +1,48 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Create a new authorized organizations description.
description: |
Create a new authorized organizations description in a given access policy.
examples: |
To create a new authorized organizations description:
$ {command} --orgs=organizations/12345 \
--policy=9876543
request:
api_version: v1
collection: accesscontextmanager.accessPolicies.authorizedOrgsDescs
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=authorizedOrgsDesc.name
ALPHA:
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=authorizedOrgsDesc.name
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The authorized organizations description to create.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:authorized-orgs-desc
params:
- api_field: authorizedOrgsDesc.authorizationType
arg_name: authorization_type
required: true
help_text: The authorization type of the authorized organizations description. For example, trust, troubleshooting or logging.
- api_field: authorizedOrgsDesc.assetType
arg_name: asset_type
required: true
help_text: The asset type of this authorized organizations description. For example, device, or credential strength.
- api_field: authorizedOrgsDesc.authorizationDirection
arg_name: authorization_direction
required: true
help_text: Authorization direction of this authorization relationship. Specifies whether to allow specified organizations to evaluate this organization's traffic, or allow specified organizations traffic to be evaluated by this org.
- api_field: authorizedOrgsDesc.orgs
arg_name: orgs
help_text: |
Comma-separated list of organizations (in the following format: `organizations/<organizationnumber>`).

View File

@@ -0,0 +1,26 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Delete an authorized organizations description.
description: |
Delete an authorized organizations description in a given access policy.
examples: |
To delete an existing authorized organizations description, run:
$ {command} my_authorized_orgs_desc_id
request:
collection: accesscontextmanager.accessPolicies.authorizedOrgsDescs
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The authorized organizations description you want to delete.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:authorized-orgs-desc

View File

@@ -0,0 +1,23 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: Show details about an authorized organizations description.
description: |
Show details about an existing authorized organizations description.
examples: |
To get details about an existing authorized organizations description, run:
$ {command} my_authorized_orgs_desc_id
request:
collection: accesscontextmanager.accessPolicies.authorizedOrgsDescs
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The authorized organizations description for which you want to show details.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:authorized-orgs-desc

View File

@@ -0,0 +1,42 @@
- release_tracks: [ALPHA, GA]
help_text:
brief: List authorized organizations descriptions.
description: List all authorized organizations descriptions in an access policy object.
GA:
examples: |
To list authorized organizations description in an access policy, run:
$ {command}
This command prints out a list of authorized organizations descriptions in a tabular form:
NAME
my_authorized_orgs_desc
ALPHA:
examples: |
To list authorized organizations description in an access policy, run:
$ {command}
This will print out a list of authorized organizations descriptions in a tabular form:
NAME
my_authorized_orgs_desc
request:
collection: accesscontextmanager.accessPolicies.authorizedOrgsDescs
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The access policy for which you want to list the corresponding authorized organizations descriptions.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
output:
format: |
table(
name.basename()
)

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 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.
"""`gcloud access-context-manager authorized-orgs update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import authorized_orgs as authorized_orgs_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import authorized_orgs
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.command_lib.util.args import repeated
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateAuthorizedOrgsDescsBase(base.UpdateCommand):
"""Update an existing authorized organizations description."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
UpdateAuthorizedOrgsDescsBase.ArgsVersioned(parser)
@staticmethod
def ArgsVersioned(parser):
authorized_orgs.AddResourceArg(parser, 'to update')
authorized_orgs.AddAuthorizedOrgsDescUpdateArgs(parser)
def Run(self, args):
client = authorized_orgs_api.Client(version=self._API_VERSION)
authorized_orgs_desc_ref = args.CONCEPTS.authorized_orgs_desc.Parse()
result = repeated.CachedResult.FromFunc(client.Get,
authorized_orgs_desc_ref)
policies.ValidateAccessPolicyArg(authorized_orgs_desc_ref, args)
return self.Patch(
client=client,
authorized_orgs_desc_ref=authorized_orgs_desc_ref,
orgs=authorized_orgs.ParseOrgs(args, result),
)
def Patch(self, client, authorized_orgs_desc_ref, orgs):
return client.Patch(authorized_orgs_desc_ref, orgs=orgs)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateAuthorizedOrgsDescsAlpha(UpdateAuthorizedOrgsDescsBase):
"""Update an existing authorized orgsd desc."""
_INCLUDE_UNRESTRICTED = False
_API_VERSION = 'v1alpha'
@staticmethod
def Args(parser):
UpdateAuthorizedOrgsDescsBase.ArgsVersioned(parser)
detailed_help = {
'brief':
'Update the organizations for an existing authorized organizations '
'description.',
'DESCRIPTION':
('This command updates an authorized organizations description.'),
'EXAMPLES': (
'To update the organizations for an authorized organizations '
'description:\n\n $ {command} my-authorized-orgs '
'--add-orgs="organizations/123,organizations/456" ')
}
UpdateAuthorizedOrgsDescsBase.detailed_help = detailed_help
UpdateAuthorizedOrgsDescsAlpha.detailed_help = detailed_help

View File

@@ -0,0 +1,31 @@
# -*- 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 the Access Context Manager cloud-bindings CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.DefaultUniverseOnly
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.GA)
class AccessContextManager(base.Group):
"""Manage Access Context Manager cloud access bindings.
An access binding assigns an access level to a group, enforcing the policy
when a user in the group accesses the Cloud Console or API.
"""

View File

@@ -0,0 +1,345 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Create cloud access bindings for a specific group.
GA:
description: |
Create a new cloud access binding. The access level and/or session settings will be globally
bound with the group.
To apply access level and/or session settings to a specific application, specify the
restricted application in the 'binding-file'. In such case, the access level and/or
session settings specified in the yaml file will be bound with the group and the restricted
applications.
examples: |
To create a new cloud access binding, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc
To create a new cloud access binding for particular applications using a yaml file, run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--binding-file='binding.yaml'
To create a new global cloud access binding, and for particular applications
using a yaml file, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--organization='1234567890' \
--binding-file='binding.yaml'
To create a new cloud access binding for the dry run access level, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--dry-run-level=accessPolicies/123/accessLevels/def
To create a new cloud access binding with global session settings, specify your session
length using an ISO duration string and the `session-length` flag. For example:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h
To set a particular session reauth method for these session settings, run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h --session-reauth-method=LOGIN
To create session settings for a particular application, supply a YAML file and run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--binding-file='binding.yaml'
Global and per-app session settings can be set on the same group, along with access levels.
For example:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h --session-reauth-method=LOGIN \
--level=accessPolicies/123/accessLevels/abc \
--dry-run-level=accessPolicies/123/accessLevels/def \
--binding-file='binding.yaml'
ALPHA:
description: |
Create a new access binding. The access level (if any) will be bound with
- a group and the restricted client application
- a specific service account or all service accounts in a specified project.
The session settings (if any) will be bound with
- a group
If you want to bind session settings to a particular application, use scoped access
settings.
If a group key is specified, the access level and/or session settings are globally enforced
for all context-aware access group members, as specified in the binding.
If a restricted client application is also specified, then the enforcement applies only to
the specified application, and not to the entire organization. Session settings are
incompatible with the top level --restricted-client-application flags; please use
--binding-file to specify scoped access settings. If the restricted client application is
specified, then --binding-file cannot be set.
If a service account is specified, then the enforcement applies only to the specified
service account.
If a service account project is specified, the enforcement applies to all of the
service accounts belonging to the specified project.
examples: |
To create a new global cloud access binding, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc
To create a new cloud access binding for particular applications, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--organization='1234567890' \
--restricted-client-application-names='Google Cloud SDK, Cloud Console' \
--restricted-client-application-client-ids='123456789.apps.googleusercontent.com'
To create a new cloud access binding for particular applications using a yaml file, run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--binding-file='binding.yaml'
To create a new global cloud access binding, and for particular applications
using a yaml file, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--organization='1234567890' \
--binding-file='binding.yaml'
To create a new global cloud access binding for the dry run access level,
run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--dry-run-level=accessPolicies/123/accessLevels/def
To create a new cloud access binding for the dry run access level for particular
applications, run:
$ {command} --group-key=my-group-key --level=accessPolicies/123/accessLevels/abc \
--dry-run-level=accessPolicies/123/accessLevels/def \
--organization='1234567890' \
--restricted-client-application-names='Google Cloud SDK, Cloud Console' \
--restricted-client-application-client-ids='123456789.apps.googleusercontent.com'
To create a new cloud access binding for a particular service account, run:
$ {command} --service-account=service-account@project.iam.gserviceaccount.com \
--level=accessPolicies/123/accessLevels/abc \
--organization='1234567890'
To create a new cloud access binding for all service accounts in a particular project, run:
$ {command} --service-account-project-number='987654321' \
--level=accessPolicies/123/accessLevels/abc \
--organization='1234567890' \
To create a new cloud access binding for a specific federated principal, run:
$ {command} --federated-principal='//iam.googleapis.com/projects/1234567890/locations/global/workloadIdentityPools/my-pool/subject/my-subject' \
--level=accessPolicies/123/accessLevels/abc \
--organization='1234567890'
To create a new cloud access binding with global session settings, specify your session
length using an ISO duration string and the `session-length` flag. For example:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h
To set a particular session reauth method for these session settings, run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h --session-reauth-method=LOGIN
To create session settings for specific applications, supply a YAML file and run:
$ {command} --group-key=my-group-key --organization='1234567890' \
--binding-file='binding.yaml'
Global and per-app session settings can be set on the same group, along with access levels.
For example:
$ {command} --group-key=my-group-key --organization='1234567890' \
--session-length=2h --session-reauth-method=LOGIN \
--level=accessPolicies/123/accessLevels/abc \
--dry-run-level=accessPolicies/123/accessLevels/def \
--binding-file='binding.yaml'
GA:
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1
disable_resource_check: true
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessScopedAccessSettings
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessLevels
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessOrganization
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionSettings
ALPHA:
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1alpha
disable_resource_check: true
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessScopedAccessSettings
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessLevels
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessOrganization
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessRestrictedClientApplicationsAlpha
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionSettings
arguments:
params:
- api_field: gcpUserAccessBinding
metavar: YAML_FILE
arg_name: binding-file
help_text: |
Path to the file that contains a Google Cloud Platform user access binding.
This file contains a YAML-compliant object representing
a GcpUserAccessBinding (as described in the API reference) containing ScopedAccessSettings only.
No other binding fields are allowed.
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ParseGcpUserAccessBindingFromBindingFile:api_version=v1alpha
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ParseGcpUserAccessBindingFromBindingFile:api_version=v1
- api_field: gcpUserAccessBinding.groupKey
arg_name: group-key
type: str
help_text: Google Group ID whose members are subject to the restrictions of this binding.
GA:
required: true
- api_field: gcpUserAccessBinding.accessLevels
arg_name: level
type: str
GA:
help_text: |
The access level that binds to the given group. The input must be the full identifier
of an access level, such as `accessPolicies/123/accessLevels/abc`.
ALPHA:
help_text: |
The access level that binds to the given group and restricted client applications.
The input must be the full identifier of an access level, such as
`accessPolicies/123/accessLevels/abc`. If no `restricted-client-application-client-ids`
or `restricted-client-application-names` are provided, then the access level is applied
to the entire organization.
- api_field: gcpUserAccessBinding.dryRunAccessLevels
arg_name: dry-run-level
type: str
GA:
help_text: |
The dry run access level that binds to the given group. The dry run access level will be
evaluated but won't be enforced. Denial on dry run access level will be logged. The input
must be the full identifier of an access level, such as
`accessPolicies/123/accessLevels/new-def`.
ALPHA:
help_text: |
The dry run access level that binds to the given group and restricted client applications.
The dry run access level is evaluated but isn't enforced. Denial on a dry run access level
is logged. The input must be the full identifier of an access level, such as
`accessPolicies/123/accessLevels/new-def`. If no
`restricted-client-application-client-ids` or `restricted-client-application-names` are
provided, then the access level is applied to the entire organization.
- api_field: gcpUserAccessBinding.sessionSettings.sessionLength
arg_name: session-length
type: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionLength
GA:
help_text: |
The maximum lifetime of a user session provided as an ISO 8601 duration string. Must be at
least one hour or zero seconds, and no more than twenty-four hours. Granularity is limited
to seconds.
When --session-length=0 then users in the group attached to this binding will have infinite
session length, effectively disabling the session settings.
A session begins when a user signs in successfully. If a user signs out before the end of
the session lifetime, a new login creates a new session with a fresh lifetime. When a
session expires, the user is asked to re-authenticate in accordance with session-method.
Setting --session-reauth-method when --session-length is empty raises an error.
ALPHA:
help_text: |
The maximum lifetime of a user session provided as an ISO 8601 duration string. Must be at
least one hour or zero seconds, and no more than twenty-four hours. Granularity is limited
to seconds.
When --session-length=0 then users in the group attached to this binding will have infinite
session length, effectively disabling session.
A session begins when a user signs-in successfully. If a user signs out before the end of
the session lifetime, a new login creates a new session with a fresh lifetime. When a
session expires, the user is asked to re-authenticate in accordance with session-method.
Setting --session-reauth-method when --session-length is empty raises an error. Cannot set
--session-length with --restricted-client-application-client-ids or
--restricted-client-application-names; please use scoped access settings.
- api_field: gcpUserAccessBinding.sessionSettings.sessionReauthMethod
arg_name: session-reauth-method
default: login
help_text: |
Specifies the type of re-authentication challenge given to the user when their session
expires. Defaults to --session-reauth-method=login if unspecified and --session-length is
set. Cannot be used when --session-length is empty or 0.
choices:
- arg_value: login
enum_value: LOGIN
help_text: |
The user must complete a regular login.
- arg_value: security-key
enum_value: SECURITY_KEY
help_text: |
The user must re-autheticate using their security key. Before enabling this session reauth
method, ensure a security key is properly configured for the user. For help configuring
your security key, see
https://support.google.com/a/answer/2537800?hl=en#zippy=%2Cview-add-or-remove-security-keys
- arg_value: password
enum_value: PASSWORD
help_text: |
The user will only be required to enter their password.
- api_field: parent
arg_name: organization
type: googlecloudsdk.command_lib.util.hooks.types:Resource:collection=cloudresourcemanager.organizations
processor: googlecloudsdk.command_lib.util.hooks.processors:RelativeName
help_text: Parent organization for this binding.
- arg_name: policy
type: str
hidden: true
help_text: The access policy that the access level belongs to.
- arg_name: restricted-client-application-client-ids
required: false
release_tracks: [ALPHA]
type: 'googlecloudsdk.calliope.arg_parsers:ArgList:'
help_text: Client IDs to which the access level is applied.
- arg_name: restricted-client-application-names
required: false
release_tracks: [ALPHA]
type: 'googlecloudsdk.calliope.arg_parsers:ArgList:'
help_text: Application names to which the access level is applied.
- api_field: gcpUserAccessBinding.principal.serviceAccount
arg_name: service-account
hidden: true
required: false
release_tracks: [ALPHA]
type: str
help_text: |
The access level that binds to the given service account email. For example
`service-account@project.iam.gserviceaccount.com`.
- api_field: gcpUserAccessBinding.principal.serviceAccountProjectNumber
arg_name: service-account-project-number
hidden: true
required: false
release_tracks: [ALPHA]
type: str
help_text: |
The access level that binds to all the service accounts belong to the given project number.
- api_field: gcpUserAccessBinding.principal.federatedPrincipal
arg_name: federated-principal
hidden: true
required: false
release_tracks: [ALPHA]
type: str
help_text: |
The access level that binds to the given federated principal.
output:
format: yaml

View File

@@ -0,0 +1,24 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Delete a cloud access binding.
description: |
Delete an existing cloud access binding.
## EXAMPLES
To delete an existing cloud access binding, run:
$ {command} --binding=binding-id
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The cloud access binding you want to delete.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:cloud-access-binding
is_positional: false

View File

@@ -0,0 +1,24 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: Show details about a cloud access binding.
description: |
Show details about an existing cloud access binding.
## EXAMPLES
To get details about an existing cloud access binding, run:
$ {command} --binding=binding-id
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The cloud access binding you want to show details about
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:cloud-access-binding
is_positional: false

View File

@@ -0,0 +1,186 @@
- release_tracks: [GA, ALPHA]
help_text:
brief: List cloud access bindings under an organization.
description: List cloud access bindings.
GA:
examples: |
To list cloud access bindings, run:
$ {command}
This command prints a list of Google Cloud user access bindings, `gcpUserAccessBindings`,
in YAML format. By default, the binding is printed in the following format:
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
groupKey: a3dad
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
sessionSettings:
sessionLength: 57600s
sessionLengthEnabled: true
sessionReauthMethod: LOGIN
Or
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
groupKey: a3dad
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
scopedAccessSettings:
- activeSettings:
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunSettings:
accessLevels:
- accessPolicies/9522/accessLevels/specific_location
scope:
clientScope:
restrictedClientApplication:
clientId: 123.apps.googleusercontent.com
- activeSettings:
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunSettings:
accessLevels:
- accessPolicies/9522/accessLevels/specific_location
scope:
clientScope:
restrictedClientApplication:
name: Cloud Console
- activeSettings:
sessionSettings:
sessionLength: 57600s
sessionLengthEnabled: true
sessionReauthMethod: LOGIN
scope:
clientScope:
restrictedClientApplication:
clientId: 123.apps.googleusercontent.com
sessionSettings:
sessionLength: 57600s
sessionLengthEnabled: true
sessionReauthMethod: LOGIN
ALPHA:
examples: |
To list cloud access bindings, run:
$ {command}
This command prints a list of Google Cloud user access bindings, `gcpUserAccessBindings`,
in YAML format. By default, the binding is printed in the following format:
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
groupKey: a3dad
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
Or
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
groupKey: a3dad
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
scopedAccessSettings:
- activeSettings:
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunSettings:
accessLevels:
- accessPolicies/9522/accessLevels/specific_location
scope:
clientScope:
restrictedClientApplication:
clientId: 123.apps.googleusercontent.com
- activeSettings:
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunSettings:
accessLevels:
- accessPolicies/9522/accessLevels/specific_location
scope:
clientScope:
restrictedClientApplication:
name: Cloud Console
- activeSettings:
sessionSettings:
sessionLength: 57600s
sessionLengthEnabled: true
sessionReauthMethod: LOGIN
scope:
clientScope:
restrictedClientApplication:
clientId: 123.apps.googleusercontent.com
sessionSettings:
sessionLength: 57600s
sessionLengthEnabled: true
sessionReauthMethod: LOGIN
If filter is specified as
`principal:serviceAccount OR principal:serviceAccountProjectNumber`,
the output is printed in the following format:
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
principal:
serviceAccount: service_account@project.iam.gserviceaccount.com
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
Or
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
principal:
serviceAccountProjectNumber: 123456789
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
If filter is specified as
`principal:federatedPrincipal`,
the output is printed in the following format:
---
accessLevels:
- accessPolicies/9522/accessLevels/device_trusted
dryRunAccessLevels:
- accessPolicies/9522/accessLevels/specific_location
principal:
federatedPrincipal: principal://iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/pool-id/subject/subject-id
name: organizations/256/gcpUserAccessBindings/b3-BhcX_Ud5N
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
GA:
api_version: v1
ALPHA:
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessFilter
arguments:
resource:
help_text: The parent organization of the bindings you want to list.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:organization
output:
GA:
format: yaml(name, groupKey, accessLevels, dryRunAccessLevels, sessionSettings, restrictedClientApplications, scopedAccessSettings)
ALPHA:
format: yaml(name, groupKey, principal, accessLevels, dryRunAccessLevels, sessionSettings, restrictedClientApplications, scopedAccessSettings)

View File

@@ -0,0 +1,221 @@
- release_tracks: [GA, ALPHA]
GA:
help_text:
brief: Update a existing cloud access binding under an organization.
description: |
Update an existing cloud access binding. You can update the level, dry run level, session
settings, and scoped access settings. They cannot all be empty.
examples: |
To update an existing cloud access binding, run:
$ {command} --binding=my-binding-id --level=accessPolicies/123/accessLevels/new-abc
To remove level and add dry run level, run:
$ {command} --binding=my-binding-id --level= \
--dry-run-level=accessPolicies/123/accessLevels/new-def
To replace scoped access settings with a new list, run:
$ {command} --binding=my-binding-id --binding-file='binding.yaml'
To append scoped access settings to the existing list, run:
$ {command} --binding=my-binding-id --binding-file='binding.yaml' --append
Note this is only possible for scoped access settings that exclusively hold session
settings (i.e. no access levels).
To update session settings, run:
$ {command} --binding=my-binding-id --session-length=2h
To update the session reauth method you must also specify --session-length (this can be the
existing value if you only want to modify the reauth method), run:
$ {command} --binding=my-binding-id --session-length=2h --session-reauth-method=login
To disable session settings, set --session-length=0, for example:
$ {command} --binding=my-binding-id --session-length=0
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessScopedAccessSettings
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessLevels
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:AddUpdateMask
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionSettings
ALPHA:
help_text:
brief: Update an existing access binding under an organization.
description: |
Update an existing access binding. You can update the level, dry run level, scoped access
settings, session settings, restricted client application client IDs, and restricted client
application names.
They can't all be empty. Session settings are incompatible with restricted client
application client IDs/names; please use scoped access settings to bind session settings to
an application.
examples: |
To update an existing access binding, run:
$ {command} --binding=my-binding-id --level=accessPolicies/123/accessLevels/new-abc
To remove level and add dry run level, run:
$ {command} --binding=my-binding-id --level= \
--dry-run-level=accessPolicies/123/accessLevels/new-def
To update restricted client applications, run:
$ {command} --binding=my-binding-id \
--restricted-client-application-client-ids='123.apps.googleusercontent.com' \
--restricted-client-application-names='Cloud Console, Google Cloud SDK'
Or
$ {command} --binding=my-binding-id --binding-file='binding.yaml'
To replace scoped access settings with a new list, run:
$ {command} --binding=my-binding-id --binding-file='binding.yaml'
To append scoped access settings to the existing list, run:
$ {command} --binding=my-binding-id --binding-file='binding.yaml' --append
Note this is only possible for scoped access settings that exclusively hold session
settings.
To update session settings, run:
$ {command} --binding=my-binding-id --session-length=2h
To update the session reauth method you must also specify --session-length (this can be the
existing value if you only want to modify the reauth method), run:
$ {command} --binding=my-binding-id --session-length=2h --session-reauth-method=login
To disable session settings, set --session-length=0, for example:
$ {command} --binding=my-binding-id --session-length=0
request:
collection: accesscontextmanager.organizations.gcpUserAccessBindings
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessScopedAccessSettings
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessLevels
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessRestrictedClientApplicationsAlpha
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionSettings
- googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:AddUpdateMaskAlpha
arguments:
resource:
help_text: The cloud access binding you want to update.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:cloud-access-binding
is_positional: false
params:
- api_field: gcpUserAccessBinding
metavar: YAML_FILE
arg_name: binding-file
help_text: |
Path to the file that contains a Google Cloud Platform user access binding.
This file contains a YAML-compliant object representing
a GcpUserAccessBinding (as described in the API reference) containing ScopedAccessSettings only.
No other binding fields are allowed.
The file content replaces the corresponding fields in the existing binding. Unless --append
is specified. See --append help text for more details.
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ParseGcpUserAccessBindingFromBindingFile:api_version=v1alpha
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ParseGcpUserAccessBindingFromBindingFile:api_version=v1
- api_field: gcpUserAccessBinding.accessLevels
arg_name: level
type: str
help_text: |
The access level that replaces the existing level for the given binding. The input must
be the full identifier of an access level, such as
`accessPolicies/123/accessLevels/new-abc`.
- api_field: gcpUserAccessBinding.dryRunAccessLevels
arg_name: dry-run-level
type: str
help_text: |
The dry run access level that replaces the existing dry run level for the given binding.
The input must be the full identifier of an access level, such as
`accessPolicies/123/accessLevels/new-def`.
- api_field: gcpUserAccessBinding.sessionSettings.sessionLength
arg_name: session-length
type: googlecloudsdk.command_lib.accesscontextmanager.cloud_bindings:ProcessSessionLength
help_text: |
The maximum lifetime of a user session provided as an ISO 8601 duration string. Must be at
least one hour or zero, and no more than twenty-four hours. Granularity is limited to
seconds.
When --session-length=0 users in the group attached to this binding will have infinite
session length, effectively disabling the session settings.
A session begins after a user signs in successfully. If a user signs out before the end of
the session lifetime, a new login creates a new session with a fresh lifetime. When a
session expires, the user is asked to reauthenticate in accordance with
session-reauth-method.
Setting --session-reauth-method when --session-length is empty raises an error. Cannot set
--session-length on restricted client applications; please use scoped access settings.
- api_field: gcpUserAccessBinding.sessionSettings.sessionReauthMethod
arg_name: session-reauth-method
default: login
help_text: |
Specifies the security check a user must undergo when their session expires. Defaults to
--session-reauth-method=LOGIN if unspecified and --session-length is set. Cannot be used when
--session-length is empty or 0.
choices:
- arg_value: login
enum_value: LOGIN
help_text: |
The user will be prompted to perform regular login. Users who are enrolled in two-step
verification and haven't chosen to "Remember this computer" will be prompted for their
second factor.
- arg_value: security-key
enum_value: SECURITY_KEY
help_text: |
The user will be prompted to autheticate using their security key. If no security key has
been configured, the LOGIN method is used.
- arg_value: password
enum_value: PASSWORD
help_text: |
The user will only be required to enter their password.
- arg_name: policy
type: str
hidden: true
help_text: The access policy that the access level belongs to.
- arg_name: restricted-client-application-client-ids
required: false
release_tracks: [ALPHA]
type: 'googlecloudsdk.calliope.arg_parsers:ArgList:'
help_text: |
The application client IDs that replace the existing application client IDs for
the restricted client applications in the given binding.
- arg_name: restricted-client-application-names
required: false
release_tracks: [ALPHA]
type: 'googlecloudsdk.calliope.arg_parsers:ArgList:'
help_text: |
The application names that replace the existing application names for
the restricted client applications in the given binding.
- api_field: append
arg_name: append
help_text: |
When true, append the ScopedAccessSettings in `--binding-file` to the existing
ScopedAccessSettings on the binding. When false, the existing binding's ScopedAccessSettings
will be overwritten. Defaults to false. You may only append ScopedAccessSettings that
exclusively hold session settings (i.e no access levels).
required: false
default: false

View File

@@ -0,0 +1,29 @@
# -*- 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.
"""The command group for the Access Context Manager levels CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class AccessContextManager(base.Group):
"""Manage Access Context Manager levels.
An access level is a classification of requests based on raw attributes of
that request (e.g. IP address, device identity, time of day, etc.).
"""

View File

@@ -0,0 +1,30 @@
# -*- 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.
"""The command group for the Access Context Manager levels CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class LevelCondition(base.Group):
"""Manage Access Context Manager level conditions.
An access level is a classification of requests based on raw attributes of
that request (e.g. IP address, device identity, time of day, etc.). These
individual attributes are called conditions.
"""

View File

@@ -0,0 +1,43 @@
- release_tracks: [ALPHA, BETA, GA]
command_type: DESCRIBE
help_text:
brief: List conditions for an access level.
description: List conditions for a basic access level.
request:
collection: accesscontextmanager.accessPolicies.accessLevels
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
static_fields:
accessLevelFormat: AS_DEFINED
arguments:
resource:
help_text: The access level you want to list the conditions for.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:level
is_positional: false
output:
format: |
table(
basic:format="
table(format('Conditions are joined with {} operator.
', combiningFunction):label='')",
basic.conditions:format="
table[all-box,title='ACCESS LEVEL CONDITIONS'](
negate:label=NEGATED,
devicePolicy.list(),
ipSubnetworks.list(separator='
'),
members.list(separator='
'),
requiredAccessLevels.map().basename().list(separator='
')
)
"
)

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 Access Context Manager access level 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 Access Context Manager access level configurations."""

View File

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

View File

@@ -0,0 +1,89 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Create a new access level.
description: Create a new access level in a given access policy.
request:
collection: accesscontextmanager.accessPolicies.accessLevels
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=accessLevel.name
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.accesscontextmanager.levels:ClearCombiningFunctionUnlessBasicSpecSet
ALPHA:
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=accessLevel.name
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.accesscontextmanager.levels:ClearCombiningFunctionUnlessBasicSpecSet
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The access level to create.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:level
params:
- api_field: accessLevel.description
arg_name: description
required: false
help_text: Long-form description of access level.
- api_field: accessLevel.title
arg_name: title
required: true
help_text: Short human-readable title of the access level.
- group:
required: true
mutex: true
help_text: Level specification.
params:
- group:
help_text: Basic level specification.
params:
- api_field: accessLevel.basic.combiningFunction
arg_name: combine-function
default: and
help_text: For a basic level, determines how conditions are combined.
choices:
- arg_value: and
enum_value: AND
- arg_value: or
enum_value: OR
- api_field: accessLevel.basic.conditions
arg_name: basic-level-spec
required: true
help_text: |
Path to a file containing a list of basic access level conditions.
An access level condition file is a YAML-formatted list of
conditions, which are YAML objects representing a Condition as
described in the API reference. For example:
```
- ipSubnetworks:
- 162.222.181.197/24
- 2001:db8::/48
- members:
- user:user@example.com
```
repeated: false
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseBasicLevelConditions:api_version=v1
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseBasicLevelConditions:api_version=v1alpha
- group:
help_text: Custom level specification.
params:
- api_field: accessLevel.custom.expr
arg_name: custom-level-spec
help_text: |
Path to a file representing an expression that represents an access level.
The expression is in the Common Expression Language (CEL) format. For example:
```
expression: "origin.region_code in ['US', 'CA']"
```
repeated: false
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseCustomLevel:api_version=v1
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseCustomLevel:api_version=v1alpha

View File

@@ -0,0 +1,23 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: Delete an access level.
description: Delete an access level in a given access policy.
request:
collection: accesscontextmanager.accessPolicies.accessLevels
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The access level you want to delete.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:level

View File

@@ -0,0 +1,38 @@
- release_tracks: [GA, ALPHA, BETA]
help_text:
brief: Show details about an access level.
description: Show details about an access level in a given access policy.
examples: |
To show the details of the access policy ``my-policy'', run:
$ {command} my-policy
request:
collection: accesscontextmanager.accessPolicies.accessLevels
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The access level you want to show details about.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:level
params:
- api_field: accessLevelFormat
arg_name: level-format
required: false
default: as_defined
hidden: true # Hide until CEL is ready
help_text: The format in which to display the access level.
choices:
- arg_value: as_defined
enum_value: AS_DEFINED
help_text: Display each access level as-defined.
- arg_value: cel
enum_value: CEL
help_text: Display basic levels in CEL expression format.

View File

@@ -0,0 +1,28 @@
- release_tracks: [GA, ALPHA, BETA]
help_text:
brief: List access levels.
description: List access levels.
request:
collection: accesscontextmanager.accessPolicies.accessLevels
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The access policy you want to list the access levels for.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
output:
format: |
table(
name.basename(),
title,
format("{0}", basic.yesno(yes="Basic", no="Custom")):label=LEVEL_TYPE
)

View File

@@ -0,0 +1,97 @@
- release_tracks: [ALPHA, BETA, GA]
command_type: GENERIC
help_text:
brief: |
Replace all existing access levels.
description: |
Replace all existing access level in specified access policy with access levels specified in a
file.
## EXAMPLES
To replace all levels within a policy, using etag:
$ {command} my-policy-number --source-file=path-to-file-containing-all-replacement-access-levels.yaml --etag=optional-latest-etag-of-policy
To replace all levels within a policy, without using etag:
$ {command} my-policy-number --source-file=path-to-file-containing-all-replacement-access-levels.yaml
request:
collection: accesscontextmanager.accessPolicies.accessLevels
ALPHA:
api_version: v1alpha
method: replaceAll
BETA:
api_version: v1
method: replaceAll
GA:
api_version: v1
method: replaceAll
response:
ALPHA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.levels:ParseReplaceAccessLevelsResponse:api_version=v1alpha
BETA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.levels:ParseReplaceAccessLevelsResponse:api_version=v1
GA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.levels:ParseReplaceAccessLevelsResponse:api_version=v1
arguments:
resource:
help_text: The access policy that contains the levels you want to replace.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
override_resource_collection: true
params:
- api_field: replaceAccessLevelsRequest.etag
arg_name: etag
required: false
help_text: |
An etag which specifies the version of the Access Policy. Only etags
that represent the latest version of the Access Policy will be accepted.
repeated: false
- api_field: replaceAccessLevelsRequest.accessLevels
arg_name: source-file
required: true
help_text: |
Path to a file containing a list of access levels.
An access level file is a YAML-formatted list of access levels,
which are YAML objects representing a Basic or Custom level as described in
the API reference. For example:
```
- name: accessPolicies/my_policy/accessLevels/my_level
title: My Basic Level
description: Basic level for foo.
basic:
combiningFunction: AND
conditions:
- ipSubnetworks:
- 192.168.100.14/24
- 2001:db8::/48
- members
- user1:user1@example.com
- name: accessPolicies/my_policy/accessLevels/my_other_level
title: My Other Custom Level
description: Custom level for bar.
custom:
expr:
expression: "origin.region_code in ['US', 'CA']"
```
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.accessLevels
For other versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.accessLevels
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseAccessLevels:api_version=v1alpha
BETA:
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseAccessLevels:api_version=v1
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.levels:ParseAccessLevels:api_version=v1

View File

@@ -0,0 +1,105 @@
# -*- 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.
"""`gcloud access-context-manager levels update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import levels as levels_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import levels
from googlecloudsdk.command_lib.accesscontextmanager import policies
_API_VERSION_PER_TRACK = {'ALPHA': 'v1alpha', 'BETA': 'v1', 'GA': 'v1'}
_FEATURE_MASK_PER_TRACK = {
'ALPHA': {
'custom_levels': True
},
'BETA': {
'custom_levels': True
},
'GA': {
'custom_levels': True
}
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdateLevelGA(base.UpdateCommand):
"""Update an existing access level."""
_API_VERSION = _API_VERSION_PER_TRACK.get('GA')
_FEATURE_MASK = _FEATURE_MASK_PER_TRACK.get('GA')
@staticmethod
def Args(parser):
UpdateLevelGA.ArgsVersioned(parser, release_track='GA')
@staticmethod
def ArgsVersioned(parser, release_track):
api_version = _API_VERSION_PER_TRACK.get(release_track, 'v1')
feature_mask = _FEATURE_MASK_PER_TRACK.get(release_track, {})
levels.AddResourceArg(parser, 'to update')
levels.AddLevelArgs(parser)
levels.AddLevelSpecArgs(
parser, api_version=api_version, feature_mask=feature_mask)
def Run(self, args):
client = levels_api.Client(version=self._API_VERSION)
level_ref = args.CONCEPTS.level.Parse()
policies.ValidateAccessPolicyArg(level_ref, args)
basic_level_combine_function = None
if args.IsSpecified('combine_function'):
mapper = levels.GetCombineFunctionEnumMapper(
api_version=self._API_VERSION)
basic_level_combine_function = mapper.GetEnumForChoice(
args.combine_function)
custom_level_expr = None
if (self._FEATURE_MASK.get('custom_levels', False) and
args.IsSpecified('custom_level_spec')):
custom_level_expr = args.custom_level_spec
return client.Patch(
level_ref,
description=args.description,
title=args.title,
basic_level_combine_function=basic_level_combine_function,
basic_level_conditions=args.basic_level_spec,
custom_level_expr=custom_level_expr)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdateLevelBeta(UpdateLevelGA):
_API_VERSION = _API_VERSION_PER_TRACK.get('BETA')
_FEATURE_MASK = _FEATURE_MASK_PER_TRACK.get('BETA')
@staticmethod
def Args(parser):
UpdateLevelGA.ArgsVersioned(parser, release_track='BETA')
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdateLevelAlpha(UpdateLevelGA):
_API_VERSION = _API_VERSION_PER_TRACK.get('ALPHA')
_FEATURE_MASK = _FEATURE_MASK_PER_TRACK.get('ALPHA')
@staticmethod
def Args(parser):
UpdateLevelGA.ArgsVersioned(parser, release_track='ALPHA')

View File

@@ -0,0 +1,31 @@
# -*- 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.
"""The command group for the Access Context Manager perimeters CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class Zones(base.Group):
"""Manage Access Context Manager service perimeters.
A service perimeter describes a set of Google Cloud Platform resources which
can freely import and export data amongst themselves, but not externally.
Currently, the only allowed members of a service perimeter are projects.
"""

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 Access Context Manager service perimeter 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 Access Context Manager service perimeter configurations."""

View File

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

View File

@@ -0,0 +1,192 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Create a new service perimeter.
description: |
Create a new service perimeter in a given access policy.
examples: |
To create a new basic Service Perimeter:
$ {command} --title=my_perimeter_title --resources=projects/12345 --restricted-services="storage.googleapis.com" --policy=9876543
request:
api_version: v1
collection: accesscontextmanager.accessPolicies.servicePerimeters
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddAccessLevelsGA
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddVpcAccessibleServicesGA
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=servicePerimeter.name
ALPHA:
api_version: v1alpha
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddAccessLevelsAlpha
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddVpcAccessibleServicesAlpha
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=servicePerimeter.name
BETA:
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddAccessLevelsGA
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:AddVpcAccessibleServicesGA
- googlecloudsdk.command_lib.util.hooks.request_modifiers:SetFieldFromRelativeName:api_field=servicePerimeter.name
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The service perimeter to create.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:perimeter
params:
- api_field: servicePerimeter.description
arg_name: description
required: false
help_text: Long-form description of service perimeter.
- api_field: servicePerimeter.title
arg_name: title
required: true
help_text: Short human-readable title for the service perimeter.
- api_field: servicePerimeter.status.resources
arg_name: resources
help_text: |
Comma-separated list of resources (currently only projects, in the
form `projects/<projectnumber>`) in this perimeter.
- api_field: servicePerimeter.status.restrictedServices
arg_name: restricted-services
metavar: SERVICE
help_text: |
Comma-separated list of services to which the perimeter boundary
*does* apply (for example, `storage.googleapis.com`).
- arg_name: access-levels
api_field: servicePerimeter.status.accessLevels
metavar: LEVEL
# Added in AddAccessLevels hook because a type wouldn't have access to
# the policy of the service perimeter
type: arg_list
help_text: |
Comma-separated list of IDs for access levels (in the same policy)
that an intra-perimeter request must satisfy to be allowed.
- api_field: servicePerimeter.perimeterType
arg_name: perimeter-type
help_text: |
Type of the perimeter.
default: regular
choices:
- arg_value: regular
enum_value: PERIMETER_TYPE_REGULAR
help_text: |
Allows resources within this service perimeter to import and export
data amongst themselves.
A project may belong to at most one regular service perimeter.
- arg_value: bridge
enum_value: PERIMETER_TYPE_BRIDGE
help_text: |
Allows resources in different regular service perimeters to import
and export data between each other.
A project may belong to multiple bridge service perimeters (only if
it also belongs to a regular service perimeter). Both restricted and
unrestricted service lists, as well as access level lists,
must be empty.
- api_field: servicePerimeter.status.ingressPolicies
metavar: YAML_FILE
arg_name: ingress-policies
help_text: |
Path to a file containing a list of Ingress Policies.
This file contains a list of YAML-compliant objects representing
Ingress Policies described in the API reference.
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For more information about non-alpha versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseIngressPolicies:api_version=v1alpha
BETA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseIngressPolicies:api_version=v1
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseIngressPolicies:api_version=v1
- api_field: servicePerimeter.status.egressPolicies
metavar: YAML_FILE
arg_name: egress-policies
help_text: |
Path to a file containing a list of Engress Policies.
This file contains a list of YAML-compliant objects representing
Engress Policies described in the API reference.
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For more information about non-alpha versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseEgressPolicies:api_version=v1alpha
BETA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseEgressPolicies:api_version=v1
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseEgressPolicies:api_version=v1
- group:
release_tracks: [ALPHA]
mutex: true
required: false
params:
- api_field: servicePerimeter.status.vpcAccessibleServices
metavar: VPC_ACCESSIBLE_SERVICES_YAML_FILE
arg_name: vpc-accessible-services
help_text: |
Path to a YAML file containing the full VPC Accessible Services configuration.
This file should contain a single YAML object representing a VpcAccessibleServices
message as described in the API reference. This cannot be used with
`--vpc-allowed-services` or `--enable-vpc-accessible-services`.
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For more information about non-alpha versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseVpcAccessibleServices:api_version=v1alpha
- group:
mutex: false
params:
- api_field: servicePerimeter.status.vpcAccessibleServices.allowedServices
arg_name: vpc-allowed-services
metavar: VPC_SERVICE
help_text: |
Comma-separated list of APIs accessible from within the Service
Perimeter. In order to include all restricted services, use
reference "RESTRICTED-SERVICES".
Requires vpc-accessible-services be enabled.
- arg_name: enable-vpc-accessible-services
# api_field is not used here to allow the modify_request_hooks to handle
# the logic, preventing interference with the vpc-accessible-services YAML file.
type: bool
help_text: |
Whether to restrict API calls within the perimeter to those in the
vpc-allowed-services list.
- group:
release_tracks: [BETA, GA]
params:
- api_field: servicePerimeter.status.vpcAccessibleServices.allowedServices
arg_name: vpc-allowed-services
metavar: VPC_SERVICE
required: false
help_text: |
Comma-separated list of APIs accessible from within the Service
Perimeter. In order to include all restricted services, use
reference "RESTRICTED-SERVICES".
Requires vpc-accessible-services be enabled.
- api_field: servicePerimeter.status.vpcAccessibleServices.enableRestriction
arg_name: enable-vpc-accessible-services
required: false
type: bool
help_text: |
Whether to restrict API calls within the perimeter to those in the
vpc-allowed-services list.

View File

@@ -0,0 +1,23 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Delete a service perimeter.
description: Delete a service perimeter in a given access policy.
request:
collection: accesscontextmanager.accessPolicies.servicePerimeters
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
BETA:
api_version: v1
async:
collection: accesscontextmanager.operations
arguments:
resource:
help_text: The service perimeter you want to delete.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:perimeter

View File

@@ -0,0 +1,20 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Show details about a service perimeter.
description: Show details about an service perimeter in a given access policy.
request:
collection: accesscontextmanager.accessPolicies.servicePerimeters
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
BETA:
api_version: v1
arguments:
resource:
help_text: The service perimeter you want to show details about.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:perimeter

View File

@@ -0,0 +1,48 @@
# -*- 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 the Access Context Manager perimemters CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class DryRun(base.Group):
"""Manage the dry-run mode configuration for Service Perimeters."""
detailed_help = {
'brief':
'Enable management of dry-run mode configuration for Service Perimeters.',
'DESCRIPTION':
"""A Service Perimeter describes a set of Google Cloud Platform
resources which can freely import and export data amongst themselves,
but not externally, by default.
A dry-run mode configuration (also known as the Service Perimeter
`spec`) makes it possible to understand the impact of any changes to a
VPC Service Controls policy change before committing the change to the
enforcement mode configuration.
Note: For Service Perimeters without an explicit dry-run mode
configuration, the enforcement mode configuration is used as the dry-run
mode configuration, resulting in no audit logs being generated."""
}
DryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,310 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run create` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from apitools.base.py import exceptions as apitools_exceptions
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.command_lib.util.args import repeated
def _AddLegacyVpcAccessibleServicesArgsForCreate(parser, prefix=''):
vpc_group = parser.add_argument_group()
vpc_group.add_argument(
'--{}enable-vpc-accessible-services'.format(prefix),
action='store_true',
default=None,
help="""Whether to restrict API calls within the perimeter to those in the
`vpc-allowed-services` list.""",
)
vpc_group.add_argument(
'--{}vpc-allowed-services'.format(prefix),
metavar='vpc_allowed_services',
type=arg_parsers.ArgList(),
default=None,
help="""Comma-separated list of APIs accessible from within the Service
Perimeter. In order to include all restricted services, use
reference "RESTRICTED-SERVICES". Requires vpc-accessible-services
be enabled.""",
)
def _AddCommonArgsForDryRunCreate(parser, prefix='', version='v1'):
"""Adds arguments common to the two dry-run create modes.
Args:
parser: The argparse parser to add the arguments to.
prefix: Optional prefix, e.g. 'perimeter-' to use for the argument names.
version: Api version. e.g. v1alpha, v1beta, v1.
"""
parser.add_argument(
'--{}resources'.format(prefix),
metavar='resources',
type=arg_parsers.ArgList(),
default=None,
help="""Comma-separated list of resources (currently only projects, in the
form `projects/<projectnumber>`) in this perimeter.""")
parser.add_argument(
'--{}restricted-services'.format(prefix),
metavar='restricted_services',
type=arg_parsers.ArgList(),
default=None,
help="""Comma-separated list of services to which the perimeter boundary
*does* apply (for example, `storage.googleapis.com`).""")
parser.add_argument(
'--{}access-levels'.format(prefix),
metavar='access_levels',
type=arg_parsers.ArgList(),
default=None,
help="""Comma-separated list of IDs for access levels (in the same policy)
that an intra-perimeter request must satisfy to be allowed.""")
if version != 'v1alpha':
_AddLegacyVpcAccessibleServicesArgsForCreate(parser, prefix=prefix)
else:
# Mutually exclusive group for VPC configuration
vpc_config_group = parser.add_mutually_exclusive_group()
# New file-based argument
vpc_config_group.add_argument(
'--{}vpc-accessible-services'.format(prefix),
metavar='VPC_ACCESSIBLE_SERVICES_YAML_FILE',
type=perimeters.ParseVpcAccessibleServices(version),
help='Path to a YAML file containing a VpcAccessibleServices object.',
)
# Group for the old incremental flags
_AddLegacyVpcAccessibleServicesArgsForCreate(
vpc_config_group, prefix=prefix
)
parser.add_argument(
'--{}ingress-policies'.format(prefix),
metavar='YAML_FILE',
type=perimeters.ParseIngressPolicies(version),
default=None,
help="""Path to a file containing a list of Ingress Policies.
This file contains a list of YAML-compliant objects representing
Ingress Policies described in the API reference.
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For more information about non-alpha versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters"""
)
parser.add_argument(
'--{}egress-policies'.format(prefix),
metavar='YAML_FILE',
type=perimeters.ParseEgressPolicies(version),
default=None,
help="""Path to a file containing a list of Egress Policies.
This file contains a list of YAML-compliant objects representing
Egress Policies described in the API reference.
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For more information about non-alpha versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters"""
)
def _ParseArgWithShortName(args, short_name):
"""Returns the argument value for given short_name or None if not specified.
Args:
args: The argument object obtained by parsing the command-line arguments
using argparse.
short_name: The regular name for the argument to be fetched, such as
`access_levels`.
"""
alt_name = 'perimeter_' + short_name
if args.IsSpecified(short_name):
return getattr(args, short_name, None)
elif args.IsSpecified(alt_name):
return getattr(args, alt_name, None)
return None
def _ParseDirectionalPolicies(args):
ingress_policies = _ParseArgWithShortName(args, 'ingress_policies')
egress_policies = _ParseArgWithShortName(args, 'egress_policies')
return ingress_policies, egress_policies
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class CreatePerimeterDryRun(base.UpdateCommand):
"""Creates a dry-run spec for a new or existing Service Perimeter."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
CreatePerimeterDryRun.ArgsVersioned(parser, version='v1')
@staticmethod
def ArgsVersioned(parser, version='v1'):
parser.add_argument(
'--async',
action='store_true',
help="""Return immediately, without waiting for the operation in
progress to complete.""")
perimeters.AddResourceArg(parser, 'to update')
top_level_group = parser.add_mutually_exclusive_group(required=True)
existing_perimeter_group = top_level_group.add_argument_group(
'Arguments for creating dry-run spec for an **existing** Service '
'Perimeter.')
_AddCommonArgsForDryRunCreate(existing_perimeter_group, version=version)
new_perimeter_group = top_level_group.add_argument_group(
'Arguments for creating a dry-run spec for a new Service Perimeter.')
_AddCommonArgsForDryRunCreate(
new_perimeter_group, prefix='perimeter-', version=version)
new_perimeter_group.add_argument(
'--perimeter-title',
required=True,
default=None,
help="""Short human-readable title for the Service Perimeter.""")
new_perimeter_group.add_argument(
'--perimeter-description',
default=None,
help="""Long-form description of Service Perimeter.""")
new_perimeter_group.add_argument(
'--perimeter-type',
required=True,
default=None,
help="""Type of the perimeter.
A *regular* perimeter allows resources within this service perimeter
to import and export data amongst themselves. A project may belong
to at most one regular service perimeter.
A *bridge* perimeter allows resources in different regular service
perimeters to import and export data between each other. A project
may belong to multiple bridge service perimeters (only if it also
belongs to a regular service perimeter). Both restricted and
unrestricted service lists, as well as access level lists, must be
empty.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
perimeter_type = perimeters.GetPerimeterTypeEnumForShortName(
args.perimeter_type, self._API_VERSION)
# Extract the arguments that reside in a ServicePerimeterConfig.
resources = _ParseArgWithShortName(args, 'resources')
levels = _ParseArgWithShortName(args, 'access_levels')
levels = perimeters.ExpandLevelNamesIfNecessary(
levels, perimeter_ref.accessPoliciesId)
restricted_services = _ParseArgWithShortName(args, 'restricted_services')
vpc_accessible_services_config = None
if self._API_VERSION == 'v1alpha':
# Parse the new file-based config if present (will only be there for
# alpha)
vpc_accessible_services_config = _ParseArgWithShortName(
args, 'vpc_accessible_services'
)
vpc_allowed_services = _ParseArgWithShortName(args, 'vpc_allowed_services')
ingress_policies, egress_policies = _ParseDirectionalPolicies(args)
if (args.enable_vpc_accessible_services is None and
args.perimeter_enable_vpc_accessible_services is None):
enable_vpc_accessible_services = None
else:
enable_vpc_accessible_services = (
args.enable_vpc_accessible_services or
args.perimeter_enable_vpc_accessible_services)
result = repeated.CachedResult.FromFunc(client.Get, perimeter_ref)
try:
result.Get() # Check if the perimeter was actually obtained.
except apitools_exceptions.HttpNotFoundError:
if args.perimeter_title is None or perimeter_type is None:
raise exceptions.RequiredArgumentException(
'perimeter-title',
('Since this Service Perimeter does not exist, perimeter-title '
'and perimeter-type must be supplied.'))
else:
if args.perimeter_title is not None or perimeter_type is not None:
raise exceptions.InvalidArgumentException('perimeter-title', (
'A Service Perimeter with the given name already exists. The '
'title and the type fields cannot be updated in the dry-run mode.'))
policies.ValidateAccessPolicyArg(perimeter_ref, args)
return client.PatchDryRunConfig(
perimeter_ref,
title=args.perimeter_title,
description=args.perimeter_description,
perimeter_type=perimeter_type,
resources=resources,
levels=levels,
restricted_services=restricted_services,
vpc_allowed_services=vpc_allowed_services,
enable_vpc_accessible_services=enable_vpc_accessible_services,
vpc_yaml_flag_used=vpc_accessible_services_config is not None,
vpc_accessible_services_config=vpc_accessible_services_config,
ingress_policies=ingress_policies,
egress_policies=egress_policies,
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class CreatePerimeterDryRunAlpha(CreatePerimeterDryRun):
"""Creates a dry-run spec for a new or existing Service Perimeter."""
_API_VERSION = 'v1alpha'
@staticmethod
def Args(parser):
CreatePerimeterDryRun.ArgsVersioned(parser, version='v1alpha')
detailed_help = {
'brief':
"""Create a dry-run mode configuration for a new or existing Service
Perimeter.""",
'DESCRIPTION': (
'When a Service Perimeter with the specified name does not exist, a '
'new Service Perimeter will be created. In this case, the newly '
'created Service Perimeter will not have any enforcement mode '
'configuration, and, therefore, all policy violations will be '
'logged.\n\nWhen a perimeter with the specified name does exist, a '
'dry-run mode configuration will be created for it. The behavior of '
'the enforcement mode configuration, if present, will not be impacted '
'in this case. Requests that violate the existing enforcement mode '
'configuration of the Service Perimeter will continue being denied. '
'Requests that only violate the policy in the dry-run mode '
'configuration will be logged but will not be denied.'),
'EXAMPLES': (
'To create a dry-run configuration for an existing Service '
'Perimeter:\n\n $ {command} my-perimeter '
'--resources="projects/0123456789" '
'--access-levels="accessPolicies/a_policy/accessLevels/a_level" '
'--restricted-services="storage.googleapis.com"\n\nTo create a dry-run'
' configuration for a new Service Perimeter:\n\n $ {command} '
'my-perimeter --perimeter-title="My New Perimeter" '
'--perimeter-description="Perimeter description" '
'--perimeter-type="regular" '
'--perimeter-resources="projects/0123456789" '
'--perimeter-access-levels="accessPolicies/a_policy/accessLevels/a_level"'
' --perimeter-restricted-services="storage.googleapis.com"')
}
CreatePerimeterDryRunAlpha.detailed_help = detailed_help
CreatePerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,68 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run delete` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class DeletePerimeterDryRun(base.UpdateCommand):
"""Marks the Service Perimeter for deletion in the dry-run mode."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
perimeters.AddResourceArg(parser, 'to delete')
parser.add_argument(
'--async',
action='store_true',
help="""Return immediately, without waiting for the operation in
progress to complete.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
policies.ValidateAccessPolicyArg(perimeter_ref, args)
return client.UnsetSpec(perimeter_ref, use_explicit_dry_run_spec=True)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DeletePerimeterDryRunAlpha(DeletePerimeterDryRun):
"""Marks the Service Perimeter for deletion in the dry-run mode."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief':
'Mark the Service Perimeter as deleted in the dry-run mode.',
'DESCRIPTION':
('When this command completed successfully, the affected Service '
'Perimeter will be considered to have been deleted in the dry-run '
'mode, but the enforcement mode configuration will be left untouched.'
),
'EXAMPLES':
('To mark the Service Perimeter as deleted in the dry-run mode:\n\n'
' $ {command} my-perimeter')
}
DeletePerimeterDryRunAlpha.detailed_help = detailed_help
DeletePerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,93 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run describe` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class DescribePerimeterDryRun(base.DescribeCommand):
"""Displays the dry-run mode configuration for a Service Perimeter."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
perimeters.AddResourceArg(parser, 'to describe')
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
policies.ValidateAccessPolicyArg(perimeter_ref, args)
perimeter = client.Get(perimeter_ref)
perimeters.GenerateDryRunConfigDiff(perimeter, self._API_VERSION)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribePerimeterDryRunAlpha(DescribePerimeterDryRun):
"""Displays the dry-run mode configuration for a Service Perimeter."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief':
'Display the dry-run mode configuration for a Service Perimeter.',
'DESCRIPTION':
('The dry-run mode configuration is presented as a diff against the '
'enforcement mode configuration. \'+\' indicates additions in `spec`,'
'\'-\' indicates removals from `status` and entries without either of '
'those indicate that they are the same across the dry-run and the '
'enforcement mode configurations. When a particular field is '
'completely empty, it will not be displayed.\n\nNote: When this '
'command is executed on a Service Perimeter with no explicit dry-run '
'mode configuration, the effective dry-run mode configuration is '
'inherited from the enforcement mode configuration, and thus, the '
'enforcement mode configuration is displayed in such cases.'),
'EXAMPLES': ("""\
To display the dry-run mode configuration for a Service Perimeter:
$ {command} my-perimeter
Sample output:
===
name: my_perimeter
title: My Perimeter
type: PERIMETER_TYPE_REGULAR
resources:
+ projects/123
- projects/456
projects/789
restrictedServices:
+ bigquery.googleapis.com
- storage.googleapis.com
bigtable.googleapis.com
vpcAccessibleServices:
+ allowedServices:
+ bigquery.googleapis.com
- storage.googleapis.com
+ enableRestriction: true
""")
}
DescribePerimeterDryRunAlpha.detailed_help = detailed_help
DescribePerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,68 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run drop` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class DropPerimeterDryRun(base.UpdateCommand):
"""Resets the dry-run state of a Service Perimeter."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
perimeters.AddResourceArg(parser, 'to reset')
parser.add_argument(
'--async',
action='store_true',
help="""Return immediately, without waiting for the operation in
progress to complete.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
policies.ValidateAccessPolicyArg(perimeter_ref, args)
return client.UnsetSpec(perimeter_ref, use_explicit_dry_run_spec=False)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DropPerimeterDryRunAlpha(DropPerimeterDryRun):
"""Resets the dry-run mode configuration of a Service Perimeter."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief':
'Reset the dry-run mode configuration of a Service Perimeter.',
'DESCRIPTION':
('Removes the explicit dry-run mode configuration for a Service '
'Perimeter. After this operation, the effective dry-run mode '
'configuration is implicitly inherited from the enforcement mode '
'configuration. No audit logs will be generated in this state.'),
'EXAMPLES':
('To reset the dry-run mode configuration for a Service Perimeter:\n\n'
' $ {command} my-perimeter')
}
DropPerimeterDryRunAlpha.detailed_help = detailed_help
DropPerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,75 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run enforce` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class EnforcePerimeterDryRun(base.UpdateCommand):
"""Enforces a Service Perimeter's dry-run configuration."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
perimeters.AddResourceArg(parser, 'to reset')
parser.add_argument(
'--async',
action='store_true',
help="""Return immediately, without waiting for the operation in
progress to complete.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
policies.ValidateAccessPolicyArg(perimeter_ref, args)
return client.EnforceDryRunConfig(perimeter_ref)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class EnforcePerimeterDryRunAlpha(EnforcePerimeterDryRun):
"""Enforces a Service Perimeter's dry-run configuration."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief':
'Enforces a Service Perimeter\'s dry-run configuration.',
'DESCRIPTION':
"""\
Copies a Service Perimeter\'s dry-run mode configuration to its
enforcement mode configuration and unsets the explicit dry-run spec.
After this operation succeeds, the Service Perimeter will not have
an explicit dry-run mode configuration, and, instead, the previous
dry-run mode configuration will become the enforcement mode
configuration. The operation will not be performed if there is no
explicit dry-run mode configuration or if the dry-run mode
configuration is incompatible with the overall enforcement mode VPC
Service Controls policy.""",
'EXAMPLES':
"""\
To enforce the dry-run mode configuration for a Service Perimeter:\n\n
$ {command} my-perimeter"""
}
EnforcePerimeterDryRunAlpha.detailed_help = detailed_help
EnforcePerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,91 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run enforce-all` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class EnforceAllPerimeterDryRun(base.UpdateCommand):
"""Enforces the dry-run mode configuration for all Service Perimeters."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
parser.add_argument(
'--policy',
metavar='policy',
default=None,
help="""The parent Access Policy which owns all Service Perimeters in
scope for the commit operation.""")
parser.add_argument(
'--etag',
metavar='etag',
default=None,
help="""The etag for the version of the Access Policy that this
operation is to be performed on. If, at the time of the
operation, the etag for the Access Policy stored in Access
Context Manager is different from the specified etag, then the
commit operation will not be performed and the call will fail.
If etag is not provided, the operation will be performed as if a
valid etag is provided.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
policy_id = policies.GetDefaultPolicy()
if args.IsSpecified('policy'):
policy_id = args.policy
policy_ref = resources.REGISTRY.Parse(
policy_id, collection='accesscontextmanager.accessPolicies')
return client.Commit(policy_ref, args.etag)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class EnforceAllPerimeterDryRunAlpha(EnforceAllPerimeterDryRun):
"""Enforces the dry-run mode configuration for all Service Perimeters."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief':
'Enforces the dry-run mode configuration for all Service Perimeters.',
'DESCRIPTION':
('An enforce operation on a Service Perimeter involves copying its '
'dry-run mode configuration (`spec`) to that Service Perimeter\'s '
'enforcement mode configration (`status`). This command performs this '
'operation for *all* Service Perimeters in the user\'s Access '
'Policy.\n\nNote: Only Service Perimeters with an explicit dry-run '
'mode configuration are affected by this operation. The overall '
'operation succeeds once the dry-run configurations of all such '
'Service Perimeters have been enforced. If the operation fails for '
'any given Service Perimeter, it will cause the entire operation to'
' be aborted.'),
'EXAMPLES':
('To enforce the dry-run mode configurations for all Service Perimeter '
'in an Access Policy, run the following command:\n\n'
' $ {command}')
}
EnforceAllPerimeterDryRunAlpha.detailed_help = detailed_help
EnforceAllPerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,99 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run list` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.core import resources
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class ListPerimeterDryRun(base.ListCommand):
"""Lists the effective dry-run configuration across all Service Perimeters."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
base.URI_FLAG.RemoveFromParser(parser)
parser.add_argument(
'--policy',
metavar='policy',
default=None,
help="""Policy resource - The access policy you want to list the
effective dry-run configuration for. This represents a Cloud
resource.""")
parser.display_info.AddFormat('yaml(name.basename(), title, spec)')
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
policy_id = policies.GetDefaultPolicy()
if args.IsSpecified('policy'):
policy_id = args.policy
policy_ref = resources.REGISTRY.Parse(
policy_id, collection='accesscontextmanager.accessPolicies')
perimeters_to_display = [p for p in client.List(policy_ref)]
for p in perimeters_to_display:
# When a Service Perimeter has use_explicit_dry_run_spec set to false, the
# dry-run spec is implicitly the same as the status. In order to clearly
# show the user what exactly is being used as the dry-run spec, we set
# status to None (this list command is only for the dry-run config) and
# copy over the status to the spec when the spec is absent. We also append
# an asterisk to the name to signify that these perimeters are not
# actually identical to what the API returns.
if not p.useExplicitDryRunSpec:
p.spec = p.status
p.name += '*'
p.status = None
print('Note: Perimeters marked with \'*\' do not have an explicit `spec`. '
'Instead, their `status` also acts as the `spec`.')
return perimeters_to_display
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListPerimeterDryRunAlpha(ListPerimeterDryRun):
"""Lists the effective dry-run configuration across all Service Perimeters."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief': ('List the effective dry-run configuration across all Service '
'Perimeters.'),
'DESCRIPTION':
('By default, only the Service Perimeter name, title, type and the '
'dry-run mode configuration (as `spec`) is displayed.\n\nNote: For '
'Service Perimeters without an explicit dry-run mode configuration, '
'the enforcement mode configuration is used as the dry-run mode '
'configuration, resulting in no audit logs being generated.'),
'EXAMPLES':
('To list the dry-run mode configuration across all Service '
'Perimeter:\n\n $ {command}\n\nOutput:\n\n name: perimeter_1*\n '
'spec:\n resources:\n - projects/123\n - projects/456\n '
'restrictedServices:\n - storage.googleapis.com\n title: Perimeter'
' 1\n ---\n name: perimeter_2\n spec:\n resources:\n - '
'projects/789\n restrictedServices:\n - '
'bigquery.googleapis.com\n vpcAccessibleServices:\n '
'allowedServices:\n - bigquery.googleapis.com\n '
'enableRestriction: true\n title: Perimeter 2')
}
ListPerimeterDryRunAlpha.detailed_help = detailed_help
ListPerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,255 @@
# -*- 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.
"""`gcloud access-context-manager perimeters dry-run update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import util
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.command_lib.util.args import repeated
def _GetBaseConfig(perimeter):
"""Returns the base config to use for the update operation."""
if perimeter.useExplicitDryRunSpec:
return perimeter.spec
return perimeter.status
def _GetRepeatedFieldValue(args, field_name, base_config_value, has_spec):
"""Returns the repeated field value to use for the update operation."""
repeated_field = repeated.ParsePrimitiveArgs(args, field_name,
lambda: base_config_value or [])
# If there is no difference between base_config_value and command line input,
# AND there is no spec, then send the list of existing values from
# base_config_value for update operation. This is due to edge case of existing
# status, but no existing spec. base_config_value will be values in status in
# this case, and if the input is the same as what is set in status config,
# then an empty list will be given as the value for the corresponding field
# when creating the spec (which is incorrect).
if not has_spec and not repeated_field:
repeated_field = base_config_value
return repeated_field
def _IsFieldSpecified(field_name, args):
# We leave out the deprecated 'set' arg
list_command_prefixes = ['remove_', 'add_', 'clear_']
list_args = [command + field_name for command in list_command_prefixes]
return any(args.IsSpecified(arg) for arg in list_args)
def _GetIngressEgressFieldValue(args, field_name, base_config_value, has_spec):
"""Returns the ingress/egress field value to use for the update operation."""
ingress_egress_field = perimeters.ParseUpdateDirectionalPoliciesArgs(
args, field_name
)
# If there's currently no dry run spec and no input for ingress/egress rules
# we will inherit the existing ingress/egress rules from status/base config.
if not has_spec and ingress_egress_field is None:
ingress_egress_field = base_config_value
# At this point, there's either spec present or ingress/egress rules present,
# or both are present. If the ingress/egress input is present, we take it to
# update the existing config. If the ingress/egress is empty, then spec must
# be present. In this case, we won't update the spec because the
# ingress_egress_field will be None. None gets skipped for updates.
return ingress_egress_field
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class UpdatePerimeterDryRun(base.UpdateCommand):
"""Updates the dry-run mode configuration for a Service Perimeter."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
UpdatePerimeterDryRun.ArgsVersioned(parser, version='v1')
@staticmethod
def ArgsVersioned(parser, version='v1'):
perimeters.AddResourceArg(parser, 'to update')
perimeters.AddUpdateDirectionalPoliciesGroupArgs(parser, version)
perimeters.AddEtagArg(parser)
repeated.AddPrimitiveArgs(
parser,
'Service Perimeter',
'resources',
'Resources',
include_set=False)
repeated.AddPrimitiveArgs(
parser,
'Service Perimeter',
'restricted-services',
'Restricted Services',
include_set=False)
repeated.AddPrimitiveArgs(
parser,
'Service Perimeter',
'access-levels',
'Access Level',
include_set=False)
if version != 'v1alpha':
vpc_group = parser.add_argument_group(
'Arguments for configuring VPC accessible service restrictions.')
vpc_group.add_argument(
'--enable-vpc-accessible-services',
action='store_true',
help="""When specified restrict API calls within the Service Perimeter to the
set of vpc allowed services. To disable use
'--no-enable-vpc-accessible-services'.""")
repeated.AddPrimitiveArgs(
vpc_group,
'Service Perimeter',
'vpc-allowed-services',
'VPC Allowed Services',
include_set=False)
else:
perimeters.AddUpdateVpcAccessibleServicesGroupArgs(
parser, version
)
parser.add_argument(
'--async',
action='store_true',
help="""Return immediately, without waiting for the operation in
progress to complete.""")
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
messages = util.GetMessages(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
policies.ValidateAccessPolicyArg(perimeter_ref, args)
original_perimeter = client.Get(perimeter_ref)
base_config = _GetBaseConfig(original_perimeter)
if _IsFieldSpecified('resources', args):
updated_resources = _GetRepeatedFieldValue(
args, 'resources', base_config.resources,
original_perimeter.useExplicitDryRunSpec)
else:
updated_resources = base_config.resources
if _IsFieldSpecified('restricted_services', args):
updated_restricted_services = _GetRepeatedFieldValue(
args, 'restricted_services', base_config.restrictedServices,
original_perimeter.useExplicitDryRunSpec)
else:
updated_restricted_services = base_config.restrictedServices
if _IsFieldSpecified('access_levels', args):
updated_access_levels = _GetRepeatedFieldValue(
args, 'access_levels', base_config.accessLevels,
original_perimeter.useExplicitDryRunSpec)
else:
updated_access_levels = base_config.accessLevels
base_vpc_config = base_config.vpcAccessibleServices
if base_vpc_config is None:
base_vpc_config = messages.VpcAccessibleServices()
if _IsFieldSpecified('vpc_allowed_services', args):
updated_vpc_services = _GetRepeatedFieldValue(
args, 'vpc-allowed-services', base_vpc_config.allowedServices,
original_perimeter.useExplicitDryRunSpec)
elif base_config.vpcAccessibleServices is not None:
updated_vpc_services = base_vpc_config.allowedServices
else:
updated_vpc_services = None
if args.IsSpecified('enable_vpc_accessible_services'):
updated_vpc_enabled = args.enable_vpc_accessible_services
elif base_config.vpcAccessibleServices is not None:
updated_vpc_enabled = base_vpc_config.enableRestriction
else:
updated_vpc_enabled = None
# Alpha track: check for the new set/clear flags with YAML.
vpc_accessible_services_config = None
vpc_yaml_flag_used = False
if self._API_VERSION == 'v1alpha':
vpc_accessible_services_config, vpc_yaml_flag_used = (
perimeters.ParseUpdateVpcAccessibleServicesArgs(
args, 'vpc-accessible-services'
)
)
# Vpc allowed services list should only be populated if enable restrictions
# is set to true.
if updated_vpc_enabled is None:
updated_vpc_services = None
elif not updated_vpc_enabled:
updated_vpc_services = []
updated_ingress = _GetIngressEgressFieldValue(
args,
'ingress-policies',
base_config.ingressPolicies,
original_perimeter.useExplicitDryRunSpec,
)
updated_egress = _GetIngressEgressFieldValue(
args,
'egress-policies',
base_config.egressPolicies,
original_perimeter.useExplicitDryRunSpec,
)
return client.PatchDryRunConfig(
perimeter_ref,
resources=updated_resources,
levels=updated_access_levels,
restricted_services=updated_restricted_services,
vpc_allowed_services=updated_vpc_services,
enable_vpc_accessible_services=updated_vpc_enabled,
vpc_yaml_flag_used=vpc_yaml_flag_used,
vpc_accessible_services_config=vpc_accessible_services_config,
ingress_policies=updated_ingress,
egress_policies=updated_egress,
etag=args.etag
)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdatePerimeterDryRunAlpha(UpdatePerimeterDryRun):
"""Updates the dry-run mode configuration for a Service Perimeter."""
_API_VERSION = 'v1alpha'
@staticmethod
def Args(parser):
UpdatePerimeterDryRun.ArgsVersioned(parser, version='v1alpha')
detailed_help = {
'brief':
'Update the dry-run mode configuration for a Service Perimeter.',
'DESCRIPTION':
('This command updates the dry-run mode configuration (`spec`) for a '
'Service Perimeter.\n\nFor Service Perimeters with an explicitly '
'defined dry-run mode configuration (i.e. an explicit `spec`), this '
'operation updates that configuration directly, ignoring enforcement '
'mode configuration.\n\nService Perimeters that do not have explict '
'dry-run mode configuration will inherit the enforcement mode '
'configuration in the dry-run mode. Therefore, this command '
'effectively clones the enforcement mode configuration, then applies '
'the update on that configuration, and uses that as the explicit '
'dry-run mode configuration.'),
'EXAMPLES':
('To update the dry-run mode configuration for a Service Perimeter:\n\n'
' $ {command} my-perimeter '
'--add-resources="projects/123,projects/456" '
'--remove-restricted-services="storage.googleapis.com" '
'--add-access-levels="accessPolicies/123/accessLevels/a_level" '
'--enable-vpc-accessible-services '
'--clear-vpc-allowed-services')
}
UpdatePerimeterDryRunAlpha.detailed_help = detailed_help
UpdatePerimeterDryRun.detailed_help = detailed_help

View File

@@ -0,0 +1,28 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: List service perimeters.
description: List all service access zones in an access policy object.
request:
collection: accesscontextmanager.accessPolicies.servicePerimeters
modify_request_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.policies:ValidateAccessPolicyArg
api_version: v1
ALPHA:
api_version: v1alpha
BETA:
api_version: v1
arguments:
resource:
help_text: The access policy you want to list the service perimeters for.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
output:
format: |
table(
name.basename(),
title,
etag
)

View File

@@ -0,0 +1,91 @@
- release_tracks: [ALPHA, BETA, GA]
command_type: GENERIC
help_text:
brief: |
Replace all existing service perimeters.
description: |
Replace all existing service perimeter in specified access policy with service perimeters
specified in a file.
## EXAMPLES
To replace all perimeters within a policy, using etag:
$ {command} my-policy-number --source-file=path-to-file-containing-all-replacement-service-perimeters.yaml --etag=optional-latest-etag-of-policy
To replace all perimeters within a policy, without using etag:
$ {command} my-policy-number --source-file=path-to-file-containing-all-replacement-service-perimeters.yaml
request:
collection: accesscontextmanager.accessPolicies.servicePerimeters
ALPHA:
api_version: v1alpha
method: replaceAll
BETA:
api_version: v1
method: replaceAll
GA:
api_version: v1
method: replaceAll
response:
ALPHA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseReplaceServicePerimetersResponseAlpha
BETA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseReplaceServicePerimetersResponseGA
GA:
modify_response_hooks:
- googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseReplaceServicePerimetersResponseGA
arguments:
resource:
help_text: The access policy that contains the perimeters you want to replace.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
override_resource_collection: true
params:
- api_field: replaceServicePerimetersRequest.etag
arg_name: etag
required: false
help_text: |
An etag which specifies the version of the Access Policy. Only etags
that represent the latest version of the Access Policy will be accepted.
repeated: false
- api_field: replaceServicePerimetersRequest.servicePerimeters
arg_name: source-file
required: true
help_text: |
Path to a file containing a list of service perimeters.
An service perimeter file is a YAML-formatted list of service perimeters,
which are YAML objects representing a Condition as described in
the API reference. For example:
```
- name: my_perimeter
title: My Perimeter
description: Perimeter for foo.
perimeterType: PERIMETER_TYPE_REGULAR
status:
resources:
- projects/0123456789
accessLevels:
- accessPolicies/my_policy/accessLevels/my_level
restrictedServices:
- storage.googleapis.com
```
For more information about the alpha version, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1alpha/accessPolicies.servicePerimeters
For other versions, see:
https://cloud.google.com/access-context-manager/docs/reference/rest/v1/accessPolicies.servicePerimeters
repeated: false
ALPHA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseServicePerimetersAlpha
BETA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseServicePerimetersGA
GA:
processor: googlecloudsdk.command_lib.accesscontextmanager.perimeters:ParseServicePerimetersGA

View File

@@ -0,0 +1,132 @@
# -*- 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.
"""`gcloud access-context-manager zones update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import zones as zones_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import perimeters
from googlecloudsdk.command_lib.accesscontextmanager import policies
from googlecloudsdk.command_lib.util.args import repeated
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.GA)
class UpdatePerimetersGA(base.UpdateCommand):
"""Update an existing access zone."""
_INCLUDE_UNRESTRICTED = False
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
UpdatePerimetersGA.ArgsVersioned(parser, version='v1')
@staticmethod
def ArgsVersioned(parser, version='v1'):
perimeters.AddResourceArg(parser, 'to update')
perimeters.AddPerimeterUpdateArgs(parser, version=version)
def Run(self, args):
client = zones_api.Client(version=self._API_VERSION)
perimeter_ref = args.CONCEPTS.perimeter.Parse()
result = repeated.CachedResult.FromFunc(client.Get, perimeter_ref)
policies.ValidateAccessPolicyArg(perimeter_ref, args)
vpc_accessible_services_config = None
vpc_yaml_flag_used = False
if self._API_VERSION == 'v1alpha':
vpc_accessible_services_config, vpc_yaml_flag_used = (
perimeters.ParseUpdateVpcAccessibleServicesArgs(
args, 'vpc-accessible-services'
)
)
return self.Patch(
client=client,
args=args,
result=result,
perimeter_ref=perimeter_ref,
description=args.description,
title=args.title,
perimeter_type=perimeters.GetTypeEnumMapper(
version=self._API_VERSION).GetEnumForChoice(args.type),
resources=perimeters.ParseResources(args, result),
restricted_services=perimeters.ParseRestrictedServices(args, result),
levels=perimeters.ParseLevels(args, result,
perimeter_ref.accessPoliciesId),
vpc_allowed_services=perimeters.ParseVpcRestriction(
args, result, self._API_VERSION),
enable_vpc_accessible_services=args.enable_vpc_accessible_services,
vpc_yaml_flag_used=vpc_yaml_flag_used,
vpc_accessible_services_config=vpc_accessible_services_config,
ingress_policies=perimeters.ParseUpdateDirectionalPoliciesArgs(
args, 'ingress-policies'),
egress_policies=perimeters.ParseUpdateDirectionalPoliciesArgs(
args, 'egress-policies'),
etag=args.etag)
def Patch(self, client, args, result, perimeter_ref, description, title,
perimeter_type, resources, restricted_services, levels,
vpc_allowed_services, enable_vpc_accessible_services,
vpc_yaml_flag_used, vpc_accessible_services_config,
ingress_policies, egress_policies, etag):
return client.Patch(
perimeter_ref,
description=description,
title=title,
perimeter_type=perimeter_type,
resources=resources,
restricted_services=restricted_services,
levels=levels,
vpc_allowed_services=vpc_allowed_services,
enable_vpc_accessible_services=enable_vpc_accessible_services,
vpc_yaml_flag_used=vpc_yaml_flag_used,
vpc_accessible_services_config=vpc_accessible_services_config,
ingress_policies=ingress_policies,
egress_policies=egress_policies,
etag=etag)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdatePerimetersAlpha(UpdatePerimetersGA):
"""Update an existing access zone."""
_INCLUDE_UNRESTRICTED = False
_API_VERSION = 'v1alpha'
@staticmethod
def Args(parser):
UpdatePerimetersGA.ArgsVersioned(parser, version='v1alpha')
detailed_help = {
'brief':
'Update the enforced configuration for an existing Service Perimeter.',
'DESCRIPTION':
('This command updates the enforced configuration (`status`) of a '
'Service Perimeter.'),
'EXAMPLES':
('To update the enforced configuration for a Service Perimeter:\n\n'
' $ {command} my-perimeter '
'--add-resources="projects/123,projects/456" '
'--remove-restricted-services="storage.googleapis.com" '
'--add-access-levels="accessPolicies/123/accessLevels/a_level" '
'--enable-vpc-accessible-services '
'--clear-vpc-allowed-services')
}
UpdatePerimetersGA.detailed_help = detailed_help
UpdatePerimetersAlpha.detailed_help = detailed_help

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.
"""The policy command group for the Access Context Manager CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class AccessContextManager(base.Group):
"""Manage Access Context Manager policies.
An access policy is a container for access levels and access zones.
"""

View File

@@ -0,0 +1,36 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Add IAM policy binding for an access policy.
description: |
Adds a policy binding to the IAM policy of an access policy. The binding consists of a role,
identity, and access policy.
examples: |
To add an IAM policy binding for the role of ``roles/notebooks.admin'' for the user 'test-user@gmail.com'
on the access policy 'accessPolicies/123', run:
$ {command} --member='user:test-user@gmail.com' --role='roles/notebooks.admin' accessPolicies/123
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: accesscontextmanager.accessPolicies
use_relative_name: true
ALPHA:
api_version: v1alpha
method: setIamPolicy
BETA:
api_version: v1
method: setIamPolicy
GA:
api_version: v1
method: setIamPolicy
arguments:
resource:
help_text: The access policy to add the IAM binding.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: getIamPolicyRequest.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 Access Context Manager access policy 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 Access Context Manager access policy configurations."""

View File

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

View File

@@ -0,0 +1,67 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Create a new access policy.
description: |
Create a new Access Context Manager policy. An Access Context Manager policy, also known as
an access policy, is a container for access levels and VPC Service Controls service
perimeters.
You can optionally specify either a folder or a project as a scope of an access policy. A
scoped policy only allows projects under that scope to be restricted by any service perimeters
defined with that policy. The scope must be within the organization that this policy is
associated with. You can specify only one folder or project as the scope for an access
policy. If you don't specify a scope, then the scope extends to the entire organization and
any projects within the organization can be added to service perimeters in this policy.
This command only creates an access policy. Access levels and service perimeters need to be
created explicitly.
examples: |
To create an access policy that applies to the entire organization, run:
$ {command} --organization=organizations/123 --title="My Policy"
To create an access policy that applies to the folder with the ID 345, run:
$ {command} --organization=organizations/123 --scopes=folders/345 \
--title="My Folder Policy"
Only projects within this folder can be added to service perimeters within this policy.
To create an access policy that applies only to the project with the project number 567, run:
$ {command} --organization=organizations/123 --scopes=projects/567 \
--title="My Project Policy"
request:
collection: accesscontextmanager.accessPolicies
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
async:
collection: accesscontextmanager.operations
result_attribute: response
extract_resource_result: false
arguments:
params:
- api_field: title
arg_name: title
required: true
help_text: Short human-readable title of the access policy.
- api_field: parent
arg_name: organization
required: true
type: googlecloudsdk.command_lib.util.hooks.types:Resource:collection=cloudresourcemanager.organizations
processor: googlecloudsdk.command_lib.util.hooks.processors:RelativeName
help_text: Parent organization for the access policies.
- api_field: scopes
arg_name: scopes
required: false
help_text: |
Folder or project on which this policy is applicable. You can specify only one folder or
project as the scope and the scope must exist within the specified organization. If you
don't specify a scope, the policy applies to the entire organization.

View File

@@ -0,0 +1,18 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Delete an access policy.
description: Delete a given access policy.
request:
collection: accesscontextmanager.accessPolicies
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The access policy you want to delete.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy

View File

@@ -0,0 +1,18 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Show details about an access policy.
description: Show details about a given access policy.
request:
collection: accesscontextmanager.accessPolicies
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: The access level you want to show details about.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy

View File

@@ -0,0 +1,33 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Get the IAM policy for an access policy.
description: |
*{command}* Displays the IAM policy associated with an access policy.
If formatted as JSON, the output can be edited and used as
a policy file for *set-iam-policy*. The output includes an "etag"
field identifying the version emitted and allowing detection of
concurrent policy updates; see
$ {parent} set-iam-policy for additional details.
examples: |
To print the IAM policy for a given access policy, run:
$ {command} accessPolicies/1234
request:
collection: accesscontextmanager.accessPolicies
use_relative_name: true
ALPHA:
api_version: v1alpha
method: getIamPolicy
BETA:
api_version: v1
method: getIamPolicy
GA:
api_version: v1
method: getIamPolicy
arguments:
resource:
help_text: The access policy for which to display the IAM policy.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy

View File

@@ -0,0 +1,42 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: List access policies.
description: |
List access policies.
## EXAMPLES
To list access policies, run the following command:
$ {command}
This command prints a list of Access Policies in a tabular form:
NAME ORGANIZATION SCOPE TITLE ETAG
MY_POLICY 12345 projects/123 My Policy 123abcdef
request:
collection: accesscontextmanager.accessPolicies
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
resource_method_params:
parent: '{__relative_name__}'
arguments:
resource:
help_text: The parent organization of the policies you want to list.
spec: !REF googlecloudsdk.command_lib.organizations.resources:organization
output:
format: |
table(
name.basename(),
parent.basename():label=ORGANIZATION,
scopes.flatten(),
title,
etag
)

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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 Access Context Manager access policy configurations."""
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 Quotas(base.Group):
"""Manage Access Context Manager access policy quotas."""

View File

@@ -0,0 +1,174 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""`gcloud access-context-manager policies quotas list` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import dataclasses
from googlecloudsdk.api_lib.accesscontextmanager import levels as levels_api
from googlecloudsdk.api_lib.accesscontextmanager import zones as perimeters_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import policies
@dataclasses.dataclass
class Metric:
title: str
usage: int
@base.Hidden
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListPoliciesQuotas(base.ListCommand):
"""Lists the Quota Usage."""
_API_VERSION = 'v1alpha'
def GetPrimetersQuotaUsage(self, perimeters_to_display):
"""Returns service primeters quota usage.
Args:
perimeters_to_display: Response of ListServicePerimeters API
"""
arguments = list(perimeters_to_display)
service_primeters = len(arguments)
protected_resources = 0
ingress_rules = 0
egress_rules = 0
total_ingress_egress_attributes = self.GetTotalIngressEgressAttributes(
arguments
)
for metric in arguments:
configs = []
if metric.status:
configs.append(metric.status)
if metric.spec:
configs.append(metric.spec)
for config in configs:
protected_resources += len(config.resources)
ingress_rules += len(config.ingressPolicies)
egress_rules += len(config.egressPolicies)
return [
Metric('Service primeters', service_primeters),
Metric('Protected resources', protected_resources),
Metric('Ingress rules', ingress_rules),
Metric('Egress rules', egress_rules),
Metric(
'Total ingress/egress attributes', total_ingress_egress_attributes
),
]
def GetLevelsQuotaUsage(self, levels_to_display):
"""Returns levels quota usage, only counts basic access levels.
Args:
levels_to_display: Response of ListAccessLevels API
"""
access_levels = 0
for level in levels_to_display:
if level.basic:
access_levels += 1
return [Metric('Access levels', access_levels)]
def GetTotalIngressEgressAttributes(self, perimeters_to_display):
"""Returns total ingress/egress attributes quota usage.
Args:
perimeters_to_display: Response of ListServicePerimeters API
"""
elements_count = 0
for metric in perimeters_to_display:
configs = []
if metric.status:
configs.append(metric.status)
if metric.spec:
configs.append(metric.spec)
for config in configs:
if config.ingressPolicies:
for ingress_policy in config.ingressPolicies:
elements_count += len(ingress_policy.ingressFrom.sources)
elements_count += len(ingress_policy.ingressFrom.identities)
elements_count += sum(
len(o.methodSelectors)
for o in ingress_policy.ingressTo.operations
)
elements_count += len(ingress_policy.ingressTo.resources)
if config.egressPolicies:
for egress_policy in config.egressPolicies:
elements_count += len(egress_policy.egressFrom.identities)
elements_count += sum(
len(o.methodSelectors)
for o in egress_policy.egressTo.operations
)
elements_count += len(egress_policy.egressTo.resources)
return elements_count
@staticmethod
def Args(parser):
policies.AddResourceArg(parser, 'to list the quota usage')
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat('table(title, usage)')
def Run(self, args):
perimeters_client = perimeters_api.Client(version=self._API_VERSION)
levels_client = levels_api.Client(version=self._API_VERSION)
policy_ref = args.CONCEPTS.policy.Parse()
levels_to_display = levels_client.List(policy_ref)
perimeters_to_display = perimeters_client.List(policy_ref)
primeters_quota_usage = self.GetPrimetersQuotaUsage(perimeters_to_display)
levels_quota_usage = self.GetLevelsQuotaUsage(levels_to_display)
return primeters_quota_usage + levels_quota_usage
detailed_help = {
'brief': (
'List the quota usage of a specific Access Context Manager policy.'
),
'DESCRIPTION': (
'List quota usage of a specific Access Context Manager policy,'
' also known as an access policy. Metrics include: Serivce perimeters,'
' Protected resources, Ingress rules, Egress rules, Access rules and'
' Total ingress/egress attributes. For access levels, this only counts'
' basic access levels.'
),
'EXAMPLES': """
To list the quota usage of a specific Access Context Manager policy:
$ {command} POLICY
Sample output:
===
TITLE USAGE
Service primeters 1
Protected resources 1
Ingress rules 1
Egress rules 1
Total ingress/egress attributes 3
Access levels 1
""",
}
ListPoliciesQuotas.detailed_help = detailed_help

View File

@@ -0,0 +1,35 @@
release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Remove IAM policy binding for an access policy.
description: |
Removes a policy binding to the IAM policy of an access policy, given an access policy ID and the binding.
examples: |
To remove an IAM policy binding for the role of ``roles/editor'' for the user 'test-user@gmail.com'
on the access policy 'accessPolicies/123', run:
$ {command} accessPolicies/123 --member='user:test-user@gmail.com' --role='roles/editor'
See https://cloud.google.com/iam/docs/managing-policies for details of
policy role and member types.
request:
collection: accesscontextmanager.accessPolicies
use_relative_name: true
ALPHA:
api_version: v1alpha
method: setIamPolicy
BETA:
api_version: v1
method: setIamPolicy
GA:
api_version: v1
method: setIamPolicy
arguments:
resource:
help_text: The access policy to remove the IAM binding.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy
iam:
enable_condition: true
policy_version: 3
get_iam_policy_version_path: getIamPolicyRequest.options.requestedPolicyVersion

View File

@@ -0,0 +1,35 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Set IAM policy for an access policy.
description: |
Sets the IAM policy for a access policy, given access policy ID and a file
encoded in JSON or YAML that contains the IAM policy.
examples: |
The following command reads an IAM policy defined in a JSON file
`policy.json` and sets it for the access policy with the ID
`accessPolicies/1234`:
$ {command} accessPolicies/1234 policy.json
See https://cloud.google.com/iam/docs/managing-policies for details of the
policy file format and contents.
request:
collection: accesscontextmanager.accessPolicies
use_relative_name: true
ALPHA:
api_version: v1alpha
method: setIamPolicy
BETA:
api_version: v1
method: setIamPolicy
GA:
api_version: v1
method: setIamPolicy
modify_request_hooks:
- googlecloudsdk.command_lib.iam.hooks:UseMaxRequestedPolicyVersion:api_field=setIamPolicyRequest.policy.version
arguments:
resource:
help_text: The access policy to set the IAM policy for.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:policy

View File

@@ -0,0 +1,52 @@
# -*- 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.
"""`gcloud access-context-manager policies update` command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import policies as policies_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.accesscontextmanager import common
from googlecloudsdk.command_lib.accesscontextmanager import policies
@base.ReleaseTracks(base.ReleaseTrack.GA)
class UpdatePoliciesGA(base.UpdateCommand):
"""Update an existing access policy."""
_API_VERSION = 'v1'
@staticmethod
def Args(parser):
policies.AddResourceArg(parser, 'to update')
common.GetTitleArg('access policy').AddToParser(parser)
def Run(self, args):
client = policies_api.Client(version=self._API_VERSION)
policy_ref = args.CONCEPTS.policy.Parse()
return client.Patch(policy_ref, title=args.title)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class UpdatePoliciesAlpha(UpdatePoliciesGA):
_API_VERSION = 'v1alpha'
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class UpdatePoliciesBeta(UpdatePoliciesGA):
_API_VERSION = 'v1'

View File

@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The command group for the Access Context Manager supported-permissions CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.Hidden
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class SupportedPermissions(base.Group):
"""Retrieve VPC Service Controls Supported Permissions.
The {command} command group lets you list VPC Service Controls supported
permissions. It also lets you describe which permissions in a provided role
are supported by VPC Service Controls.
## EXAMPLES
To see all VPC Service Controls supported permissions:
$ {command} list
To see which permissions in a provided role are supported by VPC Service
Controls:
$ {command} describe roles/example.role.name
"""

View File

@@ -0,0 +1,147 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""permissions describe command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import dataclasses
from googlecloudsdk.api_lib.accesscontextmanager import supported_permissions
from googlecloudsdk.api_lib.iam import util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import flags
from googlecloudsdk.command_lib.iam import iam_util
@dataclasses.dataclass
class SupportedPermission:
role_name: str
support_status: str
supported_permissions: str
def __eq__(self, other: 'SupportedPermission') -> bool:
return (
self.role_name == other.role_name
and self.support_status == other.support_status
and self.supported_permissions == other.supported_permissions
)
@base.Hidden
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DescribeSupportedPermissions(base.DescribeCommand):
"""Describes which permissions in a provided role are supported by [VPC Service Controls]."""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief': (
'Describes which permissions in a provided role are supported by VPC'
' Service Controls'
),
'DESCRIPTION': (
'Describes which permissions in a provided role are supported by VPC'
' Service Controls.'
),
'EXAMPLES': """\
To describe which permissions VPC Service Controls supports for a provided role, run:
$ {command} roles/example.role.name
This command prints out a list of all supported permissions in a tabular form:
ROLE NAME SUPPORT STATUS SUPPORTED PERMISSIONS
roles/example.role.name SUPPORTED example.permission.one
example.permission.two
To describe which permissions VPC Service Controls supports for a custom role, run:
$ {command} TestCustomRole --project=example-project
NOTE: If the provided role is a custom role, an organization or project must be specified.
This command prints out a list of all supported permissions in a tabular form:
ROLE NAME SUPPORT STATUS SUPPORTED PERMISSIONS
projects/example-project/roles/TestCustomRole SUPPORTED example.permission.one
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
flags.AddParentFlags(parser, 'describe', required=False)
flags.GetRoleFlag('describe').AddToParser(parser)
parser.display_info.AddFormat(
'table(role_name, support_status, supported_permissions)'
)
def Run(self, args):
"""Run 'access-context-manager supported-permissions describe ROLE'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
An object of type SupportedPermission describing which permissions in the
role are supported by VPC Service Controls.
"""
# Get the role from IAM to understand which permissions are included in it.
role_name = iam_util.GetRoleName(args.organization, args.project, args.role)
iam_client, iam_messages = util.GetClientAndMessages()
res = iam_client.organizations_roles.Get(
iam_messages.IamOrganizationsRolesGetRequest(
name=role_name,
)
)
iam_permissions_set = set(res.includedPermissions)
# Get the supported permissions from ACM.
acm_client = supported_permissions.Client(version=self._API_VERSION)
# iterate through the supported permissions in ACM and find the ones that
# are in the role.
role_permissions_supported_by_acm = []
for acm_supported_permission in acm_client.List(page_size=100, limit=None):
if acm_supported_permission in iam_permissions_set:
role_permissions_supported_by_acm.append(acm_supported_permission)
if len(role_permissions_supported_by_acm) == len(iam_permissions_set):
break
if len(role_permissions_supported_by_acm) == len(iam_permissions_set):
support_status = 'SUPPORTED'
elif role_permissions_supported_by_acm:
support_status = 'PARTIALLY_SUPPORTED'
else:
support_status = 'NOT_SUPPORTED'
return [
SupportedPermission(
role_name,
support_status,
'\n'.join(role_permissions_supported_by_acm),
)
]

View File

@@ -0,0 +1,82 @@
# -*- coding: utf-8 -*- #
# Copyright 2025 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""permissions list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import supported_permissions
from googlecloudsdk.calliope import base
@base.Hidden
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListSupportedPermissions(base.ListCommand):
"""Lists all [VPC Service Controls supported permissions].
Lists the permissions that VPC Service Controls supports.
"""
_API_VERSION = 'v1alpha'
detailed_help = {
'brief': 'Lists all VPC Service Controls supported permissions',
'DESCRIPTION': (
'Lists the permissions that VPC Service Controls supports.'
),
'EXAMPLES': """\
To list VPC Service Controls supported permissions, run:
$ {command}
This command prints out a list of all supported permissions in a tabular form:
PERMISSION
example.permission.one
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat(
'table(.:label=PERMISSION:sort=1)'
)
def Run(self, args):
"""Run 'access-context-manager supported-permissions list'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
The list of VPC Service Controls supported permissions.
"""
client = supported_permissions.Client(version=self._API_VERSION)
return client.List(args.page_size, args.limit)

View File

@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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 the Access Context Manager supported-services CLI."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(
base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA
)
class SupportedServices(base.Group):
"""Retrieve VPC Service Controls Supported Services.
The {command} command group lets you list VPC Service Controls supported
services and its properties.
## EXAMPLES
To see all VPC Service Controls supported services:
$ {command} list
To see support information about VPC Service Controls supported services:
$ {command} describe SERVICE_NAME
"""

View File

@@ -0,0 +1,26 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: Gets information about a VPC Service Controls Supported Service.
description: Get service information allowed in an access policy object.
examples: |
To get VPC Service Controls support information for `bigquery.googleapis.com`, run:
$ {command} bigquery.googleapis.com
request:
collection: accesscontextmanager.services
method: get
api_version: v1
BETA:
api_version: v1
ALPHA:
api_version: v1alpha
arguments:
resource:
help_text: VPC Service Controls supported service.
spec: !REF googlecloudsdk.command_lib.accesscontextmanager.resources:supported-service
output:
format: |
yaml(availableOnRestrictedVip,knownLimitations,name,serviceSupportStage,supportedMethods)

View File

@@ -0,0 +1,113 @@
# -*- coding: utf-8 -*- #
# Copyright 2023 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.
"""services list command."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.accesscontextmanager import supported_services
from googlecloudsdk.calliope import base
@base.UniverseCompatible
@base.ReleaseTracks(base.ReleaseTrack.GA)
class ListGA(base.ListCommand):
"""Lists all [VPC Service Controls supported services].
Lists the services that VPC Service Controls supports. The services that are
in this list either fully support VPC Service Controls or the
integration of this service with VPC Service Controls is in
[Preview stage](https://cloud.google.com/products#product-launch-stages).
Services that aren't in this list don't support VPC Service Controls and
aren't guaranteed to function properly in a VPC Service Controls
environment.
"""
_API_VERSION = 'v1'
detailed_help = {
'brief': 'Lists all VPC Service Controls supported services',
'DESCRIPTION': (
'Lists the services that VPC Service Controls supports. The services'
' that are in this list fully support VPC Service Controls or'
' the integration of this service with VPC Service Controls is in'
' [Preview'
' stage](https://cloud.google.com/products#product-launch-stages),'
' or the service integration is scheduled to be shut down and removed'
' which is in [Deprecation stage]'
' (https://cloud.google.com/products#product-launch-stages).'
" Services that aren't in this list don't support VPC Service"
" Controls and aren't guaranteed to function properly in a VPC"
' Service Controls environment.'
),
'EXAMPLES': """\
To list VPC Service Controls supported services, run:
$ {command}
This command prints out a list of all supported services in a tabular form:
NAME TITLE SERVICE_SUPPORT_STAGE AVAILABLE_ON_RESTRICTED_VIP KNOWN_LIMITATIONS
vpcsc_supported_service VPC-SC Supported API GA True False
""",
}
@staticmethod
def Args(parser):
"""Args is called by calliope to gather arguments for this command.
Args:
parser: An argparse parser that you can use to add arguments that go on
the command line after this command. Positional arguments are allowed.
"""
# Remove unneeded list-related flags from parser
base.URI_FLAG.RemoveFromParser(parser)
parser.display_info.AddFormat("""
table(
name:label=NAME:sort=1,
title:label=TITLE,
serviceSupportStage:label=SERVICE_SUPPORT_STAGE,
availableOnRestrictedVip.yesno(no=False):label=AVAILABLE_ON_RESTRICTED_VIP,
known_limitations.yesno(no=False):label=KNOWN_LIMITATIONS
)
""")
def Run(self, args):
"""Run 'access-context-manager supported-services list'.
Args:
args: argparse.Namespace, The arguments that this command was invoked
with.
Returns:
The list of VPC Service Controls supportes services.
"""
client = supported_services.Client(version=self._API_VERSION)
return client.List(args.page_size, args.limit)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class ListBeta(ListGA):
_API_VERSION = 'v1'
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class ListAlpha(ListBeta):
_API_VERSION = 'v1alpha'

View File

@@ -0,0 +1,35 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google Inc. 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 Managed Microsoft AD."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA,
base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class ActiveDirectory(base.Group):
"""Manage Managed Microsoft AD resources."""
category = base.IDENTITY_CATEGORY
def Filter(self, context, args):
# TODO(b/190523114): Determine if command group works with project number
base.RequireProjectID(args)
del context, args

View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google Inc. 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 Managed Microsoft AD domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA,
base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Domains(base.Group):
"""Manage Managed Microsoft AD domains."""

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2021 Google Inc. 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 Managed Microsoft AD backups."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.GA,
base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class Backups(base.Group):
"""Managed Microsoft AD Backups."""

View File

@@ -0,0 +1,52 @@
- release_tracks: [GA, ALPHA, BETA]
help_text:
brief: |
Create a Managed Microsoft AD domain backup.
description: |
Create a new Managed Microsoft AD domain backup with the specified name using Google Cloud's
Managed Service for Microsoft Active Directory.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified domain is being created.
* A backup already exists with the same target domain name.
* The active account doesn't have permission to access the specified domain.
* The active account doesn't have permission to create AD domain backups.
examples: |
To create an AD domain backup named `my-backup` under domain
`my-domain.com`, run:
$ {command} my-backup --domain=my-domain.com --project=my-proj --async
async:
collection: managedidentities.projects.locations.global.operations
request: &request
collection: managedidentities.projects.locations.global.domains.backups
method: create
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:backup
help_text: |
Name of the Managed Microsoft AD domain backup you want to create.
params:
- arg_name: labels
api_field: backup.labels.additionalProperties
metavar: KEY=VALUE
help_text: |
List of label KEY=VALUE pairs to add.
type:
arg_dict:
flatten: true
spec:
- api_field: key
- api_field: value

View File

@@ -0,0 +1,38 @@
- release_tracks: [GA, ALPHA, BETA]
help_text:
brief: |
Delete a Managed Microsoft AD domain backup.
description: |
Delete a Managed Microsoft AD domain backup with the specified name using Google Cloud's
Managed Service for Microsoft Active Directory.
This command can fail for the following reasons:
* The specified backup doesn't exist.
* The active account doesn't have permission to access the specified domain.
* The active account doesn't have permission to access the specified AD domain backup.
examples: |
To delete an AD domain backup `my-backup` under domain
`projects/my-proj/locations/global/domains/my-domain.com`, run:
$ {command} projects/my-proj/locations/global/domains/my-domain.com/backups/my-backup \
--async
async:
collection: managedidentities.projects.locations.global.operations
request: &request
collection: managedidentities.projects.locations.global.domains.backups
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:backup
help_text: |
Name of the Managed Microsoft AD domain backup you want to delete.

View File

@@ -0,0 +1,35 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Describe a Managed Microsoft AD domain backup.
description: |
Show metadata for a Managed Microsoft AD domain backup.
Displays all metadata associated with an Active Directory domain backup when provided with a
valid domain backup name.
This command can fail for the following reasons:
* The specified domain backup doesn't exist.
* The active account doesn't have permission to access the specified
domain.
examples: |
To display all metadata associated with an AD domain backup with the name
`my-backup` under the domain `my-domain` in project `my-project`, run:
$ {command} projects/my-proj/locations/global/domains/my-domain.com/backups/my-backup
request: &request
collection: managedidentities.projects.locations.global.domains.backups
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:backup
help_text: |
Name of the Managed Microsoft AD domain backup you want to describe.

View File

@@ -0,0 +1,47 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
List all Managed Microsoft AD domain backups.
description: |
List all Managed Microsoft AD domain backups in the specified Managed Microsoft AD domain.
Displays associated Active Directory domain backups.
This command can fail for the following reasons:
* The active account doesn't have permission to access the specified
domain.
examples: |
To list all AD domain backups in the project `my-project` under domain
`my-domain.com`, run:
$ {command} --project=my-project --domain=my-domain.com --limit=5
request: &request
collection: managedidentities.projects.locations.global.domains.backups
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the domain for which you want to list all associated Managed Microsoft AD domain backups.
response:
id_field: name
output:
format: |
table(
name.basename():label=NAME,
backup:label=BACKUP,
state:label=STATE,
type:label=TYPE,
description:label=DESCRIPTION,
createTime.date()
)

View File

@@ -0,0 +1,46 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Update a Managed Microsoft AD domain backup.
description: |
Update a Managed Microsoft AD domain backup.
* The specified backup doesn't exist.
* The active account doesn't have permission to access the specified domain.
* The active account doesn't have permission to access the specified domain backup.
examples: |
To update an AD domain backup `my-backup` under domain
`projects/my-proj/locations/global/domains/my-domain.com` with the labels `l1` and `l2`, run:
$ {command} projects/my-proj/locations/global/domains/my-domain.com/backups/my-backup \
--update-labels=l1=1,l2=2
async:
collection: managedidentities.projects.locations.global.operations
request: &request
collection: managedidentities.projects.locations.global.domains.backups
ALPHA:
api_version: v1alpha1
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.backup_util:UpdatePatchRequest
- googlecloudsdk.command_lib.active_directory.backup_util:UpdateLabels
BETA:
api_version: v1beta1
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.backup_util:UpdatePatchRequest
- googlecloudsdk.command_lib.active_directory.backup_util:UpdateLabels
GA:
api_version: v1
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.backup_util:UpdatePatchRequest
- googlecloudsdk.command_lib.active_directory.backup_util:UpdateLabels
method: patch
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:backup
help_text: |
Name of the Managed Microsoft AD domain backup you want to update.
additional_arguments_hook: googlecloudsdk.command_lib.active_directory.flags:BackupUpdateLabelsFlags

View File

@@ -0,0 +1,100 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: |
Create a Managed Microsoft AD domain.
description: |
Create a new Managed Microsoft AD domain with the given name using Google Cloud's
Managed Service for Microsoft Active Directory.
This command can fail for the following reasons:
* An AD domain with the same name already exists.
* The active account does not have permission to create AD domains.
* There is an overlap between the provided CIDR range and authorized network's CIDR.
* A valid region was not provided.
examples: |
The following command creates an AD domain with the name
`my-domain.com` in region `us-central1`, a network peering to `my-network` and
consuming the IP address range `10.172.0.0/24`.
$ {command} my-domain.com --region=us-central1 --reserved-ip-range="10.172.0.0/24"
--authorized-networks=projects/my-project/global/networks/my-network
async:
collection: managedidentities.projects.locations.global.operations
request: &request
collection: managedidentities.projects.locations.global.domains
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.util:AppendLocationsGlobalToParent
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the managed Managed Microsoft AD domain you want to create.
params:
- arg_name: authorized-networks
api_field: domain.authorizedNetworks
help_text: |
Names of the Google Compute Engine networks to which the domain will be connected.
- arg_name: region
api_field: domain.locations
help_text: |
Google Compute Engine region in which to provision domain controllers.
required: true
- arg_name: admin-name
ALPHA:
api_field: domain.managedIdentitiesAdminName
BETA:
api_field: domain.admin
GA:
api_field: domain.admin
help_text: |
Name of the administrator that may be used to perform Active Directory
operations. This is a delegated administrator account provisioned by our service.
If left unspecified `MIAdmin` will be used. This is different from both the domain
administrator and the Directory Services Restore Mode (DSRM) administrator.
- arg_name: labels
api_field: domain.labels.additionalProperties
metavar: KEY=VALUE
help_text: |
List of label KEY=VALUE pairs to add.
type:
arg_dict:
flatten: true
spec:
- api_field: key
- api_field: value
- arg_name: tags
release_tracks: [GA]
# TODO(b/338531743): Remove hidden as part of GA launch.
hidden: true
api_field: domain.tags.additionalProperties
metavar: KEY=VALUE
help_text: |
List of tag KEY=VALUE pairs to add.
type:
arg_dict:
flatten: true
spec:
- api_field: key
- api_field: value
- arg_name: reserved-ip-range
api_field: domain.reservedIpRange
help_text: |
Classless Inter-Domain Routing range of internal addresses that
are reserved for this domain.
required: true
- arg_name: enable-audit-logs
type: bool
action: store_true
api_field: domain.auditLogsEnabled
help_text: |
If specified, Active Directory data audit logs are enabled for the domain.

View File

@@ -0,0 +1,31 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Delete a managed Microsoft Active Directory domain.
description: |
Delete a managed Microsoft Active Directory (AD) domain with
the given fully-qualified domain name.
This command can fail for the following reasons:
* The AD domain specified does not exist.
* The active account does not have permission to access the given
AD domain.
examples: |
The following command deletes an AD domain with the name
`my-domain.com`.
$ {command} my-domain.com
async:
collection: managedidentities.projects.locations.global.operations
request: &request
api_version: v1
collection: managedidentities.projects.locations.global.domains
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the managed Managed Microsoft AD domain you want to delete.

View File

@@ -0,0 +1,35 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Describe a Managed Microsoft AD domain.
description: |
Show metadata for a Managed Microsoft AD domain.
Displays all metadata associated with a Active Directory domain given a
valid AD domain fully-qualified domain name.
This command can fail for the following reasons:
* The domain specified does not exist.
* The active account does not have permission to access the given
domain.
examples: |
The following command prints metadata for an AD domain with the name
`my-domain.com`.
$ {command} my-domain.com
request: &request
collection: managedidentities.projects.locations.global.domains
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain you want to describe.

View File

@@ -0,0 +1,32 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Describe the LDAPS settings of a Managed Microsoft AD domain.
description: |
Describe the Lightweight Directory Access Protocol over TLS/SSL (LDAPS) settings of a Managed Microsoft AD domain.
This command can fail for the following reasons:
* The domain specified does not exist.
* The active account does not have permission to view LDAPS settings for the domain.
examples: |
The following command shows the LDAPS settings for an AD domain with the name
`my-domain.com`.
$ {command} my-domain.com
request: &request
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
collection: managedidentities.projects.locations.global.domains
method: getLdapssettings
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain you want to describe.

View File

@@ -0,0 +1,51 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: |
Initiate schema extension for a Managed Microsoft AD domain.
description: |
Initiate schema extension for a Managed Microsoft AD domain.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified domain is either being created or updated.
* The specified domain is under maintenance.
* The active account doesn't have permission to initiate schema extension on the specified domain.
examples: |
The following command initiates a schema extension for the domain
`my-domain.com` in project `my-project`, with description `Test Description`,
using the LDIF file `demo.ldif`
$ {command} my-domain.com --description="Test Description" --ldif-file=demo.ldf --project=my-project --async
async:
collection: managedidentities.projects.locations.global.operations
request:
collection: managedidentities.projects.locations.global.domains
method: extendSchema
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
help_text: |
Name of the Managed Microsoft AD domain for which you want to extend schema.
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
params:
- arg_name: description
api_field: extendSchemaRequest.description
required: true
help_text: |
Description of schema change.
- arg_name: ldif-file
type: googlecloudsdk.calliope.arg_parsers:FileContents:binary=True
api_field: extendSchemaRequest.fileContents
required: true
help_text: |
Local LDIF file path that contains commands for schema extension. The file size can't be larger than 1 MB.

View File

@@ -0,0 +1,30 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Describe the IAM policy for a Managed Microsoft AD domain.
description: |
*{command}* displays the IAM policy associated with an Managed Microsoft AD domain.
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.
This command can fail for the following reasons:
* The domain specified does not exist.
* The active account does not have permission to access the given
domain's IAM policies.
examples: |
To print the IAM policy for `my-domain.com`, run:
$ {command} my-domain.com
request: &request
api_version: v1
collection: managedidentities.projects.locations.global.domains
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain that you want to get the IAM policy for.

View File

@@ -0,0 +1,69 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
List Managed Microsoft AD domains.
description: |
List all Managed Microsoft AD domains in the specified project.
You can specify the maximum number of domains to list using the
`--limit` flag.
examples: |
The following command lists a maximum of five domains:
$ {command} --limit=5
request: &request
collection: managedidentities.projects.locations.global.domains
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.util:AppendLocationsGlobalToParent
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:project
help_text: |
The project of the AD domains to display.
output:
ALPHA:
format: |
table(
name.basename():label=DOMAIN_NAME,
state:label=DOMAIN_STATE,
reservedIpRange:label=RESERVED_IP_RANGE,
locations:label=REGIONS,
labels:label=LABELS,
managedIdentitiesAdminName:label=ADMIN_NAME,
auditLogsEnabled:label=AUDIT_LOGS_ENABLED,
createTime.date():sort=1
)
BETA:
format: |
table(
name.basename():label=DOMAIN_NAME,
state:label=DOMAIN_STATE,
reservedIpRange:label=RESERVED_IP_RANGE,
locations:label=REGIONS,
labels:label=LABELS,
admin:label=ADMIN_NAME,
auditLogsEnabled:label=AUDIT_LOGS_ENABLED,
createTime.date():sort=1
)
GA:
format: |
table(
name.basename():label=DOMAIN_NAME,
state:label=DOMAIN_STATE,
reservedIpRange:label=RESERVED_IP_RANGE,
locations:label=REGIONS,
labels:label=LABELS,
admin:label=ADMIN_NAME,
auditLogsEnabled:label=AUDIT_LOGS_ENABLED,
createTime.date():sort=1
)

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2022 Google Inc. 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 Managed Microsoft AD domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class Domains(base.Group):
"""Manage Managed Microsoft AD domains."""

View File

@@ -0,0 +1,31 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: |
Check existing permissions on a Managed Microsoft AD domain for domain migration.
description: |
Check existing permissions on a Managed Microsoft AD domain for domain migration.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified domain is either being created or updated.
* The active account doesn't have permission to check migration permissions on the specified domain.
examples: |
The following command checks migration permissions on the domain
`my-domain.com` in project `my-project`.
$ {command} my-domain.com --project=my-project
request:
collection: managedidentities.projects.locations.global.domains
method: checkMigrationPermission
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
arguments:
resource:
help_text: |
Name of the Managed Microsoft AD domain for which you want to check migration permissions.
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain

View File

@@ -0,0 +1,34 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: |
Disable domain migration permissions on a Managed Microsoft AD domain.
description: |
Disable domain migration permissions on a Managed Microsoft AD domain.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified domain is either being created or updated.
* The active account doesn't have permission to disable migration permissions on the specified domain.
examples: |
The following command disables migration permissions on the domain
`my-domain.com` in project `my-project`.
$ {command} my-domain.com --project=my-project --async
async:
collection: managedidentities.projects.locations.global.operations
request:
collection: managedidentities.projects.locations.global.domains
method: disableMigration
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
arguments:
resource:
help_text: |
Name of the Managed Microsoft AD domain on which you want to disable migration permissions.
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain

View File

@@ -0,0 +1,53 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: |
Enable domain migration permissions on a Managed Microsoft AD domain.
description: |
Enable domain migration permissions on a Managed Microsoft AD domain.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified domain is either being created or updated.
* The active account doesn't have permission to enable migration permissions on the specified domain.
examples: |
The following command enables migration permissions on the domain
`my-domain.com` in project `my-project` for two on-premises domains `onprem-domain-1.com` and
`onprem-domain-2.com`, with SID Filtering disabled for `onprem-domain-1.com`.
$ {command} my-domain.com --onprem-domains=onprem-domain-1.com,onprem-domain-2.com --disable-sid-filtering-domains=onprem-domain-1.com --project=my-project --async
async:
collection: managedidentities.projects.locations.global.operations
request:
collection: managedidentities.projects.locations.global.domains
method: enableMigration
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
modify_request_hooks:
- googlecloudsdk.command_lib.active_directory.migration_util:UpdateOnPremSIDDetails
input:
confirmation_prompt: |
You are about to enable SID History migration permissions
on Managed Microsoft AD domain [{__name__}] in [{projectsId}].
arguments:
resource:
help_text: |
Name of the Managed Microsoft AD domain on which you want to enable migration permissions.
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
params:
- arg_name: onprem-domains
required: true
type: "googlecloudsdk.calliope.arg_parsers:ArgList:"
help_text: |
List of trusted domains that are being migrated.
- arg_name: disable-sid-filtering-domains
type: "googlecloudsdk.calliope.arg_parsers:ArgList:"
help_text: |
List of migrating domains on which SID Filtering must be disabled. The list is empty by default.

View File

@@ -0,0 +1,35 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Reset the admin password for a Managed Microsoft AD domain.
description: |
Reset the delegated admin password for a Managed Microsoft AD domain given a valid AD domain
fully-qualified domain name.
This command can fail for the following reasons:
* The AD domain specified does not exist.
* The active account does not have permission to access the given
AD domain.
examples: |
The following command resets the admin password for an AD domain with
the name `my-domain.com`.
$ {command} my-domain.com
request: &request
collection: managedidentities.projects.locations.global.domains
api_version: v1
method: resetAdminPassword
input:
confirmation_prompt: |
You are about to reset the admin password for Managed Microsoft AD domain [{__name__}]
in [{projectsId}].
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain you want to reset the password for.
command_type: GENERIC

View File

@@ -0,0 +1,43 @@
- release_tracks: [ALPHA, BETA, GA]
help_text:
brief: |
Restore a domain from the specified backup.
description: |
Restore a Managed Microsoft AD domain to a previous point in time when the
backup was taken.
This command can fail for the following reasons:
* The specified domain doesn't exist.
* The specified backup doesn't exist.
* The active account doesn't have permission to restore the specified domain.
examples: |
To restore the domain `my-domain.com` from backup `my-backup`, run:
$ {command} my-domain.com --backup=my-backup --async
async:
collection: managedidentities.projects.locations.global.operations
request:
collection: managedidentities.projects.locations.global.domains
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
GA:
api_version: v1
method: restore
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain you want to restore.
params:
- arg_name: backup
required: true
api_field: restoreDomainRequest.backupId
help_text: |
Name of the domain backup from which you want to restore the Managed Microsoft AD domain.

View File

@@ -0,0 +1,30 @@
- release_tracks: [GA, BETA, ALPHA]
help_text:
brief: |
Set the IAM policy for a Managed Microsoft AD domain.
description: |
Set the IAM policy associated with a Managed Microsoft AD domain.
This command can fail for the following reasons:
* The domain specified does not exist.
* The active account does not have permission to access the given
domain's IAM policies.
examples: |
To set the IAM policy for `my-domain.com`, run:
$ {command} my-domain.com policy.json
See https://cloud.google.com/iam/docs/managing-policies for details of the
policy file format and contents.
request: &request
api_version: v1
collection: managedidentities.projects.locations.global.domains
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:domain
help_text: |
Name of the Managed Microsoft AD domain you want to set the IAM policy for.

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google Inc. 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 Cloud SQL integrations with Managed Microsoft AD domains."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
@base.ReleaseTracks(base.ReleaseTrack.BETA,
base.ReleaseTrack.ALPHA)
class SqlIntegrations(base.Group):
"""Discover Cloud SQL integrations with Managed Microsoft AD domains."""

View File

@@ -0,0 +1,39 @@
- release_tracks: [ALPHA, BETA]
help_text:
brief: |
Describe a Cloud SQL integration against a Managed Microsoft AD domain.
description: |
Describe a Cloud SQL integration against a Managed Microsoft AD domain.
Displays all details of a Cloud SQL integration given a valid integration ID.
examples: |
To describe a Cloud SQL integration with the ID
`my-integration` under the managed AD domain `my-domain`, run:
$ {command} my-integration --domain=my-domain --project=my-project
request:
ALPHA:
api_version: v1alpha1
BETA:
api_version: v1beta1
collection: managedidentities.projects.locations.global.domains.sqlIntegrations
arguments:
resource:
spec: !REF googlecloudsdk.command_lib.active_directory.resources:sql_integration
help_text: |
Arguments and flags that specify the SQL integration you want to describe.
response:
id_field: name
output:
format: |
table(
name.basename():label=NAME,
sqlInstance:label=SQL_INSTANCE,
state:label=STATE,
createTime.date()
)

Some files were not shown because too many files have changed in this diff Show More