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)
31
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
41
42from google.cloud.resourcemanager_v3 import gapic_version as package_version
43
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
48
49from google.iam.v1 import iam_policy_pb2 # type: ignore
50from google.iam.v1 import policy_pb2 # type: ignore
51from google.longrunning import operations_pb2
52from google.protobuf import timestamp_pb2 # type: ignore
53
54from google.cloud.resourcemanager_v3.services.organizations import pagers
55from google.cloud.resourcemanager_v3.types import organizations
56
57from .transports.base import DEFAULT_CLIENT_INFO, OrganizationsTransport
58from .transports.grpc import OrganizationsGrpcTransport
59from .transports.grpc_asyncio import OrganizationsGrpcAsyncIOTransport
60from .transports.rest import OrganizationsRestTransport
61
62
63class OrganizationsClientMeta(type):
64 """Metaclass for the Organizations client.
65
66 This provides class-level methods for building and retrieving
67 support objects (e.g. transport) without polluting the client instance
68 objects.
69 """
70
71 _transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationsTransport]]
72 _transport_registry["grpc"] = OrganizationsGrpcTransport
73 _transport_registry["grpc_asyncio"] = OrganizationsGrpcAsyncIOTransport
74 _transport_registry["rest"] = OrganizationsRestTransport
75
76 def get_transport_class(
77 cls,
78 label: Optional[str] = None,
79 ) -> Type[OrganizationsTransport]:
80 """Returns an appropriate transport class.
81
82 Args:
83 label: The name of the desired transport. If none is
84 provided, then the first transport in the registry is used.
85
86 Returns:
87 The transport class to use.
88 """
89 # If a specific transport is requested, return that one.
90 if label:
91 return cls._transport_registry[label]
92
93 # No transport is requested; return the default (that is, the first one
94 # in the dictionary).
95 return next(iter(cls._transport_registry.values()))
96
97
98class OrganizationsClient(metaclass=OrganizationsClientMeta):
99 """Allows users to manage their organization resources."""
100
101 @staticmethod
102 def _get_default_mtls_endpoint(api_endpoint):
103 """Converts api endpoint to mTLS endpoint.
104
105 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
106 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
107 Args:
108 api_endpoint (Optional[str]): the api endpoint to convert.
109 Returns:
110 str: converted mTLS api endpoint.
111 """
112 if not api_endpoint:
113 return api_endpoint
114
115 mtls_endpoint_re = re.compile(
116 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
117 )
118
119 m = mtls_endpoint_re.match(api_endpoint)
120 name, mtls, sandbox, googledomain = m.groups()
121 if mtls or not googledomain:
122 return api_endpoint
123
124 if sandbox:
125 return api_endpoint.replace(
126 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
127 )
128
129 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
130
131 DEFAULT_ENDPOINT = "cloudresourcemanager.googleapis.com"
132 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
133 DEFAULT_ENDPOINT
134 )
135
136 @classmethod
137 def from_service_account_info(cls, info: dict, *args, **kwargs):
138 """Creates an instance of this client using the provided credentials
139 info.
140
141 Args:
142 info (dict): The service account private key info.
143 args: Additional arguments to pass to the constructor.
144 kwargs: Additional arguments to pass to the constructor.
145
146 Returns:
147 OrganizationsClient: The constructed client.
148 """
149 credentials = service_account.Credentials.from_service_account_info(info)
150 kwargs["credentials"] = credentials
151 return cls(*args, **kwargs)
152
153 @classmethod
154 def from_service_account_file(cls, filename: str, *args, **kwargs):
155 """Creates an instance of this client using the provided credentials
156 file.
157
158 Args:
159 filename (str): The path to the service account private key json
160 file.
161 args: Additional arguments to pass to the constructor.
162 kwargs: Additional arguments to pass to the constructor.
163
164 Returns:
165 OrganizationsClient: The constructed client.
166 """
167 credentials = service_account.Credentials.from_service_account_file(filename)
168 kwargs["credentials"] = credentials
169 return cls(*args, **kwargs)
170
171 from_service_account_json = from_service_account_file
172
173 @property
174 def transport(self) -> OrganizationsTransport:
175 """Returns the transport used by the client instance.
176
177 Returns:
178 OrganizationsTransport: The transport used by the client
179 instance.
180 """
181 return self._transport
182
183 @staticmethod
184 def organization_path(
185 organization: str,
186 ) -> str:
187 """Returns a fully-qualified organization string."""
188 return "organizations/{organization}".format(
189 organization=organization,
190 )
191
192 @staticmethod
193 def parse_organization_path(path: str) -> Dict[str, str]:
194 """Parses a organization path into its component segments."""
195 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
196 return m.groupdict() if m else {}
197
198 @staticmethod
199 def common_billing_account_path(
200 billing_account: str,
201 ) -> str:
202 """Returns a fully-qualified billing_account string."""
203 return "billingAccounts/{billing_account}".format(
204 billing_account=billing_account,
205 )
206
207 @staticmethod
208 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
209 """Parse a billing_account path into its component segments."""
210 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
211 return m.groupdict() if m else {}
212
213 @staticmethod
214 def common_folder_path(
215 folder: str,
216 ) -> str:
217 """Returns a fully-qualified folder string."""
218 return "folders/{folder}".format(
219 folder=folder,
220 )
221
222 @staticmethod
223 def parse_common_folder_path(path: str) -> Dict[str, str]:
224 """Parse a folder path into its component segments."""
225 m = re.match(r"^folders/(?P<folder>.+?)$", path)
226 return m.groupdict() if m else {}
227
228 @staticmethod
229 def common_organization_path(
230 organization: str,
231 ) -> str:
232 """Returns a fully-qualified organization string."""
233 return "organizations/{organization}".format(
234 organization=organization,
235 )
236
237 @staticmethod
238 def parse_common_organization_path(path: str) -> Dict[str, str]:
239 """Parse a organization path into its component segments."""
240 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
241 return m.groupdict() if m else {}
242
243 @staticmethod
244 def common_project_path(
245 project: str,
246 ) -> str:
247 """Returns a fully-qualified project string."""
248 return "projects/{project}".format(
249 project=project,
250 )
251
252 @staticmethod
253 def parse_common_project_path(path: str) -> Dict[str, str]:
254 """Parse a project path into its component segments."""
255 m = re.match(r"^projects/(?P<project>.+?)$", path)
256 return m.groupdict() if m else {}
257
258 @staticmethod
259 def common_location_path(
260 project: str,
261 location: str,
262 ) -> str:
263 """Returns a fully-qualified location string."""
264 return "projects/{project}/locations/{location}".format(
265 project=project,
266 location=location,
267 )
268
269 @staticmethod
270 def parse_common_location_path(path: str) -> Dict[str, str]:
271 """Parse a location path into its component segments."""
272 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
273 return m.groupdict() if m else {}
274
275 @classmethod
276 def get_mtls_endpoint_and_cert_source(
277 cls, client_options: Optional[client_options_lib.ClientOptions] = None
278 ):
279 """Return the API endpoint and client cert source for mutual TLS.
280
281 The client cert source is determined in the following order:
282 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
283 client cert source is None.
284 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
285 default client cert source exists, use the default one; otherwise the client cert
286 source is None.
287
288 The API endpoint is determined in the following order:
289 (1) if `client_options.api_endpoint` if provided, use the provided one.
290 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
291 default mTLS endpoint; if the environment variable is "never", use the default API
292 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
293 use the default API endpoint.
294
295 More details can be found at https://google.aip.dev/auth/4114.
296
297 Args:
298 client_options (google.api_core.client_options.ClientOptions): Custom options for the
299 client. Only the `api_endpoint` and `client_cert_source` properties may be used
300 in this method.
301
302 Returns:
303 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
304 client cert source to use.
305
306 Raises:
307 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
308 """
309 if client_options is None:
310 client_options = client_options_lib.ClientOptions()
311 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
312 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
313 if use_client_cert not in ("true", "false"):
314 raise ValueError(
315 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
316 )
317 if use_mtls_endpoint not in ("auto", "never", "always"):
318 raise MutualTLSChannelError(
319 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
320 )
321
322 # Figure out the client cert source to use.
323 client_cert_source = None
324 if use_client_cert == "true":
325 if client_options.client_cert_source:
326 client_cert_source = client_options.client_cert_source
327 elif mtls.has_default_client_cert_source():
328 client_cert_source = mtls.default_client_cert_source()
329
330 # Figure out which api endpoint to use.
331 if client_options.api_endpoint is not None:
332 api_endpoint = client_options.api_endpoint
333 elif use_mtls_endpoint == "always" or (
334 use_mtls_endpoint == "auto" and client_cert_source
335 ):
336 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
337 else:
338 api_endpoint = cls.DEFAULT_ENDPOINT
339
340 return api_endpoint, client_cert_source
341
342 def __init__(
343 self,
344 *,
345 credentials: Optional[ga_credentials.Credentials] = None,
346 transport: Optional[Union[str, OrganizationsTransport]] = None,
347 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
348 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
349 ) -> None:
350 """Instantiates the organizations client.
351
352 Args:
353 credentials (Optional[google.auth.credentials.Credentials]): The
354 authorization credentials to attach to requests. These
355 credentials identify the application to the service; if none
356 are specified, the client will attempt to ascertain the
357 credentials from the environment.
358 transport (Union[str, OrganizationsTransport]): The
359 transport to use. If set to None, a transport is chosen
360 automatically.
361 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
362 client. It won't take effect if a ``transport`` instance is provided.
363 (1) The ``api_endpoint`` property can be used to override the
364 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
365 environment variable can also be used to override the endpoint:
366 "always" (always use the default mTLS endpoint), "never" (always
367 use the default regular endpoint) and "auto" (auto switch to the
368 default mTLS endpoint if client certificate is present, this is
369 the default value). However, the ``api_endpoint`` property takes
370 precedence if provided.
371 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
372 is "true", then the ``client_cert_source`` property can be used
373 to provide client certificate for mutual TLS transport. If
374 not provided, the default SSL client certificate will be used if
375 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
376 set, no client certificate will be used.
377 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
378 The client info used to send a user-agent string along with
379 API requests. If ``None``, then default info will be used.
380 Generally, you only need to set this if you're developing
381 your own client library.
382
383 Raises:
384 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
385 creation failed for any reason.
386 """
387 if isinstance(client_options, dict):
388 client_options = client_options_lib.from_dict(client_options)
389 if client_options is None:
390 client_options = client_options_lib.ClientOptions()
391 client_options = cast(client_options_lib.ClientOptions, client_options)
392
393 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
394 client_options
395 )
396
397 api_key_value = getattr(client_options, "api_key", None)
398 if api_key_value and credentials:
399 raise ValueError(
400 "client_options.api_key and credentials are mutually exclusive"
401 )
402
403 # Save or instantiate the transport.
404 # Ordinarily, we provide the transport, but allowing a custom transport
405 # instance provides an extensibility point for unusual situations.
406 if isinstance(transport, OrganizationsTransport):
407 # transport is a OrganizationsTransport instance.
408 if credentials or client_options.credentials_file or api_key_value:
409 raise ValueError(
410 "When providing a transport instance, "
411 "provide its credentials directly."
412 )
413 if client_options.scopes:
414 raise ValueError(
415 "When providing a transport instance, provide its scopes "
416 "directly."
417 )
418 self._transport = transport
419 else:
420 import google.auth._default # type: ignore
421
422 if api_key_value and hasattr(
423 google.auth._default, "get_api_key_credentials"
424 ):
425 credentials = google.auth._default.get_api_key_credentials(
426 api_key_value
427 )
428
429 Transport = type(self).get_transport_class(transport)
430 self._transport = Transport(
431 credentials=credentials,
432 credentials_file=client_options.credentials_file,
433 host=api_endpoint,
434 scopes=client_options.scopes,
435 client_cert_source_for_mtls=client_cert_source_func,
436 quota_project_id=client_options.quota_project_id,
437 client_info=client_info,
438 always_use_jwt_access=True,
439 api_audience=client_options.api_audience,
440 )
441
442 def get_organization(
443 self,
444 request: Optional[Union[organizations.GetOrganizationRequest, dict]] = None,
445 *,
446 name: Optional[str] = None,
447 retry: OptionalRetry = gapic_v1.method.DEFAULT,
448 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
449 metadata: Sequence[Tuple[str, str]] = (),
450 ) -> organizations.Organization:
451 r"""Fetches an organization resource identified by the
452 specified resource name.
453
454 .. code-block:: python
455
456 # This snippet has been automatically generated and should be regarded as a
457 # code template only.
458 # It will require modifications to work:
459 # - It may require correct/in-range values for request initialization.
460 # - It may require specifying regional endpoints when creating the service
461 # client as shown in:
462 # https://googleapis.dev/python/google-api-core/latest/client_options.html
463 from google.cloud import resourcemanager_v3
464
465 def sample_get_organization():
466 # Create a client
467 client = resourcemanager_v3.OrganizationsClient()
468
469 # Initialize request argument(s)
470 request = resourcemanager_v3.GetOrganizationRequest(
471 name="name_value",
472 )
473
474 # Make the request
475 response = client.get_organization(request=request)
476
477 # Handle the response
478 print(response)
479
480 Args:
481 request (Union[google.cloud.resourcemanager_v3.types.GetOrganizationRequest, dict]):
482 The request object. The request sent to the ``GetOrganization`` method. The
483 ``name`` field is required. ``organization_id`` is no
484 longer accepted.
485 name (str):
486 Required. The resource name of the Organization to
487 fetch. This is the organization's relative path in the
488 API, formatted as "organizations/[organizationId]". For
489 example, "organizations/1234".
490
491 This corresponds to the ``name`` field
492 on the ``request`` instance; if ``request`` is provided, this
493 should not be set.
494 retry (google.api_core.retry.Retry): Designation of what errors, if any,
495 should be retried.
496 timeout (float): The timeout for this request.
497 metadata (Sequence[Tuple[str, str]]): Strings which should be
498 sent along with the request as metadata.
499
500 Returns:
501 google.cloud.resourcemanager_v3.types.Organization:
502 The root node in the resource
503 hierarchy to which a particular entity's
504 (a company, for example) resources
505 belong.
506
507 """
508 # Create or coerce a protobuf request object.
509 # Quick check: If we got a request object, we should *not* have
510 # gotten any keyword arguments that map to the request.
511 has_flattened_params = any([name])
512 if request is not None and has_flattened_params:
513 raise ValueError(
514 "If the `request` argument is set, then none of "
515 "the individual field arguments should be set."
516 )
517
518 # Minor optimization to avoid making a copy if the user passes
519 # in a organizations.GetOrganizationRequest.
520 # There's no risk of modifying the input as we've already verified
521 # there are no flattened fields.
522 if not isinstance(request, organizations.GetOrganizationRequest):
523 request = organizations.GetOrganizationRequest(request)
524 # If we have keyword arguments corresponding to fields on the
525 # request, apply these.
526 if name is not None:
527 request.name = name
528
529 # Wrap the RPC method; this adds retry and timeout information,
530 # and friendly error handling.
531 rpc = self._transport._wrapped_methods[self._transport.get_organization]
532
533 # Certain fields should be provided within the metadata header;
534 # add these here.
535 metadata = tuple(metadata) + (
536 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
537 )
538
539 # Send the request.
540 response = rpc(
541 request,
542 retry=retry,
543 timeout=timeout,
544 metadata=metadata,
545 )
546
547 # Done; return the response.
548 return response
549
550 def search_organizations(
551 self,
552 request: Optional[Union[organizations.SearchOrganizationsRequest, dict]] = None,
553 *,
554 query: Optional[str] = None,
555 retry: OptionalRetry = gapic_v1.method.DEFAULT,
556 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
557 metadata: Sequence[Tuple[str, str]] = (),
558 ) -> pagers.SearchOrganizationsPager:
559 r"""Searches organization resources that are visible to the user and
560 satisfy the specified filter. This method returns organizations
561 in an unspecified order. New organizations do not necessarily
562 appear at the end of the results, and may take a small amount of
563 time to appear.
564
565 Search will only return organizations on which the user has the
566 permission ``resourcemanager.organizations.get``
567
568 .. code-block:: python
569
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
578
579 def sample_search_organizations():
580 # Create a client
581 client = resourcemanager_v3.OrganizationsClient()
582
583 # Initialize request argument(s)
584 request = resourcemanager_v3.SearchOrganizationsRequest(
585 )
586
587 # Make the request
588 page_result = client.search_organizations(request=request)
589
590 # Handle the response
591 for response in page_result:
592 print(response)
593
594 Args:
595 request (Union[google.cloud.resourcemanager_v3.types.SearchOrganizationsRequest, dict]):
596 The request object. The request sent to the ``SearchOrganizations`` method.
597 query (str):
598 Optional. An optional query string used to filter the
599 Organizations to return in the response. Query rules are
600 case-insensitive.
601
602 ::
603
604 | Field | Description |
605 |------------------|--------------------------------------------|
606 | directoryCustomerId, owner.directoryCustomerId | Filters by directory
607 customer id. |
608 | domain | Filters by domain. |
609
610 Organizations may be queried by ``directoryCustomerId``
611 or by ``domain``, where the domain is a G Suite domain,
612 for example:
613
614 - Query ``directorycustomerid:123456789`` returns
615 Organization resources with
616 ``owner.directory_customer_id`` equal to
617 ``123456789``.
618 - Query ``domain:google.com`` returns Organization
619 resources corresponding to the domain ``google.com``.
620
621 This corresponds to the ``query`` field
622 on the ``request`` instance; if ``request`` is provided, this
623 should not be set.
624 retry (google.api_core.retry.Retry): Designation of what errors, if any,
625 should be retried.
626 timeout (float): The timeout for this request.
627 metadata (Sequence[Tuple[str, str]]): Strings which should be
628 sent along with the request as metadata.
629
630 Returns:
631 google.cloud.resourcemanager_v3.services.organizations.pagers.SearchOrganizationsPager:
632 The response returned from the SearchOrganizations
633 method.
634
635 Iterating over this object will yield results and
636 resolve additional pages automatically.
637
638 """
639 # Create or coerce a protobuf request object.
640 # Quick check: If we got a request object, we should *not* have
641 # gotten any keyword arguments that map to the request.
642 has_flattened_params = any([query])
643 if request is not None and has_flattened_params:
644 raise ValueError(
645 "If the `request` argument is set, then none of "
646 "the individual field arguments should be set."
647 )
648
649 # Minor optimization to avoid making a copy if the user passes
650 # in a organizations.SearchOrganizationsRequest.
651 # There's no risk of modifying the input as we've already verified
652 # there are no flattened fields.
653 if not isinstance(request, organizations.SearchOrganizationsRequest):
654 request = organizations.SearchOrganizationsRequest(request)
655 # If we have keyword arguments corresponding to fields on the
656 # request, apply these.
657 if query is not None:
658 request.query = query
659
660 # Wrap the RPC method; this adds retry and timeout information,
661 # and friendly error handling.
662 rpc = self._transport._wrapped_methods[self._transport.search_organizations]
663
664 # Send the request.
665 response = rpc(
666 request,
667 retry=retry,
668 timeout=timeout,
669 metadata=metadata,
670 )
671
672 # This method is paged; wrap the response in a pager, which provides
673 # an `__iter__` convenience method.
674 response = pagers.SearchOrganizationsPager(
675 method=rpc,
676 request=request,
677 response=response,
678 metadata=metadata,
679 )
680
681 # Done; return the response.
682 return response
683
684 def get_iam_policy(
685 self,
686 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
687 *,
688 resource: Optional[str] = None,
689 retry: OptionalRetry = gapic_v1.method.DEFAULT,
690 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
691 metadata: Sequence[Tuple[str, str]] = (),
692 ) -> policy_pb2.Policy:
693 r"""Gets the access control policy for an organization resource. The
694 policy may be empty if no such policy or resource exists. The
695 ``resource`` field should be the organization's resource name,
696 for example: "organizations/123".
697
698 Authorization requires the IAM permission
699 ``resourcemanager.organizations.getIamPolicy`` on the specified
700 organization.
701
702 .. code-block:: python
703
704 # This snippet has been automatically generated and should be regarded as a
705 # code template only.
706 # It will require modifications to work:
707 # - It may require correct/in-range values for request initialization.
708 # - It may require specifying regional endpoints when creating the service
709 # client as shown in:
710 # https://googleapis.dev/python/google-api-core/latest/client_options.html
711 from google.cloud import resourcemanager_v3
712 from google.iam.v1 import iam_policy_pb2 # type: ignore
713
714 def sample_get_iam_policy():
715 # Create a client
716 client = resourcemanager_v3.OrganizationsClient()
717
718 # Initialize request argument(s)
719 request = iam_policy_pb2.GetIamPolicyRequest(
720 resource="resource_value",
721 )
722
723 # Make the request
724 response = client.get_iam_policy(request=request)
725
726 # Handle the response
727 print(response)
728
729 Args:
730 request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
731 The request object. Request message for ``GetIamPolicy`` method.
732 resource (str):
733 REQUIRED: The resource for which the
734 policy is being requested. See the
735 operation documentation for the
736 appropriate value for this field.
737
738 This corresponds to the ``resource`` field
739 on the ``request`` instance; if ``request`` is provided, this
740 should not be set.
741 retry (google.api_core.retry.Retry): Designation of what errors, if any,
742 should be retried.
743 timeout (float): The timeout for this request.
744 metadata (Sequence[Tuple[str, str]]): Strings which should be
745 sent along with the request as metadata.
746
747 Returns:
748 google.iam.v1.policy_pb2.Policy:
749 An Identity and Access Management (IAM) policy, which specifies access
750 controls for Google Cloud resources.
751
752 A Policy is a collection of bindings. A binding binds
753 one or more members, or principals, to a single role.
754 Principals can be user accounts, service accounts,
755 Google groups, and domains (such as G Suite). A role
756 is a named list of permissions; each role can be an
757 IAM predefined role or a user-created custom role.
758
759 For some types of Google Cloud resources, a binding
760 can also specify a condition, which is a logical
761 expression that allows access to a resource only if
762 the expression evaluates to true. A condition can add
763 constraints based on attributes of the request, the
764 resource, or both. To learn which resources support
765 conditions in their IAM policies, see the [IAM
766 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
767
768 **JSON example:**
769
770 {
771 "bindings": [
772 {
773 "role":
774 "roles/resourcemanager.organizationAdmin",
775 "members": [ "user:mike@example.com",
776 "group:admins@example.com",
777 "domain:google.com",
778 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
779 ]
780
781 }, { "role":
782 "roles/resourcemanager.organizationViewer",
783 "members": [ "user:eve@example.com" ],
784 "condition": { "title": "expirable access",
785 "description": "Does not grant access after
786 Sep 2020", "expression": "request.time <
787 timestamp('2020-10-01T00:00:00.000Z')", } }
788
789 ], "etag": "BwWWja0YfJA=", "version": 3
790
791 }
792
793 **YAML example:**
794
795 bindings: - members: - user:\ mike@example.com -
796 group:\ admins@example.com - domain:google.com -
797 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
798 role: roles/resourcemanager.organizationAdmin -
799 members: - user:\ eve@example.com role:
800 roles/resourcemanager.organizationViewer
801 condition: title: expirable access description:
802 Does not grant access after Sep 2020 expression:
803 request.time <
804 timestamp('2020-10-01T00:00:00.000Z') etag:
805 BwWWja0YfJA= version: 3
806
807 For a description of IAM and its features, see the
808 [IAM
809 documentation](\ https://cloud.google.com/iam/docs/).
810
811 """
812 # Create or coerce a protobuf request object.
813 # Quick check: If we got a request object, we should *not* have
814 # gotten any keyword arguments that map to the request.
815 has_flattened_params = any([resource])
816 if request is not None and has_flattened_params:
817 raise ValueError(
818 "If the `request` argument is set, then none of "
819 "the individual field arguments should be set."
820 )
821
822 if isinstance(request, dict):
823 # The request isn't a proto-plus wrapped type,
824 # so it must be constructed via keyword expansion.
825 request = iam_policy_pb2.GetIamPolicyRequest(**request)
826 elif not request:
827 # Null request, just make one.
828 request = iam_policy_pb2.GetIamPolicyRequest()
829 if resource is not None:
830 request.resource = resource
831
832 # Wrap the RPC method; this adds retry and timeout information,
833 # and friendly error handling.
834 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
835
836 # Certain fields should be provided within the metadata header;
837 # add these here.
838 metadata = tuple(metadata) + (
839 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
840 )
841
842 # Send the request.
843 response = rpc(
844 request,
845 retry=retry,
846 timeout=timeout,
847 metadata=metadata,
848 )
849
850 # Done; return the response.
851 return response
852
853 def set_iam_policy(
854 self,
855 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
856 *,
857 resource: Optional[str] = None,
858 retry: OptionalRetry = gapic_v1.method.DEFAULT,
859 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
860 metadata: Sequence[Tuple[str, str]] = (),
861 ) -> policy_pb2.Policy:
862 r"""Sets the access control policy on an organization resource.
863 Replaces any existing policy. The ``resource`` field should be
864 the organization's resource name, for example:
865 "organizations/123".
866
867 Authorization requires the IAM permission
868 ``resourcemanager.organizations.setIamPolicy`` on the specified
869 organization.
870
871 .. code-block:: python
872
873 # This snippet has been automatically generated and should be regarded as a
874 # code template only.
875 # It will require modifications to work:
876 # - It may require correct/in-range values for request initialization.
877 # - It may require specifying regional endpoints when creating the service
878 # client as shown in:
879 # https://googleapis.dev/python/google-api-core/latest/client_options.html
880 from google.cloud import resourcemanager_v3
881 from google.iam.v1 import iam_policy_pb2 # type: ignore
882
883 def sample_set_iam_policy():
884 # Create a client
885 client = resourcemanager_v3.OrganizationsClient()
886
887 # Initialize request argument(s)
888 request = iam_policy_pb2.SetIamPolicyRequest(
889 resource="resource_value",
890 )
891
892 # Make the request
893 response = client.set_iam_policy(request=request)
894
895 # Handle the response
896 print(response)
897
898 Args:
899 request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
900 The request object. Request message for ``SetIamPolicy`` method.
901 resource (str):
902 REQUIRED: The resource for which the
903 policy is being specified. See the
904 operation documentation for the
905 appropriate value for this field.
906
907 This corresponds to the ``resource`` field
908 on the ``request`` instance; if ``request`` is provided, this
909 should not be set.
910 retry (google.api_core.retry.Retry): Designation of what errors, if any,
911 should be retried.
912 timeout (float): The timeout for this request.
913 metadata (Sequence[Tuple[str, str]]): Strings which should be
914 sent along with the request as metadata.
915
916 Returns:
917 google.iam.v1.policy_pb2.Policy:
918 An Identity and Access Management (IAM) policy, which specifies access
919 controls for Google Cloud resources.
920
921 A Policy is a collection of bindings. A binding binds
922 one or more members, or principals, to a single role.
923 Principals can be user accounts, service accounts,
924 Google groups, and domains (such as G Suite). A role
925 is a named list of permissions; each role can be an
926 IAM predefined role or a user-created custom role.
927
928 For some types of Google Cloud resources, a binding
929 can also specify a condition, which is a logical
930 expression that allows access to a resource only if
931 the expression evaluates to true. A condition can add
932 constraints based on attributes of the request, the
933 resource, or both. To learn which resources support
934 conditions in their IAM policies, see the [IAM
935 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
936
937 **JSON example:**
938
939 {
940 "bindings": [
941 {
942 "role":
943 "roles/resourcemanager.organizationAdmin",
944 "members": [ "user:mike@example.com",
945 "group:admins@example.com",
946 "domain:google.com",
947 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
948 ]
949
950 }, { "role":
951 "roles/resourcemanager.organizationViewer",
952 "members": [ "user:eve@example.com" ],
953 "condition": { "title": "expirable access",
954 "description": "Does not grant access after
955 Sep 2020", "expression": "request.time <
956 timestamp('2020-10-01T00:00:00.000Z')", } }
957
958 ], "etag": "BwWWja0YfJA=", "version": 3
959
960 }
961
962 **YAML example:**
963
964 bindings: - members: - user:\ mike@example.com -
965 group:\ admins@example.com - domain:google.com -
966 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
967 role: roles/resourcemanager.organizationAdmin -
968 members: - user:\ eve@example.com role:
969 roles/resourcemanager.organizationViewer
970 condition: title: expirable access description:
971 Does not grant access after Sep 2020 expression:
972 request.time <
973 timestamp('2020-10-01T00:00:00.000Z') etag:
974 BwWWja0YfJA= version: 3
975
976 For a description of IAM and its features, see the
977 [IAM
978 documentation](\ https://cloud.google.com/iam/docs/).
979
980 """
981 # Create or coerce a protobuf request object.
982 # Quick check: If we got a request object, we should *not* have
983 # gotten any keyword arguments that map to the request.
984 has_flattened_params = any([resource])
985 if request is not None and has_flattened_params:
986 raise ValueError(
987 "If the `request` argument is set, then none of "
988 "the individual field arguments should be set."
989 )
990
991 if isinstance(request, dict):
992 # The request isn't a proto-plus wrapped type,
993 # so it must be constructed via keyword expansion.
994 request = iam_policy_pb2.SetIamPolicyRequest(**request)
995 elif not request:
996 # Null request, just make one.
997 request = iam_policy_pb2.SetIamPolicyRequest()
998 if resource is not None:
999 request.resource = resource
1000
1001 # Wrap the RPC method; this adds retry and timeout information,
1002 # and friendly error handling.
1003 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
1004
1005 # Certain fields should be provided within the metadata header;
1006 # add these here.
1007 metadata = tuple(metadata) + (
1008 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1009 )
1010
1011 # Send the request.
1012 response = rpc(
1013 request,
1014 retry=retry,
1015 timeout=timeout,
1016 metadata=metadata,
1017 )
1018
1019 # Done; return the response.
1020 return response
1021
1022 def test_iam_permissions(
1023 self,
1024 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None,
1025 *,
1026 resource: Optional[str] = None,
1027 permissions: Optional[MutableSequence[str]] = None,
1028 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1029 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1030 metadata: Sequence[Tuple[str, str]] = (),
1031 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1032 r"""Returns the permissions that a caller has on the specified
1033 organization. The ``resource`` field should be the
1034 organization's resource name, for example: "organizations/123".
1035
1036 There are no permissions required for making this API call.
1037
1038 .. code-block:: python
1039
1040 # This snippet has been automatically generated and should be regarded as a
1041 # code template only.
1042 # It will require modifications to work:
1043 # - It may require correct/in-range values for request initialization.
1044 # - It may require specifying regional endpoints when creating the service
1045 # client as shown in:
1046 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1047 from google.cloud import resourcemanager_v3
1048 from google.iam.v1 import iam_policy_pb2 # type: ignore
1049
1050 def sample_test_iam_permissions():
1051 # Create a client
1052 client = resourcemanager_v3.OrganizationsClient()
1053
1054 # Initialize request argument(s)
1055 request = iam_policy_pb2.TestIamPermissionsRequest(
1056 resource="resource_value",
1057 permissions=['permissions_value1', 'permissions_value2'],
1058 )
1059
1060 # Make the request
1061 response = client.test_iam_permissions(request=request)
1062
1063 # Handle the response
1064 print(response)
1065
1066 Args:
1067 request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]):
1068 The request object. Request message for ``TestIamPermissions`` method.
1069 resource (str):
1070 REQUIRED: The resource for which the
1071 policy detail is being requested. See
1072 the operation documentation for the
1073 appropriate value for this field.
1074
1075 This corresponds to the ``resource`` field
1076 on the ``request`` instance; if ``request`` is provided, this
1077 should not be set.
1078 permissions (MutableSequence[str]):
1079 The set of permissions to check for the ``resource``.
1080 Permissions with wildcards (such as '*' or 'storage.*')
1081 are not allowed. For more information see `IAM
1082 Overview <https://cloud.google.com/iam/docs/overview#permissions>`__.
1083
1084 This corresponds to the ``permissions`` field
1085 on the ``request`` instance; if ``request`` is provided, this
1086 should not be set.
1087 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1088 should be retried.
1089 timeout (float): The timeout for this request.
1090 metadata (Sequence[Tuple[str, str]]): Strings which should be
1091 sent along with the request as metadata.
1092
1093 Returns:
1094 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
1095 Response message for TestIamPermissions method.
1096 """
1097 # Create or coerce a protobuf request object.
1098 # Quick check: If we got a request object, we should *not* have
1099 # gotten any keyword arguments that map to the request.
1100 has_flattened_params = any([resource, permissions])
1101 if request is not None and has_flattened_params:
1102 raise ValueError(
1103 "If the `request` argument is set, then none of "
1104 "the individual field arguments should be set."
1105 )
1106
1107 if isinstance(request, dict):
1108 # The request isn't a proto-plus wrapped type,
1109 # so it must be constructed via keyword expansion.
1110 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
1111 elif not request:
1112 # Null request, just make one.
1113 request = iam_policy_pb2.TestIamPermissionsRequest()
1114 if resource is not None:
1115 request.resource = resource
1116 if permissions:
1117 request.permissions.extend(permissions)
1118
1119 # Wrap the RPC method; this adds retry and timeout information,
1120 # and friendly error handling.
1121 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
1122
1123 # Certain fields should be provided within the metadata header;
1124 # add these here.
1125 metadata = tuple(metadata) + (
1126 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1127 )
1128
1129 # Send the request.
1130 response = rpc(
1131 request,
1132 retry=retry,
1133 timeout=timeout,
1134 metadata=metadata,
1135 )
1136
1137 # Done; return the response.
1138 return response
1139
1140 def __enter__(self) -> "OrganizationsClient":
1141 return self
1142
1143 def __exit__(self, type, value, traceback):
1144 """Releases underlying transport's resources.
1145
1146 .. warning::
1147 ONLY use as a context manager if the transport is NOT shared
1148 with other clients! Exiting the with block will CLOSE the transport
1149 and may cause errors in other clients!
1150 """
1151 self.transport.close()
1152
1153 def get_operation(
1154 self,
1155 request: Optional[operations_pb2.GetOperationRequest] = None,
1156 *,
1157 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1158 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1159 metadata: Sequence[Tuple[str, str]] = (),
1160 ) -> operations_pb2.Operation:
1161 r"""Gets the latest state of a long-running operation.
1162
1163 Args:
1164 request (:class:`~.operations_pb2.GetOperationRequest`):
1165 The request object. Request message for
1166 `GetOperation` method.
1167 retry (google.api_core.retry.Retry): Designation of what errors,
1168 if any, should be retried.
1169 timeout (float): The timeout for this request.
1170 metadata (Sequence[Tuple[str, str]]): Strings which should be
1171 sent along with the request as metadata.
1172 Returns:
1173 ~.operations_pb2.Operation:
1174 An ``Operation`` object.
1175 """
1176 # Create or coerce a protobuf request object.
1177 # The request isn't a proto-plus wrapped type,
1178 # so it must be constructed via keyword expansion.
1179 if isinstance(request, dict):
1180 request = operations_pb2.GetOperationRequest(**request)
1181
1182 # Wrap the RPC method; this adds retry and timeout information,
1183 # and friendly error handling.
1184 rpc = gapic_v1.method.wrap_method(
1185 self._transport.get_operation,
1186 default_timeout=None,
1187 client_info=DEFAULT_CLIENT_INFO,
1188 )
1189
1190 # Certain fields should be provided within the metadata header;
1191 # add these here.
1192 metadata = tuple(metadata) + (
1193 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1194 )
1195
1196 # Send the request.
1197 response = rpc(
1198 request,
1199 retry=retry,
1200 timeout=timeout,
1201 metadata=metadata,
1202 )
1203
1204 # Done; return the response.
1205 return response
1206
1207
1208DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1209 gapic_version=package_version.__version__
1210)
1211
1212
1213__all__ = ("OrganizationsClient",)