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,35 @@
# -*- 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 main command group for Cloud Asset Inventory."""
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 Asset(base.Group):
"""Manage the Cloud Asset Inventory."""
category = base.SECURITY_CATEGORY
def Filter(self, context, args):
# TODO(b/190524367): Determine if command group works with project number
base.RequireProjectID(args)
del context, args

View File

@@ -0,0 +1,94 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to analyze IAM policy in the specified root asset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION': """\
Analyzes IAM policies that match a request.
""",
'EXAMPLES': """\
To find out which users have been granted the
iam.serviceAccounts.actAs permission on a service account, run:
$ {command} --organization=YOUR_ORG_ID --full-resource-name=YOUR_SERVICE_ACCOUNT_FULL_RESOURCE_NAME --permissions='iam.serviceAccounts.actAs'
To find out which resources a user can access, run:
$ {command} --organization=YOUR_ORG_ID --identity='user:u1@foo.com'
To find out which roles or permissions a user has been granted on a
project, run:
$ {command} --organization=YOUR_ORG_ID --full-resource-name=YOUR_PROJECT_FULL_RESOURCE_NAME --identity='user:u1@foo.com'
To find out which users have been granted the
iam.serviceAccounts.actAs permission on any applicable resources, run:
$ {command} --organization=YOUR_ORG_ID --permissions='iam.serviceAccounts.actAs'
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeIamPolicyGA(base.Command):
"""Analyzes IAM policies that match a request."""
detailed_help = DETAILED_HELP
_API_VERSION = client_util.DEFAULT_API_VERSION
@classmethod
def Args(cls, parser):
flags.AddAnalyzerParentArgs(parser)
flags.AddAnalyzerSelectorsGroup(parser)
flags.AddAnalyzerOptionsGroup(parser, True)
flags.AddAnalyzerConditionContextGroup(parser)
flags.AddAnalyzerSavedAnalysisQueryArgs(parser)
def Run(self, args):
client = client_util.AnalyzeIamPolicyClient(self._API_VERSION)
return client.Analyze(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AnalyzeIamPolicyBETA(AnalyzeIamPolicyGA):
"""BETA version, Analyzes IAM policies that match a request."""
@classmethod
def Args(cls, parser):
AnalyzeIamPolicyGA.Args(parser)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AnalyzeIamPolicyALPHA(AnalyzeIamPolicyBETA):
"""ALPHA version, Analyzes IAM policies that match a request."""
@classmethod
def Args(cls, parser):
AnalyzeIamPolicyBETA.Args(parser)
# TODO(b/304841991): Move versioned field to common parsing function after
# version label is removed.
options_group = flags.GetOrAddOptionGroup(parser)
flags.AddAnalyzerIncludeDenyPolicyAnalysisArgs(options_group)

View File

@@ -0,0 +1,106 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to analyze IAM policy asynchronously in the specified root asset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.core import log
OPERATION_DESCRIBE_COMMAND = 'gcloud asset operations describe'
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION': """\
Analyzes IAM policies that match a request asynchronously and writes
the results to Google Cloud Storage or BigQuery destination.
""",
'EXAMPLES': """\
To find out which users have been granted the
iam.serviceAccounts.actAs permission on a service account, and write
analysis results to Google Cloud Storage, run:
$ {command} --organization=YOUR_ORG_ID --full-resource-name=YOUR_SERVICE_ACCOUNT_FULL_RESOURCE_NAME --permissions='iam.serviceAccounts.actAs' --gcs-output-path='gs://YOUR_BUCKET_NAME/YOUR_OBJECT_NAME'
To find out which resources a user can access, and write analysis
results to Google Cloud Storage, run:
$ {command} --organization=YOUR_ORG_ID --identity='user:u1@foo.com' --gcs-output-path='gs://YOUR_BUCKET_NAME/YOUR_OBJECT_NAME'
To find out which roles or permissions a user has been granted on a
project, and write analysis results to BigQuery, run:
$ {command} --organization=YOUR_ORG_ID --full-resource-name=YOUR_PROJECT_FULL_RESOURCE_NAME --identity='user:u1@foo.com' --bigquery-dataset='projects/YOUR_PROJECT_ID/datasets/YOUR_DATASET_ID' --bigquery-table-prefix='YOUR_BIGQUERY_TABLE_PREFIX'
To find out which users have been granted the
iam.serviceAccounts.actAs permission on any applicable resources, and
write analysis results to BigQuery, run:
$ {command} --organization=YOUR_ORG_ID --permissions='iam.serviceAccounts.actAs' --bigquery-dataset='projects/YOUR_PROJECT_ID/datasets/YOUR_DATASET_ID' --bigquery-table-prefix='YOUR_BIGQUERY_TABLE_PREFIX'
""",
}
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeIamPolicyLongrunning(base.Command):
"""Analyzes IAM policies that match a request asynchronously and writes the results to Google Cloud Storage or BigQuery destination."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
flags.AddAnalyzerParentArgs(parser)
flags.AddAnalyzerSelectorsGroup(parser)
flags.AddAnalyzerOptionsGroup(parser, False)
flags.AddAnalyzerConditionContextGroup(parser)
flags.AddDestinationGroup(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForAnalyzeIamPolicy(
args.organization, args.project, args.folder)
client = client_util.IamPolicyAnalysisLongrunningClient()
operation = client.Analyze(parent, args)
log.status.Print('Analyze IAM Policy in progress.')
log.status.Print('Use [{} {}] to check the status of the operation.'.format(
OPERATION_DESCRIBE_COMMAND, operation.name))
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AnalyzeIamPolicyLongrunningBETA(AnalyzeIamPolicyLongrunning):
"""Analyzes IAM policies that match a request asynchronously and writes the results to Google Cloud Storage or BigQuery destination."""
@staticmethod
def Args(parser):
AnalyzeIamPolicyLongrunning.Args(parser)
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AnalyzeIamPolicyLongrunningALPHA(AnalyzeIamPolicyLongrunningBETA):
"""Analyzes IAM policies that match a request asynchronously and writes the results to Google Cloud Storage or BigQuery destination."""
@staticmethod
def Args(parser):
AnalyzeIamPolicyLongrunningBETA.Args(parser)
# TODO(b/304841991): Move versioned field to common parsing function after
# version label is removed.
options_group = flags.GetOrAddOptionGroup(parser)
flags.AddAnalyzerIncludeDenyPolicyAnalysisArgs(options_group)

View File

@@ -0,0 +1,98 @@
# -*- 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 to analyze resource move for a specified asset and destination."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
def AddProjectArgs(parser):
parser.add_argument(
'--project',
metavar='PROJECT_ID',
required=True,
help='The project ID or number to perform the analysis.')
def AddDestinationGroup(parser):
destination_group = parser.add_group(mutex=True, required=True)
AddDestinationOrgArgs(destination_group)
AddDestinationFolderArgs(destination_group)
def AddDestinationOrgArgs(parser):
parser.add_argument(
'--destination-organization',
metavar='ORGANIZATION_ID',
required=False,
help='The destination organization ID to perform the analysis.')
def AddDestinationFolderArgs(parser):
parser.add_argument(
'--destination-folder',
metavar='FOLDER_ID',
required=False,
help='The destination folder ID to perform the analysis.')
def AddBlockersOnlyArgs(parser):
parser.add_argument(
'--blockers-only',
metavar='BLOCKERS_ONLY',
required=False,
default=False,
help='Determines whether to perform analysis against blockers only. '
'Leaving it empty means the full analysis will be performed including '
'warnings and blockers for the specified resource move.')
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeMove(base.Command):
"""Analyzes resource move."""
detailed_help = {
'DESCRIPTION':
"""\
Analyze resource migration from its current resource hierarchy.""",
'EXAMPLES':
"""\
To analyze the impacts of moving a project to a different organization, run:
$ gcloud asset analyze-move --project=YOUR_PROJECT_ID --destination-organization=ORGANIZATION_ID
To analyze the impacts of moving a project to a different folder, run:
$ gcloud asset analyze-move --project=YOUR_PROJECT_ID --destination-folder=FOLDER_ID
To analyze only the blockers of moving a project to a different folder, run:
$ gcloud asset analyze-move --project=YOUR_PROJECT_ID --destination-folder=FOLDER_ID --blockers-only=true
"""
}
@staticmethod
def Args(parser):
AddProjectArgs(parser)
AddDestinationGroup(parser)
AddBlockersOnlyArgs(parser)
def Run(self, args):
client = client_util.AnalyzeMoveClient()
return client.AnalyzeMove(args)

View File

@@ -0,0 +1,125 @@
# -*- 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 AnalyzeOrgPolicies API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Analyze organization policies under a scope.
""",
'EXAMPLES':
"""\
To list 10 organization policies of a constraint in an organization, run:
$ {command} --scope=organizations/YOUR_ORG_ID --constraint=YOUR_CONSTRAINT_NAME --limit=10
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=True,
help=("""\
Scope can only be an organization. The analysis is
limited to the Cloud organization policies within this scope. The caller must be
granted the `cloudasset.assets.searchAllResources` permission on
the desired scope.
The allowed values are:
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddConstraintArgument(parser):
parser.add_argument(
'--constraint',
metavar='CONSTRAINT',
required=True,
help=("""\
The name of the constraint to analyze organization policies for. The
response only contains analyzed organization policies for the provided
constraint.
Example:
* organizations/{ORGANIZATION_NUMBER}/customConstraints/{CUSTOM_CONSTRAINT_NAME}
for a user-defined custom constraint.
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AnalyzeOrgPolicies(base.ListCommand):
"""Analyze organization policies under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicies(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AnalyzeOrgPoliciesBeta(AnalyzeOrgPolicies):
"""Analyze organization policies under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicies(args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeOrgPoliciesGA(AnalyzeOrgPolicies):
"""Analyze organization policies under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicies(args)

View File

@@ -0,0 +1,110 @@
# -*- 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 AnalyzeOrgPolicyGovernedAssets API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Analyze organization policies governed assets under a scope.
""",
'EXAMPLES':
"""\
To list 10 assets governed by a constraint in an organization, run:
$ {command} --scope=organizations/YOUR_ORG_ID --constraint=YOUR_CONSTRAINT_NAME --limit=10
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=True,
help=("""\
Scope can only be an organization. The analysis is
limited to the Cloud organization policies and assets within this scope. The caller must be
granted the `cloudasset.assets.searchAllResources` and `cloudasset.assets.searchAllIamPolicies` permission on
the desired scope.
The allowed values are:
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddConstraintArgument(parser):
parser.add_argument(
'--constraint',
metavar='CONSTRAINT',
required=True,
help=("""\
The name of the constraint to analyze organization policies for. The
response only contains analyzed organization policies for the provided
constraint.
Examples:
* organizations/{ORGANIZATION_NUMBER}/customConstraints/{CUSTOM_CONSTRAINT_NAME}
for a user-defined custom constraint.
* organizations/{ORGANIZATION_NUMBER}/constraints/{CANNED_CONSTRAINT_NAME}
for a gcp-service-defined canned constraint.
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AnalyzeOrgPolicyGovernedAssets(base.ListCommand):
"""Analyze organization policies governed assets under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicyGovernedAssets(args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeOrgPolicyGovernedAssetsGA(AnalyzeOrgPolicyGovernedAssets):
"""Analyze organization policies governed assets under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicyGovernedAssets(args)

View File

@@ -0,0 +1,126 @@
# -*- 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 AnalyzeOrgPolicyGovernedContainers API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Analyze organization policies governed containers under a scope.
""",
'EXAMPLES':
"""\
To list 10 containers governed by a constraint in an organization, run:
$ {command} --scope=organizations/YOUR_ORG_ID --constraint=YOUR_CONSTRAINT_NAME --limit=10
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=True,
help=("""\
Scope can only be an organization. The analysis is
limited to the Cloud organization policies and containers within this scope. The caller must be
granted the `cloudasset.assets.searchAllResources` permission on
the desired scope.
The allowed values are:
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddConstraintArgument(parser):
parser.add_argument(
'--constraint',
metavar='CONSTRAINT',
required=True,
help=("""\
The name of the constraint to analyze organization policies for. The
response only contains analyzed organization policies for the provided
constraint.
Example:
* organizations/{ORGANIZATION_NUMBER}/customConstraints/{CUSTOM_CONSTRAINT_NAME}
for a user-defined custom constraint.
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class AnalyzeOrgPolicyGovernedContainers(base.ListCommand):
"""Analyze organization policies governed containers under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicyGovernedContainers(args)
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class AnalyzeOrgPolicyGovernedContainersBeta(AnalyzeOrgPolicyGovernedContainers
):
"""Analyze organization policies governed containers under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicyGovernedContainers(args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class AnalyzeOrgPolicyGovernedContainersGA(AnalyzeOrgPolicyGovernedContainers):
"""Analyze organization policies governed containers under a scope."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddConstraintArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.OrgPolicyAnalyzerClient()
return client.AnalyzeOrgPolicyGovernedContainers(args)

View File

@@ -0,0 +1,84 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to export assets to Google Cloud Storage or BigQuery."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.core import log
OPERATION_DESCRIBE_COMMAND = 'gcloud asset operations describe'
# pylint: disable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Export(base.Command):
"""Export the cloud assets to Google Cloud Storage/BigQuery."""
detailed_help = {
'DESCRIPTION':
"""\
Export the cloud assets to Google Cloud Storage or BigQuery. Use gcloud
asset operations describe to get the latest status of the operation. Note
that to export a project different from the project you want to bill, you
can use --billing-project or authenticate with a service account.
See https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/gcloud-asset
for examples of using a service account.
""",
'EXAMPLES':
"""\
To export a snapshot of assets of type 'compute.googleapis.com/Disk' in
project 'test-project' at '2019-03-05T00:00:00Z' to
'gs://bucket-name/object-name' and only export the asset metadata, run:
$ {command} --project='test-project' --asset-types='compute.googleapis.com/Disk' --snapshot-time='2019-03-05T00:00:00Z' --output-path='gs://bucket-name/object-name' --content-type='resource'
To export a snapshot of assets of type 'compute.googleapis.com/Disk' in
project 'test-project' at '2019-03-05T00:00:00Z' to
'projects/projectId/datasets/datasetId/tables/table_name', overwrite the table
if existed, run:
$ {command} --project='test-project' --asset-types='compute.googleapis.com/Disk' --snapshot-time='2019-03-05T00:00:00Z' --bigquery-table='projects/projectId/datasets/datasetId/tables/table_name' --output-bigquery-force --content-type='resource'
"""
}
# pylint: enable=line-too-long
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'The project which is the root asset.',
'The ID of the organization which is the root asset.',
'The ID of the folder which is the root asset.')
flags.AddSnapshotTimeArgs(parser)
flags.AddAssetTypesArgs(parser)
flags.AddContentTypeArgs(parser, required=False)
flags.AddDestinationArgs(parser)
flags.AddRelationshipTypesArgs(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetExportClient(parent)
operation = client.Export(args)
log.ExportResource(parent, is_async=True, kind='root asset')
log.status.Print('Use [{} {}] to check the status of the operation.'.format(
OPERATION_DESCRIBE_COMMAND, operation.name))

View File

@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The main command group for Cloud Asset Inventory Feeds."""
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 Feeds(base.Group):
"""Manage Cloud Asset Inventory feeds."""

View File

@@ -0,0 +1,65 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to create a Cloud Asset Inventory Feed."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class Create(base.Command):
"""Create a Cloud Asset Inventory Feed."""
detailed_help = {
'DESCRIPTION':
"""\
Create a new Cloud Asset Inventory Feed for updates on assets.
""",
'EXAMPLES':
"""\
To create a new feed 'feed1' in project 'p1' which alerts on compute
disks and network resources types, run:
$ {command} feed1 --project=p1
--asset-types=compute.googleapis.com/Network,compute.googleapis.com/Disk
--content-type=resource --pubsub-topic=projects/project1/topics/feed-topic
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'project of the feed.',
'Organization of the feed.', 'Folder of the feed.')
flags.AddFeedIdArgs(
parser,
('Asset feed identifier being created, it must be unique under the'
' specified parent resource project/folder/organization.'))
flags.AddFeedCriteriaArgs(parser)
flags.AddFeedContentTypeArgs(parser)
flags.AddFeedPubSubTopicArgs(parser, True)
flags.AddFeedConditionExpressionArgs(parser)
flags.AddFeedConditionTitleArgs(parser)
flags.AddFeedConditionDescriptionArgs(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetFeedClient(parent)
return client.Create(args)

View File

@@ -0,0 +1,54 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to delete a Cloud Asset Inventory Feed.."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class Delete(base.Command):
"""Delete a Cloud Asset Inventory Feed."""
detailed_help = {
'DESCRIPTION':
"""\
Delete a Cloud Asset Inventory Feed.
""",
'EXAMPLES':
"""\
To delete a feed 'feed1' in project 'p1', run:
$ {command} feed1 --project=p1
"""
}
# pylint: enable=line-too-long
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'project of the feed.',
'Organization of the feed.', 'Folder of the feed.')
flags.AddFeedIdArgs(parser, 'Asset feed identifier to delete.')
def Run(self, args):
parent = asset_utils.GetFeedParent(args.organization, args.project,
args.folder)
client = client_util.AssetFeedClient(parent)
client.Delete(args)

View File

@@ -0,0 +1,53 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to describe a Cloud Asset Inventory Feed."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class Describe(base.Command):
"""Describe a Cloud Asset Inventory Feed."""
detailed_help = {
'DESCRIPTION':
"""\
Describe a Cloud Asset Inventory Feed.
""",
'EXAMPLES':
"""\
To describe a feed 'feed1' in project 'p1', run:
$ {command} feed1 --project=p1
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'project of the feed.',
'Organization of the feed.', 'Folder of the feed.')
flags.AddFeedIdArgs(parser, 'Asset feed identifier to describe.')
def Run(self, args):
parent = asset_utils.GetFeedParent(args.organization, args.project,
args.folder)
client = client_util.AssetFeedClient(parent)
return client.Describe(args)

View File

@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to list Cloud Asset Inventory Feeds."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class List(base.Command):
"""List Cloud Asset Inventory Feeds."""
detailed_help = {
'DESCRIPTION':
"""\
List Cloud Asset Inventory Feeds under a parent resource.
""",
'EXAMPLES':
"""\
To list feeds in organization 'org1', run:
$ {command} --organization=org1
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'project of the feed.',
'Organization of the feed.', 'Folder of the feed.')
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetFeedClient(parent)
return client.List()

View File

@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to update an existing Cloud Asset Inventory Feed."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.command_lib.util.args import repeated
class Update(base.Command):
"""Update an existing Cloud Asset Inventory Feed."""
detailed_help = {
'DESCRIPTION':
"""\
Update an existing Cloud Asset Inventory Feed.
""",
'EXAMPLES':
"""\
To add an asset-type to an existing feed, run:
$ {command} feed1 --project=p1
--add-asset-types=pubsub.googleapis.com/Topic
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'project of the feed.',
'Organization of the feed.', 'Folder of the feed.')
flags.AddFeedIdArgs(
parser,
('Identifier of the asset feed to update, which must be unique in its '
'parent resource. Parent resource can be a project, '
'folder, or an organization. '))
repeated.AddPrimitiveArgs(
parser,
'Feed',
'asset-names',
'assetNames',
additional_help=(
'See '
'https://cloud.google.com/apis/design/resource_names#full_resource_name'
' for more information.'),
include_set=False)
repeated.AddPrimitiveArgs(
parser,
'Feed',
'asset-types',
'assetTypes',
additional_help=('See https://cloud.google.com/resource-manager/docs/'
'cloud-asset-inventory/overview for all supported '
'asset types.'),
include_set=False)
repeated.AddPrimitiveArgs(
parser,
'Feed',
'relationship-types',
'relationshipTypes',
additional_help=('See https://cloud.google.com/resource-manager/docs/'
'cloud-asset-inventory/overview for all supported '
'relationship types.'),
include_set=False)
flags.AddUpdateFeedContentTypeArgs(parser)
flags.AddFeedPubSubTopicArgs(parser, False)
flags.AddUpdateFeedConditionExpressionArgs(parser)
flags.AddUpdateFeedConditionTitleArgs(parser)
flags.AddUpdateFeedConditionDescriptionArgs(parser)
def Run(self, args):
parent = asset_utils.GetFeedParent(args.organization, args.project,
args.folder)
client = client_util.AssetFeedClient(parent)
return client.Update(args)

View File

@@ -0,0 +1,109 @@
# -*- 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 to call batch get Effective IAM Policies API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Batch get effective IAM policies that match a request.
""",
'EXAMPLES':
"""\
To list effective IAM policies of 1 resource in an organization, run:
$ {command} --scope=organizations/YOUR_ORG_ID --names=RESOURCE_NAME1
To list effective IAM policies of 2 resources in a folder, run:
$ {command} --scope=folders/YOUR_FOLDER_ID --names=RESOURCE_NAME1,RESOURCE_NAME2
To list effective IAM policies of 3 resources in a project using project ID, run:
$ {command} --scope=projects/YOUR_PROJECT_ID --names=RESOURCE_NAME1,RESOURCE_NAME2,RESOURCE_NAME3
To list effective IAM policies of 2 resources in a project using project number, run:
$ {command} --scope=projects/YOUR_PROJECT_NUMBER --names=RESOURCE_NAME1,RESOURCE_NAME2
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=True,
help=("""\
Scope can be a project, a folder, or an organization. The search is
limited to the IAM policies within this scope. The caller must be
granted the ``cloudasset.assets.analyzeIamPolicy'',
``cloudasset.assets.searchAllResources'',
``cloudasset.assets.searchAllIamPolicies'' permissions
on the desired scope.
The allowed values are:
* ```projects/{PROJECT_ID}``` (e.g. ``projects/foo-bar'')
* ```projects/{PROJECT_NUMBER}``` (e.g. ``projects/12345678'')
* ```folders/{FOLDER_NUMBER}``` (e.g. ``folders/1234567'')
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddNamesArgument(parser):
parser.add_argument(
'--names',
metavar='NAMES',
type=arg_parsers.ArgList(min_length=1, max_length=20),
required=True,
help=("""\
Names refer to a list of
[full resource names](https://cloud.google.com/asset-inventory/docs/resource-name-format)
of [searchable asset types](https://cloud.google.com/asset-inventory/docs/supported-asset-types).
For each batch call, total number of names provided is between 1 and 20.
The example value is:
* ```//cloudsql.googleapis.com/projects/{PROJECT_ID}/instances/{INSTANCE}```
(e.g. ``//cloudsql.googleapis.com/projects/probe-per-rt-project/instances/instance1'')
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.GA)
class EffectiveIAMPolicyGA(base.Command):
"""Get effective IAM policies for a specified list of resources within accessible scope, such as a project, folder or organization."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddNamesArgument(parser)
AddScopeArgument(parser)
def Run(self, args):
client = client_util.EffectiveIAMPolicyClient()
return client.BatchGetEffectiveIAMPolicies(args)

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to get history of assets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.util.args import common_args
class GetHistory(base.Command):
"""Get the update history of assets that overlaps a time window."""
detailed_help = {
'EXAMPLES':
"""\
To get the history of asset metadata for
'//compute.googleapis.com/projects/test-project/zones/us-central1-f/instances/instance1'
between '2018-10-02T15:01:23.045Z' and '2018-12-05T13:01:21.045Z', run:
$ {command} --project='test-project' --asset-names='//compute.googleapis.com/projects/test-project/zones/us-central1-f/instances/instance1' --start-time='2018-10-02T15:01:23.045Z' --end-time='2018-12-05T13:01:21.045Z' --content-type='resource'
To get the history of asset iam policy for
'//cloudresourcemanager.googleapis.com/projects/10179387634'
between '2018-10-02T15:01:23.045Z' and '2018-12-05T13:01:21.045Z', and
project '10179387634' is in organization '1060499660910', run:
$ {command} --organization='1060499660910' --asset-names='//cloudresourcemanager.googleapis.com/projects/10179387634' --start-time='2018-10-02T15:01:23.045Z' --end-time='2018-12-05T13:01:21.045Z' --content-type='iam-policy'
"""
}
@staticmethod
def Args(parser):
parent_group = parser.add_mutually_exclusive_group(required=True)
flags.AddOrganizationArgs(
parent_group, 'The ID of the organization which is the root asset.')
common_args.ProjectArgument(
help_text_to_prepend='The project which is the root asset.'
).AddToParser(parent_group)
flags.AddAssetNamesArgs(parser)
flags.AddContentTypeArgs(parser, required=True)
flags.AddRelationshipTypesArgs(parser)
flags.AddStartTimeArgs(parser)
flags.AddEndTimeArgs(parser)
def Run(self, args):
client = client_util.GetHistoryClient()
return client.GetHistory(args)

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command to list assets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.command_lib.util.args import common_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class List(base.ListCommand):
"""List the Cloud assets."""
# pylint: disable=line-too-long
detailed_help = {
'DESCRIPTION':
"""\
List the Cloud assets. Note
that to list a project different from the project you want to bill, you
can use --billing-project or authenticate with a service account.
See https://cloud.google.com/resource-manager/docs/cloud-asset-inventory/gcloud-asset
for examples of using a service account.
""",
'EXAMPLES':
"""\
To list a snapshot of assets of type 'compute.googleapis.com/Disk' in
project 'test-project' at '2019-03-05T00:00:00Z', run:
$ {command} --project='test-project' --asset-types='compute.googleapis.com/Disk' --snapshot-time='2019-03-05T00:00:00Z'
"""
}
# pylint: enable=line-too-long
@staticmethod
def Args(parser):
parent_group = parser.add_mutually_exclusive_group(required=True)
flags.AddOrganizationArgs(
parent_group, 'The ID of the organization which is the root asset.')
common_args.ProjectArgument(
help_text_to_prepend='The project which is the root asset.'
).AddToParser(parent_group)
flags.AddFolderArgs(parent_group,
'The ID of the folder which is the root asset.')
flags.AddSnapshotTimeArgs(parser)
flags.AddAssetTypesArgs(parser)
flags.AddListContentTypeArgs(parser)
flags.AddRelationshipTypesArgs(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetListClient(parent)
return client.List(args)

View File

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

View File

@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Command for asset operations describe."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
class Describe(base.DescribeCommand):
"""Describe a Cloud Asset Inventory operation."""
detailed_help = {
'EXAMPLES': """\
To describe the operation 'projects/19306908007/operations/ExportAssets/RESOURCE/78689643348272423423', run:
$ {command} projects/19306908007/operations/ExportAssets/RESOURCE/78689643348272423423
"""
}
@staticmethod
def Args(parser):
flags.AddOperationArgs(parser)
def Run(self, args):
service = client_util.AssetOperationClient()
return service.Get(name=args.id)

View File

@@ -0,0 +1,82 @@
# -*- 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 QueryAsset API."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import asset_query_printer
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.command_lib.util.args import common_args
@base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA,
base.ReleaseTrack.GA)
class Query(base.Command):
"""Query the Cloud assets."""
# pylint: disable=line-too-long
detailed_help = {
'DESCRIPTION':
"""\
Issue an analytical query on Cloud assets using a BigQuery Standard SQL
compatible statement.
""",
'EXAMPLES':
"""\
To count the number of compute instances, run:
$ {command} --project='test-project' --statement='SELECT * FROM compute_googleapis_com_Instance'
To see the query result of the previous job, pass the job-reference from the previous response:
$ {command} --project='test-project' --job-reference=<job-reference-from>
"""
}
# pylint: enable=line-too-long
@staticmethod
def Args(parser):
parent_group = parser.add_mutually_exclusive_group(required=True)
flags.AddOrganizationArgs(
parent_group, 'The ID of the organization which is the root asset.')
common_args.ProjectArgument(
help_text_to_prepend='The project which is the root asset.'
).AddToParser(parent_group)
flags.AddFolderArgs(parent_group,
'The ID of the folder which is the root asset.')
flags.AddQueryArgs(parser)
flags.AddPageSize(parser)
flags.AddPageToken(parser)
flags.AddTimeout(parser)
flags.AddTimeArgs(parser)
flags.AddQuerySystemBigQueryArgs(parser)
parser.display_info.AddFormat(
asset_query_printer.ASSET_QUERY_PRINTER_FORMAT)
asset_query_printer.AssetQueryPrinter.Register(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetQueryClient(parent)
resp = client.Query(args)
return resp

View File

@@ -0,0 +1,25 @@
# -*- 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 main command group for Cloud Asset Inventory saved queries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.calliope import base
class SavedQueries(base.Group):
"""Manage Cloud Asset Inventory saved queries."""

View File

@@ -0,0 +1,66 @@
# -*- 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 to create a Cloud Asset Inventory saved query."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.command_lib.util.args import labels_util
class Create(base.Command):
"""Create a Cloud Asset Inventory saved query."""
detailed_help = {
'DESCRIPTION':
"""\
Create a new Cloud Asset Inventory saved query.
""",
'EXAMPLES':
"""\
To create a new saved 'query-id-1' in project 'p1' with the content of the query stored locally in query.json, run:
$ {command} query-id-1 --project=p1
--query-file-path=./query-content.json
--description="This is an example saved query with query id query-id-1"
--labels="key1=val1"
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'Project of the saved query.',
'Organization of the saved query.',
'Folder of the saved query.')
query_id_help_text = (
'Saved query identifier being created. It must be unique under the'
' specified parent resource project/folder/organization.')
flags.AddSavedQueriesQueryId(parser, query_id_help_text)
flags.AddSavedQueriesQueryFilePath(parser, True)
flags.AddSavedQueriesQueryDescription(parser)
labels_util.AddCreateLabelsFlags(parser)
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetSavedQueriesClient(parent)
return client.Create(args)

View File

@@ -0,0 +1,58 @@
# -*- 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 to delete a Cloud Asset Inventory saved query."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class Delete(base.Command):
"""Delete a Cloud Asset Inventory saved query."""
detailed_help = {
'DESCRIPTION':
"""\
Delete a Cloud Asset Inventory saved query.
""",
'EXAMPLES':
"""\
To delete a saved query with id 'query1' in project 'p1', run:
$ {command} query1 --project=p1
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'Project of the saved query.',
'Organization of the saved query.',
'Folder of the saved query.')
query_id_helper_text = (
'Asset saved query identifier to be deleted. It must be unique under '
'the specified parent resource project/folder/organization.')
flags.AddSavedQueriesQueryId(parser, query_id_helper_text)
def Run(self, args):
parent = asset_utils.GetSavedQueriesParent(args.organization, args.project,
args.folder)
client = client_util.AssetSavedQueriesClient(parent)
client.Delete(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 to describe a Cloud Asset Inventory saved query."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class Describe(base.Command):
"""Describe a Cloud Asset Inventory saved query."""
detailed_help = {
'DESCRIPTION':
"""\
Describe a Cloud Asset Inventory saved query.
""",
'EXAMPLES':
"""\
To describe a saved query with query id 'query1' in project 'p1', run:
$ {command} query1 --project=p1
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'Project of the saved query.',
'Organization of the saved query.',
'Folder of the saved query.')
query_id_helper_text = (
'Asset Saved Query identifier being described. '
'It must be unique under the'
' specified parent resource: project/folder/organization.')
flags.AddSavedQueriesQueryId(parser, query_id_helper_text)
def Run(self, args):
parent = asset_utils.GetSavedQueriesParent(args.organization, args.project,
args.folder)
client = client_util.AssetSavedQueriesClient(parent)
return client.Describe(args)

View File

@@ -0,0 +1,53 @@
# -*- 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 to list Cloud Asset Inventory saved queries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
class List(base.Command):
"""List Cloud Asset Inventory saved query."""
detailed_help = {
'DESCRIPTION':
"""\
List Cloud Asset Inventory saved queries under a parent resource.
""",
'EXAMPLES':
"""\
To list saved queries in organization 'org1', run:
$ {command} --organization=org1
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'Project of the saved query.',
'Organization of the saved query.',
'Folder of the saved query.')
def Run(self, args):
parent = asset_utils.GetParentNameForExport(args.organization, args.project,
args.folder)
client = client_util.AssetSavedQueriesClient(parent)
return client.List()

View File

@@ -0,0 +1,65 @@
# -*- 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 to update an existing Cloud Asset Inventory saved query."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.asset import flags
from googlecloudsdk.command_lib.asset import utils as asset_utils
from googlecloudsdk.command_lib.util.args import labels_util
class Update(base.Command):
"""Update an existing Cloud Asset Inventory saved query."""
detailed_help = {
'DESCRIPTION':
"""\
Update an existing Cloud Asset Inventory saved query.
""",
'EXAMPLES':
"""\
To update the content of an existing saved query, run:
$ {command} query-id-1 --project=p1
--query-file-path=./query-content.json
--description="updating a query with query id query-id-1"
--update-labels="key1=val1"
"""
}
@staticmethod
def Args(parser):
flags.AddParentArgs(parser, 'Project of the saved query.',
'Organization of the saved query.',
'Folder of the saved query.')
saved_query_id_helper_text = (
'Saved query identifier being updated. It must be unique under the'
' specified parent resource project/folder/organization.')
flags.AddSavedQueriesQueryId(parser, saved_query_id_helper_text)
labels_util.AddUpdateLabelsFlags(parser)
flags.AddSavedQueriesQueryFilePath(parser, False)
flags.AddSavedQueriesQueryDescription(parser)
def Run(self, args):
parent = asset_utils.GetSavedQueriesParent(args.organization, args.project,
args.folder)
client = client_util.AssetSavedQueriesClient(parent)
return client.Update(args)

View File

@@ -0,0 +1,217 @@
# -*- 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 SearchAllIamPolicies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Searches all IAM policies within the specified scope, such as a project,
folder or organization. The caller must be granted the
``cloudasset.assets.searchAllIamPolicies'' permission on the desired
scope.
Note: The query is compared against each IAM policy binding, including its
principals, roles and conditions. The returned IAM policies, will only
contain the bindings that match your query. To learn more about the IAM
policy structure, see the [IAM policy documentation](https://cloud.google.com/iam/help/allow-policies/structure).
""",
'EXAMPLES':
"""\
To search all the IAM policies that specify ``amy@mycompany.com'' within
``organizations/123456'', ensure the caller has been granted the
``cloudasset.assets.searchAllIamPolicies'' permission on the organization
and run:
$ {command} --scope='organizations/123456' --query='policy:amy@mycompany.com'
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=False,
help=("""\
Scope can be a project, a folder, or an organization. The search is
limited to the IAM policies within this scope. The caller must be
granted the ``cloudasset.assets.searchAllIamPolicies'' permission
on the desired scope. If not specified, the [configured project property](https://cloud.google.com//sdk/docs/configurations#setting_configuration_properties)
will be used. To find the configured project, run:
```gcloud config get project```. To change the setting, run:
```gcloud config set project PROJECT_ID```.
The allowed values are:
* ```projects/{PROJECT_ID}``` (e.g. ``projects/foo-bar'')
* ```projects/{PROJECT_NUMBER}``` (e.g. ``projects/12345678'')
* ```folders/{FOLDER_NUMBER}``` (e.g. ``folders/1234567'')
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddQueryArgument(parser):
parser.add_argument(
'--query',
metavar='QUERY',
required=False,
help=("""\
Query statement. See [how to construct a
query](https://cloud.google.com/asset-inventory/docs/searching-iam-policies#how_to_construct_a_query)
for more information. If not specified or empty, it will search all the
IAM policies within the specified ```scope```. Note that the query
string is compared against each Cloud IAM policy binding, including its
principals, roles, and Cloud IAM conditions. The returned Cloud IAM
policies will only contain the bindings that match your query. To learn
more about the IAM policy structure, see the [IAM policy documentation](https://cloud.google.com/iam/help/allow-policies/structure).
Examples:
* ```policy:amy@gmail.com``` to find IAM policy bindings that specify
user ``amy@gmail.com''.
* ```policy:roles/compute.admin``` to find IAM policy bindings that
specify the Compute Admin role.
* ```policy:comp*``` to find IAM policy bindings that contain ``comp''
as a prefix of any word in the binding.
* ```policy.role.permissions:storage.buckets.update``` to find IAM
policy bindings that specify a role containing the
``storage.buckets.update'' permission. Note that if callers haven't
been granted the ``iam.roles.get'' permission for a role's included
permissions, policy bindings that specify this role will be dropped
from the search results.
* ```policy.role.permissions:upd*``` to find IAM policy bindings that
specify a role containing ``upd'' as a prefix of any word in the role
permission. Note that if callers haven't been granted the
``iam.roles.get'' permission for a role's included permissions, policy
bindings that specify this role will be dropped from the search
results.
* ```resource:organizations/123456``` to find IAM policy bindings that
are set on ``organizations/123456''.
* ```resource=//cloudresourcemanager.googleapis.com/projects/myproject```
to find IAM policy bindings that are set on the project named
``myproject''.
* ```Important``` to find IAM policy bindings that contain ``Important''
as a word in any of the searchable fields (except for the included
permissions).
* ```resource:(instance1 OR instance2) policy:amy``` to find IAM policy
bindings that are set on resources ``instance1'' or ``instance2'' and
also specify user ``amy''.
* ```roles:roles/compute.admin``` to find IAM policy bindings that
specify the Compute Admin role.
* ```memberTypes:user``` to find IAM policy bindings that contain the
``user'' principal type.
"""))
def AddAssetTypesArgument(parser):
parser.add_argument(
'--asset-types',
metavar='ASSET_TYPES',
type=arg_parsers.ArgList(),
default=[],
help=("""\
List of asset types that the IAM policies are attached to. If empty, it
will search the IAM policies that are attached to all the [searchable asset types](https://cloud.google.com/asset-inventory/docs/supported-asset-types).
Regular expressions are also supported. For example:
* ``compute.googleapis.com.*'' snapshots IAM policies attached to
asset type starts with ``compute.googleapis.com''.
* ``.*Instance'' snapshots IAM policies attached to asset type ends
with ``Instance''.
* ``.*Instance.*'' snapshots IAM policies attached to asset type
contains ``Instance''.
See [RE2](https://github.com/google/re2/wiki/Syntax) for all supported
regular expression syntax. If the regular expression does not match any
supported asset type, an ``INVALID_ARGUMENT'' error will be returned.
"""))
def AddOrderByArgument(parser):
parser.add_argument(
'--order-by',
metavar='ORDER_BY',
required=False,
help=("""\
Comma-separated list of fields specifying the sorting order of the
results. The default order is ascending. Add `` DESC'' after the field
name to indicate descending order. Redundant space characters are
ignored. Example: ``assetType DESC, resource''. Only singular primitive
fields in the response are sortable:
* `resource`
* `assetType`
* `project`
All the other fields such as repeated fields (e.g., `folders`) and
non-primitive fields (e.g., `policy`) are not supported.
Both ```--order-by``` and ```--sort-by``` flags can be used to sort the
output, with the following differences:
* The ```--order-by``` flag performs server-side sorting (better
performance), while the ```--sort-by``` flag performs client-side
sorting.
* The ```--sort-by``` flag supports all the fields in the output, while
the ```--order-by``` flag only supports limited fields as shown above.
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class SearchAllIamPoliciesBeta(base.ListCommand):
"""Searches all IAM policies within the specified accessible scope, such as a project, folder or organization."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddQueryArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.AssetSearchClient(client_util.V1P1BETA1_API_VERSION)
return client.SearchAllIamPolicies(args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class SearchAllIamPolicies(SearchAllIamPoliciesBeta):
"""Searches all IAM policies within the specified accessible scope, such as a project, folder or organization."""
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddQueryArgument(parser)
AddAssetTypesArgument(parser)
AddOrderByArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.AssetSearchClient(client_util.DEFAULT_API_VERSION)
return client.SearchAllIamPolicies(args)

View File

@@ -0,0 +1,302 @@
# -*- 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 SearchAllResources."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.asset import client_util
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import base
# pylint: disable=line-too-long
DETAILED_HELP = {
'DESCRIPTION':
"""\
Searches all Cloud resources within the specified scope, such as a
project, folder or organization. The caller must be granted the
``cloudasset.assets.searchAllResources'' permission on the desired
scope.
""",
'EXAMPLES':
"""\
To search all Cloud resources whose full resource name contains
``xyz'' as a prefix of any word, within ``organizations/123456'', ensure
the caller has been granted the ``cloudasset.assets.searchAllResources''
permission on the organization and run:
$ {command} --scope='organizations/123456' --query='name:xyz*'
"""
}
def AddScopeArgument(parser):
parser.add_argument(
'--scope',
metavar='SCOPE',
required=False,
help=("""\
A scope can be a project, a folder, or an organization. The search is
limited to the Cloud resources within this scope. The caller must be
granted the ``cloudasset.assets.searchAllResources'' permission on
the desired scope. If not specified, the [configured project property](https://cloud.google.com//sdk/docs/configurations#setting_configuration_properties)
will be used. To find the configured project, run:
```gcloud config get project```. To change the setting, run:
```gcloud config set project PROJECT_ID```.
The allowed values are:
* ```projects/{PROJECT_ID}``` (e.g., ``projects/foo-bar'')
* ```projects/{PROJECT_NUMBER}``` (e.g., ``projects/12345678'')
* ```folders/{FOLDER_NUMBER}``` (e.g., ``folders/1234567'')
* ```organizations/{ORGANIZATION_NUMBER}``` (e.g. ``organizations/123456'')
"""))
def AddQueryArgument(parser):
parser.add_argument(
'--query',
metavar='QUERY',
required=False,
help=("""\
The query statement. See [how to construct a
query](https://cloud.google.com/asset-inventory/docs/searching-resources#how_to_construct_a_query)
for more details. If not specified or empty, it will search all the
resources within the specified ```scope```.
Examples:
* ```name:Important``` to find Cloud resources whose name contains
``Important'' as a word.
* ```name=Important``` to find the Cloud resource whose name is exactly
``Important''.
* ```displayName:Impor*``` to find Cloud resources whose display name
contains ``Impor'' as a prefix of any word.
* ```location:us-west*``` to find Cloud resources whose location
contains both ``us'' and ``west'' as prefixes.
* ```labels:prod``` to find Cloud resources whose labels contain
``prod'' as a key or value.
* ```labels.env:prod``` to find Cloud resources that have a label
``env'' and its value is ``prod''.
* ```labels.env:*``` to find Cloud resources that have a label
``env''.
* ```tagKeys:env``` to find Cloud resources that are directly attached
to tags where the
[`TagKey.namespacedName`](https://cloud.google.com/resource-manager/reference/rest/v3/tagKeys#resource:-tagkey)
contains `env`.
* ```tagValues:prod*``` to find Cloud resources that are directly
attached to tags where the
[`TagValue.namespacedName`](https://cloud.google.com/resource-manager/reference/rest/v3/tagValues#resource:-tagvalue)
contains a word prefixed by `prod`.
* ```tagValueIds=tagValues/123``` to find Cloud resources that are
directly attached to tags where the
[`TagValue.name`](https://cloud.google.com/resource-manager/reference/rest/v3/tagValues#resource:-tagvalue)
is exactly `tagValues/123`.
* ```effectiveTagKeys:env``` to find Cloud resources that are directly
attached to or inherited tags where the
[`TagKey.namespacedName`](https://cloud.google.com/resource-manager/reference/rest/v3/tagKeys#resource:-tagkey)
contains `env`.
* ```effectiveTagValues:prod*``` to find Cloud resources that are
directly attached to or inherited tags where the
[`TagValue.namespacedName`](https://cloud.google.com/resource-manager/reference/rest/v3/tagValues#resource:-tagvalue)
contains a word prefixed by `prod`.
* ```effectiveTagValueIds=tagValues/123``` to find Cloud resources that
are directly attached to or inherited tags where the
[`TagValue.name`](https://cloud.google.com/resource-manager/reference/rest/v3/tagValues#resource:-tagvalue)
is exactly `tagValues/123`.
* ```kmsKey:key``` to find Cloud resources encrypted with a
customer-managed encryption key whose name contains ``key'' as a word.
This field is deprecated. Please use the `kmsKeys` field to retrieve
KMS key information.
* ```kmsKeys:key``` to find Cloud resources encrypted with
customer-managed encryption keys whose name contains the word ``key''.
* ```relationships:instance-group-1``` to find Cloud resources that have
relationships with ``instance-group-1'' in the related resource name.
* ```relationships:INSTANCE_TO_INSTANCEGROUP``` to find Compute
instances that have relationships of type
``INSTANCE_TO_INSTANCEGROUP''.
* ```relationships.INSTANCE_TO_INSTANCEGROUP:instance-group-1``` to find
Compute instances that have relationships with ``instance-group-1'' in
the Compute instance group resource name, for relationship type
``INSTANCE_TO_INSTANCEGROUP''.
* ```sccSecurityMarks.key=value``` to find Cloud resources that are
attached with security marks whose key is ``key'' and value is
``value''.
* ```sccSecurityMarks.key:*``` to find Cloud resources that are attached
with security marks whose key is ``key''.
* ```state:ACTIVE``` to find Cloud resources whose state contains
``ACTIVE'' as a word.
* ```NOT state:ACTIVE``` to find Cloud resources whose state doesn't
contain ``ACTIVE'' as a word.
* ```createTime<1609459200``` or ```createTime<2021-01-01``` or
```createTime<"2021-01-01T00:00:00"``` to find Cloud resources that
were created before ``2021-01-01 00:00:00 UTC''. 1609459200 is the
epoch timestamp of ``2021-01-01 00:00:00 UTC'' in seconds.
* ```updateTime>1609459200``` or ```updateTime>2021-01-01``` or
```updateTime>"2021-01-01T00:00:00"``` to find Cloud resources that
were updated after ``2021-01-01 00:00:00 UTC''. 1609459200 is the
epoch timestamp of ``2021-01-01 00:00:00 UTC'' in seconds.
* ```Important``` to find Cloud resources that contain ``Important''
as a word in any of the searchable fields.
* ```Impor*``` to find Cloud resources that contain ``Impor'' as a
prefix of any word in any of the searchable fields.
* ```Important location:(us-west1 OR global)``` to find
Cloud resources that contain ``Important'' as a word in any of the
searchable fields and are also located in the ``us-west1'' region or
the ``global'' location.
"""))
def AddAssetTypesArgument(parser):
parser.add_argument(
'--asset-types',
metavar='ASSET_TYPES',
type=arg_parsers.ArgList(),
default=[],
help=("""\
A list of asset types that this request searches for. If empty, it will
search all the [searchable asset types](https://cloud.google.com/asset-inventory/docs/supported-asset-types).
Regular expressions are also supported. For example:
* ``compute.googleapis.com.*'' snapshots resources whose asset type
starts with ``compute.googleapis.com''.
* ``.*Instance'' snapshots resources whose asset type ends with
``Instance''.
* ``.*Instance.*'' snapshots resources whose asset type contains
``Instance''.
See [RE2](https://github.com/google/re2/wiki/Syntax) for all supported
regular expression syntax. If the regular expression does not match any
supported asset type, an ``INVALID_ARGUMENT'' error will be returned.
"""))
def AddOrderByArgument(parser):
parser.add_argument(
'--order-by',
metavar='ORDER_BY',
required=False,
help=("""\
A comma-separated list of fields specifying the sorting order of the
results. The default order is ascending. Add `` DESC'' after the field
name to indicate descending order. Redundant space characters are
ignored. Example: ``location DESC, name''. Only singular primitive
fields in the response are sortable:
* `name`
* `assetType`
* `project`
* `displayName`
* `description`
* `location`
* `createTime`
* `updateTime`
* `state`
* `parentFullResourceName`
* `parentAssetType`
All the other fields such as repeated fields (e.g., `networkTags`,
`kmsKeys`), map fields (e.g., `labels`) and struct fields (e.g.,
`additionalAttributes`) are not supported.
Both ```--order-by``` and ```--sort-by``` flags can be used to sort the
output, with the following differences:
* The ```--order-by``` flag performs server-side sorting (better
performance), while the ```--sort-by``` flag performs client-side
sorting.
* The ```--sort-by``` flag supports all the fields in the output, while
the ```--order-by``` flag only supports limited fields as shown above.
"""))
def AddReadMaskArgument(parser):
parser.add_argument(
'--read-mask',
metavar='READ_MASK',
required=False,
help=("""\
A comma-separated list of fields specifying which fields to be returned
in the results. Only `"*"` or combination of top level fields can be
specified. Examples: `"*"`, `"name,location"`, `"name,versionedResources"`.
The read_mask paths must be valid field paths listed but not limited to
the following (both snake_case and camelCase are supported):
* `name`
* `asset_type` or `assetType`
* `project`
* `display_name` or `displayName`
* `description`
* `location`
* `labels`
* `tags`
* `effective_tags` or `effectiveTags`
* `network_tags` or `networkTags`
* `kms_keys` or `kmsKeys`
* `create_time` or `createTime`
* `update_time` or `updateTime`
* `state`
* `additional_attributes` or `additionalAttributes`
* `versioned_resources` or `versionedResources`
If read_mask is not specified, all fields except versionedResources
will be returned.
If only `"*"` is specified, all fields including versionedResources will
be returned.
"""))
# pylint: enable=line-too-long
@base.ReleaseTracks(base.ReleaseTrack.BETA)
class SearchAllResourcesBeta(base.ListCommand):
"""Searches all Cloud resources within the specified accessible scope, such as a project, folder or organization."""
detailed_help = DETAILED_HELP
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddQueryArgument(parser)
AddAssetTypesArgument(parser)
AddOrderByArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.AssetSearchClient(client_util.V1P1BETA1_API_VERSION)
return client.SearchAllResources(args)
@base.ReleaseTracks(base.ReleaseTrack.GA)
class SearchAllResources(SearchAllResourcesBeta):
"""Searches all Cloud resources within the specified accessible scope, such as a project, folder or organization."""
@staticmethod
def Args(parser):
AddScopeArgument(parser)
AddQueryArgument(parser)
AddAssetTypesArgument(parser)
AddOrderByArgument(parser)
AddReadMaskArgument(parser)
base.URI_FLAG.RemoveFromParser(parser)
def Run(self, args):
client = client_util.AssetSearchClient(client_util.DEFAULT_API_VERSION)
return client.SearchAllResources(args)