Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/resourcemanager_v3/services/tag_keys/client.py: 33%
284 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 06:03 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 06:03 +0000
1# -*- coding: utf-8 -*-
2# Copyright 2022 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16from collections import OrderedDict
17import os
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29 cast,
30)
32from google.api_core import client_options as client_options_lib
33from google.api_core import exceptions as core_exceptions
34from google.api_core import gapic_v1
35from google.api_core import retry as retries
36from google.auth import credentials as ga_credentials # type: ignore
37from google.auth.exceptions import MutualTLSChannelError # type: ignore
38from google.auth.transport import mtls # type: ignore
39from google.auth.transport.grpc import SslCredentials # type: ignore
40from google.oauth2 import service_account # type: ignore
42from google.cloud.resourcemanager_v3 import gapic_version as package_version
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
49from google.api_core import operation # type: ignore
50from google.api_core import operation_async # type: ignore
51from google.iam.v1 import iam_policy_pb2 # type: ignore
52from google.iam.v1 import policy_pb2 # type: ignore
53from google.longrunning import operations_pb2
54from google.protobuf import field_mask_pb2 # type: ignore
55from google.protobuf import timestamp_pb2 # type: ignore
57from google.cloud.resourcemanager_v3.services.tag_keys import pagers
58from google.cloud.resourcemanager_v3.types import tag_keys
60from .transports.base import DEFAULT_CLIENT_INFO, TagKeysTransport
61from .transports.grpc import TagKeysGrpcTransport
62from .transports.grpc_asyncio import TagKeysGrpcAsyncIOTransport
63from .transports.rest import TagKeysRestTransport
66class TagKeysClientMeta(type):
67 """Metaclass for the TagKeys client.
69 This provides class-level methods for building and retrieving
70 support objects (e.g. transport) without polluting the client instance
71 objects.
72 """
74 _transport_registry = OrderedDict() # type: Dict[str, Type[TagKeysTransport]]
75 _transport_registry["grpc"] = TagKeysGrpcTransport
76 _transport_registry["grpc_asyncio"] = TagKeysGrpcAsyncIOTransport
77 _transport_registry["rest"] = TagKeysRestTransport
79 def get_transport_class(
80 cls,
81 label: Optional[str] = None,
82 ) -> Type[TagKeysTransport]:
83 """Returns an appropriate transport class.
85 Args:
86 label: The name of the desired transport. If none is
87 provided, then the first transport in the registry is used.
89 Returns:
90 The transport class to use.
91 """
92 # If a specific transport is requested, return that one.
93 if label:
94 return cls._transport_registry[label]
96 # No transport is requested; return the default (that is, the first one
97 # in the dictionary).
98 return next(iter(cls._transport_registry.values()))
101class TagKeysClient(metaclass=TagKeysClientMeta):
102 """Allow users to create and manage tag keys."""
104 @staticmethod
105 def _get_default_mtls_endpoint(api_endpoint):
106 """Converts api endpoint to mTLS endpoint.
108 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
109 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
110 Args:
111 api_endpoint (Optional[str]): the api endpoint to convert.
112 Returns:
113 str: converted mTLS api endpoint.
114 """
115 if not api_endpoint:
116 return api_endpoint
118 mtls_endpoint_re = re.compile(
119 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
120 )
122 m = mtls_endpoint_re.match(api_endpoint)
123 name, mtls, sandbox, googledomain = m.groups()
124 if mtls or not googledomain:
125 return api_endpoint
127 if sandbox:
128 return api_endpoint.replace(
129 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
130 )
132 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
134 DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com"
135 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
136 DEFAULT_ENDPOINT
137 )
139 @classmethod
140 def from_service_account_info(cls, info: dict, *args, **kwargs):
141 """Creates an instance of this client using the provided credentials
142 info.
144 Args:
145 info (dict): The service account private key info.
146 args: Additional arguments to pass to the constructor.
147 kwargs: Additional arguments to pass to the constructor.
149 Returns:
150 TagKeysClient: The constructed client.
151 """
152 credentials = service_account.Credentials.from_service_account_info(info)
153 kwargs["credentials"] = credentials
154 return cls(*args, **kwargs)
156 @classmethod
157 def from_service_account_file(cls, filename: str, *args, **kwargs):
158 """Creates an instance of this client using the provided credentials
159 file.
161 Args:
162 filename (str): The path to the service account private key json
163 file.
164 args: Additional arguments to pass to the constructor.
165 kwargs: Additional arguments to pass to the constructor.
167 Returns:
168 TagKeysClient: The constructed client.
169 """
170 credentials = service_account.Credentials.from_service_account_file(filename)
171 kwargs["credentials"] = credentials
172 return cls(*args, **kwargs)
174 from_service_account_json = from_service_account_file
176 @property
177 def transport(self) -> TagKeysTransport:
178 """Returns the transport used by the client instance.
180 Returns:
181 TagKeysTransport: The transport used by the client
182 instance.
183 """
184 return self._transport
186 @staticmethod
187 def tag_key_path(
188 tag_key: str,
189 ) -> str:
190 """Returns a fully-qualified tag_key string."""
191 return "tagKeys/{tag_key}".format(
192 tag_key=tag_key,
193 )
195 @staticmethod
196 def parse_tag_key_path(path: str) -> Dict[str, str]:
197 """Parses a tag_key path into its component segments."""
198 m = re.match(r"^tagKeys/(?P<tag_key>.+?)$", path)
199 return m.groupdict() if m else {}
201 @staticmethod
202 def common_billing_account_path(
203 billing_account: str,
204 ) -> str:
205 """Returns a fully-qualified billing_account string."""
206 return "billingAccounts/{billing_account}".format(
207 billing_account=billing_account,
208 )
210 @staticmethod
211 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
212 """Parse a billing_account path into its component segments."""
213 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
214 return m.groupdict() if m else {}
216 @staticmethod
217 def common_folder_path(
218 folder: str,
219 ) -> str:
220 """Returns a fully-qualified folder string."""
221 return "folders/{folder}".format(
222 folder=folder,
223 )
225 @staticmethod
226 def parse_common_folder_path(path: str) -> Dict[str, str]:
227 """Parse a folder path into its component segments."""
228 m = re.match(r"^folders/(?P<folder>.+?)$", path)
229 return m.groupdict() if m else {}
231 @staticmethod
232 def common_organization_path(
233 organization: str,
234 ) -> str:
235 """Returns a fully-qualified organization string."""
236 return "organizations/{organization}".format(
237 organization=organization,
238 )
240 @staticmethod
241 def parse_common_organization_path(path: str) -> Dict[str, str]:
242 """Parse a organization path into its component segments."""
243 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
244 return m.groupdict() if m else {}
246 @staticmethod
247 def common_project_path(
248 project: str,
249 ) -> str:
250 """Returns a fully-qualified project string."""
251 return "projects/{project}".format(
252 project=project,
253 )
255 @staticmethod
256 def parse_common_project_path(path: str) -> Dict[str, str]:
257 """Parse a project path into its component segments."""
258 m = re.match(r"^projects/(?P<project>.+?)$", path)
259 return m.groupdict() if m else {}
261 @staticmethod
262 def common_location_path(
263 project: str,
264 location: str,
265 ) -> str:
266 """Returns a fully-qualified location string."""
267 return "projects/{project}/locations/{location}".format(
268 project=project,
269 location=location,
270 )
272 @staticmethod
273 def parse_common_location_path(path: str) -> Dict[str, str]:
274 """Parse a location path into its component segments."""
275 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
276 return m.groupdict() if m else {}
278 @classmethod
279 def get_mtls_endpoint_and_cert_source(
280 cls, client_options: Optional[client_options_lib.ClientOptions] = None
281 ):
282 """Return the API endpoint and client cert source for mutual TLS.
284 The client cert source is determined in the following order:
285 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
286 client cert source is None.
287 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
288 default client cert source exists, use the default one; otherwise the client cert
289 source is None.
291 The API endpoint is determined in the following order:
292 (1) if `client_options.api_endpoint` if provided, use the provided one.
293 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
294 default mTLS endpoint; if the environment variable is "never", use the default API
295 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
296 use the default API endpoint.
298 More details can be found at https://google.aip.dev/auth/4114.
300 Args:
301 client_options (google.api_core.client_options.ClientOptions): Custom options for the
302 client. Only the `api_endpoint` and `client_cert_source` properties may be used
303 in this method.
305 Returns:
306 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
307 client cert source to use.
309 Raises:
310 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
311 """
312 if client_options is None:
313 client_options = client_options_lib.ClientOptions()
314 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
315 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
316 if use_client_cert not in ("true", "false"):
317 raise ValueError(
318 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
319 )
320 if use_mtls_endpoint not in ("auto", "never", "always"):
321 raise MutualTLSChannelError(
322 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
323 )
325 # Figure out the client cert source to use.
326 client_cert_source = None
327 if use_client_cert == "true":
328 if client_options.client_cert_source:
329 client_cert_source = client_options.client_cert_source
330 elif mtls.has_default_client_cert_source():
331 client_cert_source = mtls.default_client_cert_source()
333 # Figure out which api endpoint to use.
334 if client_options.api_endpoint is not None:
335 api_endpoint = client_options.api_endpoint
336 elif use_mtls_endpoint == "always" or (
337 use_mtls_endpoint == "auto" and client_cert_source
338 ):
339 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
340 else:
341 api_endpoint = cls.DEFAULT_ENDPOINT
343 return api_endpoint, client_cert_source
345 def __init__(
346 self,
347 *,
348 credentials: Optional[ga_credentials.Credentials] = None,
349 transport: Optional[Union[str, TagKeysTransport]] = None,
350 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
351 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
352 ) -> None:
353 """Instantiates the tag keys client.
355 Args:
356 credentials (Optional[google.auth.credentials.Credentials]): The
357 authorization credentials to attach to requests. These
358 credentials identify the application to the service; if none
359 are specified, the client will attempt to ascertain the
360 credentials from the environment.
361 transport (Union[str, TagKeysTransport]): The
362 transport to use. If set to None, a transport is chosen
363 automatically.
364 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
365 client. It won't take effect if a ``transport`` instance is provided.
366 (1) The ``api_endpoint`` property can be used to override the
367 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
368 environment variable can also be used to override the endpoint:
369 "always" (always use the default mTLS endpoint), "never" (always
370 use the default regular endpoint) and "auto" (auto switch to the
371 default mTLS endpoint if client certificate is present, this is
372 the default value). However, the ``api_endpoint`` property takes
373 precedence if provided.
374 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
375 is "true", then the ``client_cert_source`` property can be used
376 to provide client certificate for mutual TLS transport. If
377 not provided, the default SSL client certificate will be used if
378 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
379 set, no client certificate will be used.
380 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
381 The client info used to send a user-agent string along with
382 API requests. If ``None``, then default info will be used.
383 Generally, you only need to set this if you're developing
384 your own client library.
386 Raises:
387 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
388 creation failed for any reason.
389 """
390 if isinstance(client_options, dict):
391 client_options = client_options_lib.from_dict(client_options)
392 if client_options is None:
393 client_options = client_options_lib.ClientOptions()
394 client_options = cast(client_options_lib.ClientOptions, client_options)
396 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
397 client_options
398 )
400 api_key_value = getattr(client_options, "api_key", None)
401 if api_key_value and credentials:
402 raise ValueError(
403 "client_options.api_key and credentials are mutually exclusive"
404 )
406 # Save or instantiate the transport.
407 # Ordinarily, we provide the transport, but allowing a custom transport
408 # instance provides an extensibility point for unusual situations.
409 if isinstance(transport, TagKeysTransport):
410 # transport is a TagKeysTransport instance.
411 if credentials or client_options.credentials_file or api_key_value:
412 raise ValueError(
413 "When providing a transport instance, "
414 "provide its credentials directly."
415 )
416 if client_options.scopes:
417 raise ValueError(
418 "When providing a transport instance, provide its scopes "
419 "directly."
420 )
421 self._transport = transport
422 else:
423 import google.auth._default # type: ignore
425 if api_key_value and hasattr(
426 google.auth._default, "get_api_key_credentials"
427 ):
428 credentials = google.auth._default.get_api_key_credentials(
429 api_key_value
430 )
432 Transport = type(self).get_transport_class(transport)
433 self._transport = Transport(
434 credentials=credentials,
435 credentials_file=client_options.credentials_file,
436 host=api_endpoint,
437 scopes=client_options.scopes,
438 client_cert_source_for_mtls=client_cert_source_func,
439 quota_project_id=client_options.quota_project_id,
440 client_info=client_info,
441 always_use_jwt_access=True,
442 api_audience=client_options.api_audience,
443 )
445 def list_tag_keys(
446 self,
447 request: Optional[Union[tag_keys.ListTagKeysRequest, dict]] = None,
448 *,
449 parent: Optional[str] = None,
450 retry: OptionalRetry = gapic_v1.method.DEFAULT,
451 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
452 metadata: Sequence[Tuple[str, str]] = (),
453 ) -> pagers.ListTagKeysPager:
454 r"""Lists all TagKeys for a parent resource.
456 .. code-block:: python
458 # This snippet has been automatically generated and should be regarded as a
459 # code template only.
460 # It will require modifications to work:
461 # - It may require correct/in-range values for request initialization.
462 # - It may require specifying regional endpoints when creating the service
463 # client as shown in:
464 # https://googleapis.dev/python/google-api-core/latest/client_options.html
465 from google.cloud import resourcemanager_v3
467 def sample_list_tag_keys():
468 # Create a client
469 client = resourcemanager_v3.TagKeysClient()
471 # Initialize request argument(s)
472 request = resourcemanager_v3.ListTagKeysRequest(
473 parent="parent_value",
474 )
476 # Make the request
477 page_result = client.list_tag_keys(request=request)
479 # Handle the response
480 for response in page_result:
481 print(response)
483 Args:
484 request (Union[google.cloud.resourcemanager_v3.types.ListTagKeysRequest, dict]):
485 The request object. The request message for listing all
486 TagKeys under a parent resource.
487 parent (str):
488 Required. The resource name of the TagKey's parent. Must
489 be of the form ``organizations/{org_id}`` or
490 ``projects/{project_id}`` or
491 ``projects/{project_number}``
493 This corresponds to the ``parent`` field
494 on the ``request`` instance; if ``request`` is provided, this
495 should not be set.
496 retry (google.api_core.retry.Retry): Designation of what errors, if any,
497 should be retried.
498 timeout (float): The timeout for this request.
499 metadata (Sequence[Tuple[str, str]]): Strings which should be
500 sent along with the request as metadata.
502 Returns:
503 google.cloud.resourcemanager_v3.services.tag_keys.pagers.ListTagKeysPager:
504 The ListTagKeys response message.
505 Iterating over this object will yield
506 results and resolve additional pages
507 automatically.
509 """
510 # Create or coerce a protobuf request object.
511 # Quick check: If we got a request object, we should *not* have
512 # gotten any keyword arguments that map to the request.
513 has_flattened_params = any([parent])
514 if request is not None and has_flattened_params:
515 raise ValueError(
516 "If the `request` argument is set, then none of "
517 "the individual field arguments should be set."
518 )
520 # Minor optimization to avoid making a copy if the user passes
521 # in a tag_keys.ListTagKeysRequest.
522 # There's no risk of modifying the input as we've already verified
523 # there are no flattened fields.
524 if not isinstance(request, tag_keys.ListTagKeysRequest):
525 request = tag_keys.ListTagKeysRequest(request)
526 # If we have keyword arguments corresponding to fields on the
527 # request, apply these.
528 if parent is not None:
529 request.parent = parent
531 # Wrap the RPC method; this adds retry and timeout information,
532 # and friendly error handling.
533 rpc = self._transport._wrapped_methods[self._transport.list_tag_keys]
535 # Send the request.
536 response = rpc(
537 request,
538 retry=retry,
539 timeout=timeout,
540 metadata=metadata,
541 )
543 # This method is paged; wrap the response in a pager, which provides
544 # an `__iter__` convenience method.
545 response = pagers.ListTagKeysPager(
546 method=rpc,
547 request=request,
548 response=response,
549 metadata=metadata,
550 )
552 # Done; return the response.
553 return response
555 def get_tag_key(
556 self,
557 request: Optional[Union[tag_keys.GetTagKeyRequest, dict]] = None,
558 *,
559 name: Optional[str] = None,
560 retry: OptionalRetry = gapic_v1.method.DEFAULT,
561 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
562 metadata: Sequence[Tuple[str, str]] = (),
563 ) -> tag_keys.TagKey:
564 r"""Retrieves a TagKey. This method will return
565 ``PERMISSION_DENIED`` if the key does not exist or the user does
566 not have permission to view it.
568 .. code-block:: python
570 # This snippet has been automatically generated and should be regarded as a
571 # code template only.
572 # It will require modifications to work:
573 # - It may require correct/in-range values for request initialization.
574 # - It may require specifying regional endpoints when creating the service
575 # client as shown in:
576 # https://googleapis.dev/python/google-api-core/latest/client_options.html
577 from google.cloud import resourcemanager_v3
579 def sample_get_tag_key():
580 # Create a client
581 client = resourcemanager_v3.TagKeysClient()
583 # Initialize request argument(s)
584 request = resourcemanager_v3.GetTagKeyRequest(
585 name="name_value",
586 )
588 # Make the request
589 response = client.get_tag_key(request=request)
591 # Handle the response
592 print(response)
594 Args:
595 request (Union[google.cloud.resourcemanager_v3.types.GetTagKeyRequest, dict]):
596 The request object. The request message for getting a
597 TagKey.
598 name (str):
599 Required. A resource name in the format
600 ``tagKeys/{id}``, such as ``tagKeys/123``.
602 This corresponds to the ``name`` field
603 on the ``request`` instance; if ``request`` is provided, this
604 should not be set.
605 retry (google.api_core.retry.Retry): Designation of what errors, if any,
606 should be retried.
607 timeout (float): The timeout for this request.
608 metadata (Sequence[Tuple[str, str]]): Strings which should be
609 sent along with the request as metadata.
611 Returns:
612 google.cloud.resourcemanager_v3.types.TagKey:
613 A TagKey, used to group a set of
614 TagValues.
616 """
617 # Create or coerce a protobuf request object.
618 # Quick check: If we got a request object, we should *not* have
619 # gotten any keyword arguments that map to the request.
620 has_flattened_params = any([name])
621 if request is not None and has_flattened_params:
622 raise ValueError(
623 "If the `request` argument is set, then none of "
624 "the individual field arguments should be set."
625 )
627 # Minor optimization to avoid making a copy if the user passes
628 # in a tag_keys.GetTagKeyRequest.
629 # There's no risk of modifying the input as we've already verified
630 # there are no flattened fields.
631 if not isinstance(request, tag_keys.GetTagKeyRequest):
632 request = tag_keys.GetTagKeyRequest(request)
633 # If we have keyword arguments corresponding to fields on the
634 # request, apply these.
635 if name is not None:
636 request.name = name
638 # Wrap the RPC method; this adds retry and timeout information,
639 # and friendly error handling.
640 rpc = self._transport._wrapped_methods[self._transport.get_tag_key]
642 # Certain fields should be provided within the metadata header;
643 # add these here.
644 metadata = tuple(metadata) + (
645 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
646 )
648 # Send the request.
649 response = rpc(
650 request,
651 retry=retry,
652 timeout=timeout,
653 metadata=metadata,
654 )
656 # Done; return the response.
657 return response
659 def get_namespaced_tag_key(
660 self,
661 request: Optional[Union[tag_keys.GetNamespacedTagKeyRequest, dict]] = None,
662 *,
663 name: Optional[str] = None,
664 retry: OptionalRetry = gapic_v1.method.DEFAULT,
665 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
666 metadata: Sequence[Tuple[str, str]] = (),
667 ) -> tag_keys.TagKey:
668 r"""Retrieves a TagKey by its namespaced name. This method will
669 return ``PERMISSION_DENIED`` if the key does not exist or the
670 user does not have permission to view it.
672 .. code-block:: python
674 # This snippet has been automatically generated and should be regarded as a
675 # code template only.
676 # It will require modifications to work:
677 # - It may require correct/in-range values for request initialization.
678 # - It may require specifying regional endpoints when creating the service
679 # client as shown in:
680 # https://googleapis.dev/python/google-api-core/latest/client_options.html
681 from google.cloud import resourcemanager_v3
683 def sample_get_namespaced_tag_key():
684 # Create a client
685 client = resourcemanager_v3.TagKeysClient()
687 # Initialize request argument(s)
688 request = resourcemanager_v3.GetNamespacedTagKeyRequest(
689 name="name_value",
690 )
692 # Make the request
693 response = client.get_namespaced_tag_key(request=request)
695 # Handle the response
696 print(response)
698 Args:
699 request (Union[google.cloud.resourcemanager_v3.types.GetNamespacedTagKeyRequest, dict]):
700 The request object. The request message for getting a
701 TagKey by its namespaced name.
702 name (str):
703 Required. A namespaced tag key name in the format
704 ``{parentId}/{tagKeyShort}``, such as ``42/foo`` for a
705 key with short name "foo" under the organization with ID
706 42 or ``r2-d2/bar`` for a key with short name "bar"
707 under the project ``r2-d2``.
709 This corresponds to the ``name`` field
710 on the ``request`` instance; if ``request`` is provided, this
711 should not be set.
712 retry (google.api_core.retry.Retry): Designation of what errors, if any,
713 should be retried.
714 timeout (float): The timeout for this request.
715 metadata (Sequence[Tuple[str, str]]): Strings which should be
716 sent along with the request as metadata.
718 Returns:
719 google.cloud.resourcemanager_v3.types.TagKey:
720 A TagKey, used to group a set of
721 TagValues.
723 """
724 # Create or coerce a protobuf request object.
725 # Quick check: If we got a request object, we should *not* have
726 # gotten any keyword arguments that map to the request.
727 has_flattened_params = any([name])
728 if request is not None and has_flattened_params:
729 raise ValueError(
730 "If the `request` argument is set, then none of "
731 "the individual field arguments should be set."
732 )
734 # Minor optimization to avoid making a copy if the user passes
735 # in a tag_keys.GetNamespacedTagKeyRequest.
736 # There's no risk of modifying the input as we've already verified
737 # there are no flattened fields.
738 if not isinstance(request, tag_keys.GetNamespacedTagKeyRequest):
739 request = tag_keys.GetNamespacedTagKeyRequest(request)
740 # If we have keyword arguments corresponding to fields on the
741 # request, apply these.
742 if name is not None:
743 request.name = name
745 # Wrap the RPC method; this adds retry and timeout information,
746 # and friendly error handling.
747 rpc = self._transport._wrapped_methods[self._transport.get_namespaced_tag_key]
749 # Send the request.
750 response = rpc(
751 request,
752 retry=retry,
753 timeout=timeout,
754 metadata=metadata,
755 )
757 # Done; return the response.
758 return response
760 def create_tag_key(
761 self,
762 request: Optional[Union[tag_keys.CreateTagKeyRequest, dict]] = None,
763 *,
764 tag_key: Optional[tag_keys.TagKey] = None,
765 retry: OptionalRetry = gapic_v1.method.DEFAULT,
766 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
767 metadata: Sequence[Tuple[str, str]] = (),
768 ) -> operation.Operation:
769 r"""Creates a new TagKey. If another request with the
770 same parameters is sent while the original request is in
771 process, the second request will receive an error. A
772 maximum of 1000 TagKeys can exist under a parent at any
773 given time.
775 .. code-block:: python
777 # This snippet has been automatically generated and should be regarded as a
778 # code template only.
779 # It will require modifications to work:
780 # - It may require correct/in-range values for request initialization.
781 # - It may require specifying regional endpoints when creating the service
782 # client as shown in:
783 # https://googleapis.dev/python/google-api-core/latest/client_options.html
784 from google.cloud import resourcemanager_v3
786 def sample_create_tag_key():
787 # Create a client
788 client = resourcemanager_v3.TagKeysClient()
790 # Initialize request argument(s)
791 tag_key = resourcemanager_v3.TagKey()
792 tag_key.short_name = "short_name_value"
794 request = resourcemanager_v3.CreateTagKeyRequest(
795 tag_key=tag_key,
796 )
798 # Make the request
799 operation = client.create_tag_key(request=request)
801 print("Waiting for operation to complete...")
803 response = operation.result()
805 # Handle the response
806 print(response)
808 Args:
809 request (Union[google.cloud.resourcemanager_v3.types.CreateTagKeyRequest, dict]):
810 The request object. The request message for creating a
811 TagKey.
812 tag_key (google.cloud.resourcemanager_v3.types.TagKey):
813 Required. The TagKey to be created. Only fields
814 ``short_name``, ``description``, and ``parent`` are
815 considered during the creation request.
817 This corresponds to the ``tag_key`` field
818 on the ``request`` instance; if ``request`` is provided, this
819 should not be set.
820 retry (google.api_core.retry.Retry): Designation of what errors, if any,
821 should be retried.
822 timeout (float): The timeout for this request.
823 metadata (Sequence[Tuple[str, str]]): Strings which should be
824 sent along with the request as metadata.
826 Returns:
827 google.api_core.operation.Operation:
828 An object representing a long-running operation.
830 The result type for the operation will be
831 :class:`google.cloud.resourcemanager_v3.types.TagKey` A
832 TagKey, used to group a set of TagValues.
834 """
835 # Create or coerce a protobuf request object.
836 # Quick check: If we got a request object, we should *not* have
837 # gotten any keyword arguments that map to the request.
838 has_flattened_params = any([tag_key])
839 if request is not None and has_flattened_params:
840 raise ValueError(
841 "If the `request` argument is set, then none of "
842 "the individual field arguments should be set."
843 )
845 # Minor optimization to avoid making a copy if the user passes
846 # in a tag_keys.CreateTagKeyRequest.
847 # There's no risk of modifying the input as we've already verified
848 # there are no flattened fields.
849 if not isinstance(request, tag_keys.CreateTagKeyRequest):
850 request = tag_keys.CreateTagKeyRequest(request)
851 # If we have keyword arguments corresponding to fields on the
852 # request, apply these.
853 if tag_key is not None:
854 request.tag_key = tag_key
856 # Wrap the RPC method; this adds retry and timeout information,
857 # and friendly error handling.
858 rpc = self._transport._wrapped_methods[self._transport.create_tag_key]
860 # Send the request.
861 response = rpc(
862 request,
863 retry=retry,
864 timeout=timeout,
865 metadata=metadata,
866 )
868 # Wrap the response in an operation future.
869 response = operation.from_gapic(
870 response,
871 self._transport.operations_client,
872 tag_keys.TagKey,
873 metadata_type=tag_keys.CreateTagKeyMetadata,
874 )
876 # Done; return the response.
877 return response
879 def update_tag_key(
880 self,
881 request: Optional[Union[tag_keys.UpdateTagKeyRequest, dict]] = None,
882 *,
883 tag_key: Optional[tag_keys.TagKey] = None,
884 update_mask: Optional[field_mask_pb2.FieldMask] = None,
885 retry: OptionalRetry = gapic_v1.method.DEFAULT,
886 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
887 metadata: Sequence[Tuple[str, str]] = (),
888 ) -> operation.Operation:
889 r"""Updates the attributes of the TagKey resource.
891 .. code-block:: python
893 # This snippet has been automatically generated and should be regarded as a
894 # code template only.
895 # It will require modifications to work:
896 # - It may require correct/in-range values for request initialization.
897 # - It may require specifying regional endpoints when creating the service
898 # client as shown in:
899 # https://googleapis.dev/python/google-api-core/latest/client_options.html
900 from google.cloud import resourcemanager_v3
902 def sample_update_tag_key():
903 # Create a client
904 client = resourcemanager_v3.TagKeysClient()
906 # Initialize request argument(s)
907 tag_key = resourcemanager_v3.TagKey()
908 tag_key.short_name = "short_name_value"
910 request = resourcemanager_v3.UpdateTagKeyRequest(
911 tag_key=tag_key,
912 )
914 # Make the request
915 operation = client.update_tag_key(request=request)
917 print("Waiting for operation to complete...")
919 response = operation.result()
921 # Handle the response
922 print(response)
924 Args:
925 request (Union[google.cloud.resourcemanager_v3.types.UpdateTagKeyRequest, dict]):
926 The request object. The request message for updating a
927 TagKey.
928 tag_key (google.cloud.resourcemanager_v3.types.TagKey):
929 Required. The new definition of the TagKey. Only the
930 ``description`` and ``etag`` fields can be updated by
931 this request. If the ``etag`` field is not empty, it
932 must match the ``etag`` field of the existing tag key.
933 Otherwise, ``ABORTED`` will be returned.
935 This corresponds to the ``tag_key`` field
936 on the ``request`` instance; if ``request`` is provided, this
937 should not be set.
938 update_mask (google.protobuf.field_mask_pb2.FieldMask):
939 Fields to be updated. The mask may only contain
940 ``description`` or ``etag``. If omitted entirely, both
941 ``description`` and ``etag`` are assumed to be
942 significant.
944 This corresponds to the ``update_mask`` field
945 on the ``request`` instance; if ``request`` is provided, this
946 should not be set.
947 retry (google.api_core.retry.Retry): Designation of what errors, if any,
948 should be retried.
949 timeout (float): The timeout for this request.
950 metadata (Sequence[Tuple[str, str]]): Strings which should be
951 sent along with the request as metadata.
953 Returns:
954 google.api_core.operation.Operation:
955 An object representing a long-running operation.
957 The result type for the operation will be
958 :class:`google.cloud.resourcemanager_v3.types.TagKey` A
959 TagKey, used to group a set of TagValues.
961 """
962 # Create or coerce a protobuf request object.
963 # Quick check: If we got a request object, we should *not* have
964 # gotten any keyword arguments that map to the request.
965 has_flattened_params = any([tag_key, update_mask])
966 if request is not None and has_flattened_params:
967 raise ValueError(
968 "If the `request` argument is set, then none of "
969 "the individual field arguments should be set."
970 )
972 # Minor optimization to avoid making a copy if the user passes
973 # in a tag_keys.UpdateTagKeyRequest.
974 # There's no risk of modifying the input as we've already verified
975 # there are no flattened fields.
976 if not isinstance(request, tag_keys.UpdateTagKeyRequest):
977 request = tag_keys.UpdateTagKeyRequest(request)
978 # If we have keyword arguments corresponding to fields on the
979 # request, apply these.
980 if tag_key is not None:
981 request.tag_key = tag_key
982 if update_mask is not None:
983 request.update_mask = update_mask
985 # Wrap the RPC method; this adds retry and timeout information,
986 # and friendly error handling.
987 rpc = self._transport._wrapped_methods[self._transport.update_tag_key]
989 # Certain fields should be provided within the metadata header;
990 # add these here.
991 metadata = tuple(metadata) + (
992 gapic_v1.routing_header.to_grpc_metadata(
993 (("tag_key.name", request.tag_key.name),)
994 ),
995 )
997 # Send the request.
998 response = rpc(
999 request,
1000 retry=retry,
1001 timeout=timeout,
1002 metadata=metadata,
1003 )
1005 # Wrap the response in an operation future.
1006 response = operation.from_gapic(
1007 response,
1008 self._transport.operations_client,
1009 tag_keys.TagKey,
1010 metadata_type=tag_keys.UpdateTagKeyMetadata,
1011 )
1013 # Done; return the response.
1014 return response
1016 def delete_tag_key(
1017 self,
1018 request: Optional[Union[tag_keys.DeleteTagKeyRequest, dict]] = None,
1019 *,
1020 name: Optional[str] = None,
1021 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1022 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1023 metadata: Sequence[Tuple[str, str]] = (),
1024 ) -> operation.Operation:
1025 r"""Deletes a TagKey. The TagKey cannot be deleted if it
1026 has any child TagValues.
1028 .. code-block:: python
1030 # This snippet has been automatically generated and should be regarded as a
1031 # code template only.
1032 # It will require modifications to work:
1033 # - It may require correct/in-range values for request initialization.
1034 # - It may require specifying regional endpoints when creating the service
1035 # client as shown in:
1036 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1037 from google.cloud import resourcemanager_v3
1039 def sample_delete_tag_key():
1040 # Create a client
1041 client = resourcemanager_v3.TagKeysClient()
1043 # Initialize request argument(s)
1044 request = resourcemanager_v3.DeleteTagKeyRequest(
1045 name="name_value",
1046 )
1048 # Make the request
1049 operation = client.delete_tag_key(request=request)
1051 print("Waiting for operation to complete...")
1053 response = operation.result()
1055 # Handle the response
1056 print(response)
1058 Args:
1059 request (Union[google.cloud.resourcemanager_v3.types.DeleteTagKeyRequest, dict]):
1060 The request object. The request message for deleting a
1061 TagKey.
1062 name (str):
1063 Required. The resource name of a TagKey to be deleted in
1064 the format ``tagKeys/123``. The TagKey cannot be a
1065 parent of any existing TagValues or it will not be
1066 deleted successfully.
1068 This corresponds to the ``name`` field
1069 on the ``request`` instance; if ``request`` is provided, this
1070 should not be set.
1071 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1072 should be retried.
1073 timeout (float): The timeout for this request.
1074 metadata (Sequence[Tuple[str, str]]): Strings which should be
1075 sent along with the request as metadata.
1077 Returns:
1078 google.api_core.operation.Operation:
1079 An object representing a long-running operation.
1081 The result type for the operation will be
1082 :class:`google.cloud.resourcemanager_v3.types.TagKey` A
1083 TagKey, used to group a set of TagValues.
1085 """
1086 # Create or coerce a protobuf request object.
1087 # Quick check: If we got a request object, we should *not* have
1088 # gotten any keyword arguments that map to the request.
1089 has_flattened_params = any([name])
1090 if request is not None and has_flattened_params:
1091 raise ValueError(
1092 "If the `request` argument is set, then none of "
1093 "the individual field arguments should be set."
1094 )
1096 # Minor optimization to avoid making a copy if the user passes
1097 # in a tag_keys.DeleteTagKeyRequest.
1098 # There's no risk of modifying the input as we've already verified
1099 # there are no flattened fields.
1100 if not isinstance(request, tag_keys.DeleteTagKeyRequest):
1101 request = tag_keys.DeleteTagKeyRequest(request)
1102 # If we have keyword arguments corresponding to fields on the
1103 # request, apply these.
1104 if name is not None:
1105 request.name = name
1107 # Wrap the RPC method; this adds retry and timeout information,
1108 # and friendly error handling.
1109 rpc = self._transport._wrapped_methods[self._transport.delete_tag_key]
1111 # Certain fields should be provided within the metadata header;
1112 # add these here.
1113 metadata = tuple(metadata) + (
1114 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1115 )
1117 # Send the request.
1118 response = rpc(
1119 request,
1120 retry=retry,
1121 timeout=timeout,
1122 metadata=metadata,
1123 )
1125 # Wrap the response in an operation future.
1126 response = operation.from_gapic(
1127 response,
1128 self._transport.operations_client,
1129 tag_keys.TagKey,
1130 metadata_type=tag_keys.DeleteTagKeyMetadata,
1131 )
1133 # Done; return the response.
1134 return response
1136 def get_iam_policy(
1137 self,
1138 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
1139 *,
1140 resource: Optional[str] = None,
1141 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1142 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1143 metadata: Sequence[Tuple[str, str]] = (),
1144 ) -> policy_pb2.Policy:
1145 r"""Gets the access control policy for a TagKey. The returned policy
1146 may be empty if no such policy or resource exists. The
1147 ``resource`` field should be the TagKey's resource name. For
1148 example, "tagKeys/1234". The caller must have
1149 ``cloudresourcemanager.googleapis.com/tagKeys.getIamPolicy``
1150 permission on the specified TagKey.
1152 .. code-block:: python
1154 # This snippet has been automatically generated and should be regarded as a
1155 # code template only.
1156 # It will require modifications to work:
1157 # - It may require correct/in-range values for request initialization.
1158 # - It may require specifying regional endpoints when creating the service
1159 # client as shown in:
1160 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1161 from google.cloud import resourcemanager_v3
1162 from google.iam.v1 import iam_policy_pb2 # type: ignore
1164 def sample_get_iam_policy():
1165 # Create a client
1166 client = resourcemanager_v3.TagKeysClient()
1168 # Initialize request argument(s)
1169 request = iam_policy_pb2.GetIamPolicyRequest(
1170 resource="resource_value",
1171 )
1173 # Make the request
1174 response = client.get_iam_policy(request=request)
1176 # Handle the response
1177 print(response)
1179 Args:
1180 request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
1181 The request object. Request message for ``GetIamPolicy`` method.
1182 resource (str):
1183 REQUIRED: The resource for which the
1184 policy is being requested. See the
1185 operation documentation for the
1186 appropriate value for this field.
1188 This corresponds to the ``resource`` field
1189 on the ``request`` instance; if ``request`` is provided, this
1190 should not be set.
1191 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1192 should be retried.
1193 timeout (float): The timeout for this request.
1194 metadata (Sequence[Tuple[str, str]]): Strings which should be
1195 sent along with the request as metadata.
1197 Returns:
1198 google.iam.v1.policy_pb2.Policy:
1199 An Identity and Access Management (IAM) policy, which specifies access
1200 controls for Google Cloud resources.
1202 A Policy is a collection of bindings. A binding binds
1203 one or more members, or principals, to a single role.
1204 Principals can be user accounts, service accounts,
1205 Google groups, and domains (such as G Suite). A role
1206 is a named list of permissions; each role can be an
1207 IAM predefined role or a user-created custom role.
1209 For some types of Google Cloud resources, a binding
1210 can also specify a condition, which is a logical
1211 expression that allows access to a resource only if
1212 the expression evaluates to true. A condition can add
1213 constraints based on attributes of the request, the
1214 resource, or both. To learn which resources support
1215 conditions in their IAM policies, see the [IAM
1216 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1218 **JSON example:**
1220 {
1221 "bindings": [
1222 {
1223 "role":
1224 "roles/resourcemanager.organizationAdmin",
1225 "members": [ "user:mike@example.com",
1226 "group:admins@example.com",
1227 "domain:google.com",
1228 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1229 ]
1231 }, { "role":
1232 "roles/resourcemanager.organizationViewer",
1233 "members": [ "user:eve@example.com" ],
1234 "condition": { "title": "expirable access",
1235 "description": "Does not grant access after
1236 Sep 2020", "expression": "request.time <
1237 timestamp('2020-10-01T00:00:00.000Z')", } }
1239 ], "etag": "BwWWja0YfJA=", "version": 3
1241 }
1243 **YAML example:**
1245 bindings: - members: - user:\ mike@example.com -
1246 group:\ admins@example.com - domain:google.com -
1247 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
1248 role: roles/resourcemanager.organizationAdmin -
1249 members: - user:\ eve@example.com role:
1250 roles/resourcemanager.organizationViewer
1251 condition: title: expirable access description:
1252 Does not grant access after Sep 2020 expression:
1253 request.time <
1254 timestamp('2020-10-01T00:00:00.000Z') etag:
1255 BwWWja0YfJA= version: 3
1257 For a description of IAM and its features, see the
1258 [IAM
1259 documentation](\ https://cloud.google.com/iam/docs/).
1261 """
1262 # Create or coerce a protobuf request object.
1263 # Quick check: If we got a request object, we should *not* have
1264 # gotten any keyword arguments that map to the request.
1265 has_flattened_params = any([resource])
1266 if request is not None and has_flattened_params:
1267 raise ValueError(
1268 "If the `request` argument is set, then none of "
1269 "the individual field arguments should be set."
1270 )
1272 if isinstance(request, dict):
1273 # The request isn't a proto-plus wrapped type,
1274 # so it must be constructed via keyword expansion.
1275 request = iam_policy_pb2.GetIamPolicyRequest(**request)
1276 elif not request:
1277 # Null request, just make one.
1278 request = iam_policy_pb2.GetIamPolicyRequest()
1279 if resource is not None:
1280 request.resource = resource
1282 # Wrap the RPC method; this adds retry and timeout information,
1283 # and friendly error handling.
1284 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
1286 # Certain fields should be provided within the metadata header;
1287 # add these here.
1288 metadata = tuple(metadata) + (
1289 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1290 )
1292 # Send the request.
1293 response = rpc(
1294 request,
1295 retry=retry,
1296 timeout=timeout,
1297 metadata=metadata,
1298 )
1300 # Done; return the response.
1301 return response
1303 def set_iam_policy(
1304 self,
1305 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
1306 *,
1307 resource: Optional[str] = None,
1308 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1309 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1310 metadata: Sequence[Tuple[str, str]] = (),
1311 ) -> policy_pb2.Policy:
1312 r"""Sets the access control policy on a TagKey, replacing any
1313 existing policy. The ``resource`` field should be the TagKey's
1314 resource name. For example, "tagKeys/1234". The caller must have
1315 ``resourcemanager.tagKeys.setIamPolicy`` permission on the
1316 identified tagValue.
1318 .. code-block:: python
1320 # This snippet has been automatically generated and should be regarded as a
1321 # code template only.
1322 # It will require modifications to work:
1323 # - It may require correct/in-range values for request initialization.
1324 # - It may require specifying regional endpoints when creating the service
1325 # client as shown in:
1326 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1327 from google.cloud import resourcemanager_v3
1328 from google.iam.v1 import iam_policy_pb2 # type: ignore
1330 def sample_set_iam_policy():
1331 # Create a client
1332 client = resourcemanager_v3.TagKeysClient()
1334 # Initialize request argument(s)
1335 request = iam_policy_pb2.SetIamPolicyRequest(
1336 resource="resource_value",
1337 )
1339 # Make the request
1340 response = client.set_iam_policy(request=request)
1342 # Handle the response
1343 print(response)
1345 Args:
1346 request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
1347 The request object. Request message for ``SetIamPolicy`` method.
1348 resource (str):
1349 REQUIRED: The resource for which the
1350 policy is being specified. See the
1351 operation documentation for the
1352 appropriate value for this field.
1354 This corresponds to the ``resource`` field
1355 on the ``request`` instance; if ``request`` is provided, this
1356 should not be set.
1357 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1358 should be retried.
1359 timeout (float): The timeout for this request.
1360 metadata (Sequence[Tuple[str, str]]): Strings which should be
1361 sent along with the request as metadata.
1363 Returns:
1364 google.iam.v1.policy_pb2.Policy:
1365 An Identity and Access Management (IAM) policy, which specifies access
1366 controls for Google Cloud resources.
1368 A Policy is a collection of bindings. A binding binds
1369 one or more members, or principals, to a single role.
1370 Principals can be user accounts, service accounts,
1371 Google groups, and domains (such as G Suite). A role
1372 is a named list of permissions; each role can be an
1373 IAM predefined role or a user-created custom role.
1375 For some types of Google Cloud resources, a binding
1376 can also specify a condition, which is a logical
1377 expression that allows access to a resource only if
1378 the expression evaluates to true. A condition can add
1379 constraints based on attributes of the request, the
1380 resource, or both. To learn which resources support
1381 conditions in their IAM policies, see the [IAM
1382 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1384 **JSON example:**
1386 {
1387 "bindings": [
1388 {
1389 "role":
1390 "roles/resourcemanager.organizationAdmin",
1391 "members": [ "user:mike@example.com",
1392 "group:admins@example.com",
1393 "domain:google.com",
1394 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1395 ]
1397 }, { "role":
1398 "roles/resourcemanager.organizationViewer",
1399 "members": [ "user:eve@example.com" ],
1400 "condition": { "title": "expirable access",
1401 "description": "Does not grant access after
1402 Sep 2020", "expression": "request.time <
1403 timestamp('2020-10-01T00:00:00.000Z')", } }
1405 ], "etag": "BwWWja0YfJA=", "version": 3
1407 }
1409 **YAML example:**
1411 bindings: - members: - user:\ mike@example.com -
1412 group:\ admins@example.com - domain:google.com -
1413 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
1414 role: roles/resourcemanager.organizationAdmin -
1415 members: - user:\ eve@example.com role:
1416 roles/resourcemanager.organizationViewer
1417 condition: title: expirable access description:
1418 Does not grant access after Sep 2020 expression:
1419 request.time <
1420 timestamp('2020-10-01T00:00:00.000Z') etag:
1421 BwWWja0YfJA= version: 3
1423 For a description of IAM and its features, see the
1424 [IAM
1425 documentation](\ https://cloud.google.com/iam/docs/).
1427 """
1428 # Create or coerce a protobuf request object.
1429 # Quick check: If we got a request object, we should *not* have
1430 # gotten any keyword arguments that map to the request.
1431 has_flattened_params = any([resource])
1432 if request is not None and has_flattened_params:
1433 raise ValueError(
1434 "If the `request` argument is set, then none of "
1435 "the individual field arguments should be set."
1436 )
1438 if isinstance(request, dict):
1439 # The request isn't a proto-plus wrapped type,
1440 # so it must be constructed via keyword expansion.
1441 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1442 elif not request:
1443 # Null request, just make one.
1444 request = iam_policy_pb2.SetIamPolicyRequest()
1445 if resource is not None:
1446 request.resource = resource
1448 # Wrap the RPC method; this adds retry and timeout information,
1449 # and friendly error handling.
1450 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
1452 # Certain fields should be provided within the metadata header;
1453 # add these here.
1454 metadata = tuple(metadata) + (
1455 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1456 )
1458 # Send the request.
1459 response = rpc(
1460 request,
1461 retry=retry,
1462 timeout=timeout,
1463 metadata=metadata,
1464 )
1466 # Done; return the response.
1467 return response
1469 def test_iam_permissions(
1470 self,
1471 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None,
1472 *,
1473 resource: Optional[str] = None,
1474 permissions: Optional[MutableSequence[str]] = None,
1475 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1476 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1477 metadata: Sequence[Tuple[str, str]] = (),
1478 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1479 r"""Returns permissions that a caller has on the specified TagKey.
1480 The ``resource`` field should be the TagKey's resource name. For
1481 example, "tagKeys/1234".
1483 There are no permissions required for making this API call.
1485 .. code-block:: python
1487 # This snippet has been automatically generated and should be regarded as a
1488 # code template only.
1489 # It will require modifications to work:
1490 # - It may require correct/in-range values for request initialization.
1491 # - It may require specifying regional endpoints when creating the service
1492 # client as shown in:
1493 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1494 from google.cloud import resourcemanager_v3
1495 from google.iam.v1 import iam_policy_pb2 # type: ignore
1497 def sample_test_iam_permissions():
1498 # Create a client
1499 client = resourcemanager_v3.TagKeysClient()
1501 # Initialize request argument(s)
1502 request = iam_policy_pb2.TestIamPermissionsRequest(
1503 resource="resource_value",
1504 permissions=['permissions_value1', 'permissions_value2'],
1505 )
1507 # Make the request
1508 response = client.test_iam_permissions(request=request)
1510 # Handle the response
1511 print(response)
1513 Args:
1514 request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]):
1515 The request object. Request message for ``TestIamPermissions`` method.
1516 resource (str):
1517 REQUIRED: The resource for which the
1518 policy detail is being requested. See
1519 the operation documentation for the
1520 appropriate value for this field.
1522 This corresponds to the ``resource`` field
1523 on the ``request`` instance; if ``request`` is provided, this
1524 should not be set.
1525 permissions (MutableSequence[str]):
1526 The set of permissions to check for the ``resource``.
1527 Permissions with wildcards (such as '*' or 'storage.*')
1528 are not allowed. For more information see `IAM
1529 Overview <https://cloud.google.com/iam/docs/overview#permissions>`__.
1531 This corresponds to the ``permissions`` field
1532 on the ``request`` instance; if ``request`` is provided, this
1533 should not be set.
1534 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1535 should be retried.
1536 timeout (float): The timeout for this request.
1537 metadata (Sequence[Tuple[str, str]]): Strings which should be
1538 sent along with the request as metadata.
1540 Returns:
1541 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
1542 Response message for TestIamPermissions method.
1543 """
1544 # Create or coerce a protobuf request object.
1545 # Quick check: If we got a request object, we should *not* have
1546 # gotten any keyword arguments that map to the request.
1547 has_flattened_params = any([resource, permissions])
1548 if request is not None and has_flattened_params:
1549 raise ValueError(
1550 "If the `request` argument is set, then none of "
1551 "the individual field arguments should be set."
1552 )
1554 if isinstance(request, dict):
1555 # The request isn't a proto-plus wrapped type,
1556 # so it must be constructed via keyword expansion.
1557 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
1558 elif not request:
1559 # Null request, just make one.
1560 request = iam_policy_pb2.TestIamPermissionsRequest()
1561 if resource is not None:
1562 request.resource = resource
1563 if permissions:
1564 request.permissions.extend(permissions)
1566 # Wrap the RPC method; this adds retry and timeout information,
1567 # and friendly error handling.
1568 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
1570 # Certain fields should be provided within the metadata header;
1571 # add these here.
1572 metadata = tuple(metadata) + (
1573 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1574 )
1576 # Send the request.
1577 response = rpc(
1578 request,
1579 retry=retry,
1580 timeout=timeout,
1581 metadata=metadata,
1582 )
1584 # Done; return the response.
1585 return response
1587 def __enter__(self) -> "TagKeysClient":
1588 return self
1590 def __exit__(self, type, value, traceback):
1591 """Releases underlying transport's resources.
1593 .. warning::
1594 ONLY use as a context manager if the transport is NOT shared
1595 with other clients! Exiting the with block will CLOSE the transport
1596 and may cause errors in other clients!
1597 """
1598 self.transport.close()
1600 def get_operation(
1601 self,
1602 request: Optional[operations_pb2.GetOperationRequest] = None,
1603 *,
1604 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1605 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1606 metadata: Sequence[Tuple[str, str]] = (),
1607 ) -> operations_pb2.Operation:
1608 r"""Gets the latest state of a long-running operation.
1610 Args:
1611 request (:class:`~.operations_pb2.GetOperationRequest`):
1612 The request object. Request message for
1613 `GetOperation` method.
1614 retry (google.api_core.retry.Retry): Designation of what errors,
1615 if any, should be retried.
1616 timeout (float): The timeout for this request.
1617 metadata (Sequence[Tuple[str, str]]): Strings which should be
1618 sent along with the request as metadata.
1619 Returns:
1620 ~.operations_pb2.Operation:
1621 An ``Operation`` object.
1622 """
1623 # Create or coerce a protobuf request object.
1624 # The request isn't a proto-plus wrapped type,
1625 # so it must be constructed via keyword expansion.
1626 if isinstance(request, dict):
1627 request = operations_pb2.GetOperationRequest(**request)
1629 # Wrap the RPC method; this adds retry and timeout information,
1630 # and friendly error handling.
1631 rpc = gapic_v1.method.wrap_method(
1632 self._transport.get_operation,
1633 default_timeout=None,
1634 client_info=DEFAULT_CLIENT_INFO,
1635 )
1637 # Certain fields should be provided within the metadata header;
1638 # add these here.
1639 metadata = tuple(metadata) + (
1640 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1641 )
1643 # Send the request.
1644 response = rpc(
1645 request,
1646 retry=retry,
1647 timeout=timeout,
1648 metadata=metadata,
1649 )
1651 # Done; return the response.
1652 return response
1655DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1656 gapic_version=package_version.__version__
1657)
1660__all__ = ("TagKeysClient",)