Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/resourcemanager_v3/services/projects/client.py: 31%
313 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.projects import pagers
58from google.cloud.resourcemanager_v3.types import projects
60from .transports.base import DEFAULT_CLIENT_INFO, ProjectsTransport
61from .transports.grpc import ProjectsGrpcTransport
62from .transports.grpc_asyncio import ProjectsGrpcAsyncIOTransport
63from .transports.rest import ProjectsRestTransport
66class ProjectsClientMeta(type):
67 """Metaclass for the Projects 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[ProjectsTransport]]
75 _transport_registry["grpc"] = ProjectsGrpcTransport
76 _transport_registry["grpc_asyncio"] = ProjectsGrpcAsyncIOTransport
77 _transport_registry["rest"] = ProjectsRestTransport
79 def get_transport_class(
80 cls,
81 label: Optional[str] = None,
82 ) -> Type[ProjectsTransport]:
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 ProjectsClient(metaclass=ProjectsClientMeta):
102 """Manages Google Cloud Projects."""
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 ProjectsClient: 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 ProjectsClient: 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) -> ProjectsTransport:
178 """Returns the transport used by the client instance.
180 Returns:
181 ProjectsTransport: The transport used by the client
182 instance.
183 """
184 return self._transport
186 @staticmethod
187 def project_path(
188 project: str,
189 ) -> str:
190 """Returns a fully-qualified project string."""
191 return "projects/{project}".format(
192 project=project,
193 )
195 @staticmethod
196 def parse_project_path(path: str) -> Dict[str, str]:
197 """Parses a project path into its component segments."""
198 m = re.match(r"^projects/(?P<project>.+?)$", 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, ProjectsTransport]] = 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 projects 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, ProjectsTransport]): 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, ProjectsTransport):
410 # transport is a ProjectsTransport 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 get_project(
446 self,
447 request: Optional[Union[projects.GetProjectRequest, dict]] = None,
448 *,
449 name: 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 ) -> projects.Project:
454 r"""Retrieves the project identified by the specified ``name`` (for
455 example, ``projects/415104041262``).
457 The caller must have ``resourcemanager.projects.get`` permission
458 for this project.
460 .. code-block:: python
462 # This snippet has been automatically generated and should be regarded as a
463 # code template only.
464 # It will require modifications to work:
465 # - It may require correct/in-range values for request initialization.
466 # - It may require specifying regional endpoints when creating the service
467 # client as shown in:
468 # https://googleapis.dev/python/google-api-core/latest/client_options.html
469 from google.cloud import resourcemanager_v3
471 def sample_get_project():
472 # Create a client
473 client = resourcemanager_v3.ProjectsClient()
475 # Initialize request argument(s)
476 request = resourcemanager_v3.GetProjectRequest(
477 name="name_value",
478 )
480 # Make the request
481 response = client.get_project(request=request)
483 # Handle the response
484 print(response)
486 Args:
487 request (Union[google.cloud.resourcemanager_v3.types.GetProjectRequest, dict]):
488 The request object. The request sent to the
489 [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]
490 method.
491 name (str):
492 Required. The name of the project (for example,
493 ``projects/415104041262``).
495 This corresponds to the ``name`` field
496 on the ``request`` instance; if ``request`` is provided, this
497 should not be set.
498 retry (google.api_core.retry.Retry): Designation of what errors, if any,
499 should be retried.
500 timeout (float): The timeout for this request.
501 metadata (Sequence[Tuple[str, str]]): Strings which should be
502 sent along with the request as metadata.
504 Returns:
505 google.cloud.resourcemanager_v3.types.Project:
506 A project is a high-level Google
507 Cloud entity. It is a container for
508 ACLs, APIs, App Engine Apps, VMs, and
509 other Google Cloud Platform resources.
511 """
512 # Create or coerce a protobuf request object.
513 # Quick check: If we got a request object, we should *not* have
514 # gotten any keyword arguments that map to the request.
515 has_flattened_params = any([name])
516 if request is not None and has_flattened_params:
517 raise ValueError(
518 "If the `request` argument is set, then none of "
519 "the individual field arguments should be set."
520 )
522 # Minor optimization to avoid making a copy if the user passes
523 # in a projects.GetProjectRequest.
524 # There's no risk of modifying the input as we've already verified
525 # there are no flattened fields.
526 if not isinstance(request, projects.GetProjectRequest):
527 request = projects.GetProjectRequest(request)
528 # If we have keyword arguments corresponding to fields on the
529 # request, apply these.
530 if name is not None:
531 request.name = name
533 # Wrap the RPC method; this adds retry and timeout information,
534 # and friendly error handling.
535 rpc = self._transport._wrapped_methods[self._transport.get_project]
537 # Certain fields should be provided within the metadata header;
538 # add these here.
539 metadata = tuple(metadata) + (
540 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
541 )
543 # Send the request.
544 response = rpc(
545 request,
546 retry=retry,
547 timeout=timeout,
548 metadata=metadata,
549 )
551 # Done; return the response.
552 return response
554 def list_projects(
555 self,
556 request: Optional[Union[projects.ListProjectsRequest, dict]] = None,
557 *,
558 parent: Optional[str] = None,
559 retry: OptionalRetry = gapic_v1.method.DEFAULT,
560 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
561 metadata: Sequence[Tuple[str, str]] = (),
562 ) -> pagers.ListProjectsPager:
563 r"""Lists projects that are direct children of the specified folder
564 or organization resource. ``list()`` provides a strongly
565 consistent view of the projects underneath the specified parent
566 resource. ``list()`` returns projects sorted based upon the
567 (ascending) lexical ordering of their ``display_name``. The
568 caller must have ``resourcemanager.projects.list`` permission on
569 the identified parent.
571 .. code-block:: python
573 # This snippet has been automatically generated and should be regarded as a
574 # code template only.
575 # It will require modifications to work:
576 # - It may require correct/in-range values for request initialization.
577 # - It may require specifying regional endpoints when creating the service
578 # client as shown in:
579 # https://googleapis.dev/python/google-api-core/latest/client_options.html
580 from google.cloud import resourcemanager_v3
582 def sample_list_projects():
583 # Create a client
584 client = resourcemanager_v3.ProjectsClient()
586 # Initialize request argument(s)
587 request = resourcemanager_v3.ListProjectsRequest(
588 parent="parent_value",
589 )
591 # Make the request
592 page_result = client.list_projects(request=request)
594 # Handle the response
595 for response in page_result:
596 print(response)
598 Args:
599 request (Union[google.cloud.resourcemanager_v3.types.ListProjectsRequest, dict]):
600 The request object. The request sent to the
601 [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects]
602 method.
603 parent (str):
604 Required. The name of the parent resource whose projects
605 are being listed. Only children of this parent resource
606 are listed; descendants are not listed.
608 If the parent is a folder, use the value
609 ``folders/{folder_id}``. If the parent is an
610 organization, use the value ``organizations/{org_id}``.
612 This corresponds to the ``parent`` field
613 on the ``request`` instance; if ``request`` is provided, this
614 should not be set.
615 retry (google.api_core.retry.Retry): Designation of what errors, if any,
616 should be retried.
617 timeout (float): The timeout for this request.
618 metadata (Sequence[Tuple[str, str]]): Strings which should be
619 sent along with the request as metadata.
621 Returns:
622 google.cloud.resourcemanager_v3.services.projects.pagers.ListProjectsPager:
623 A page of the response received from the
624 [ListProjects][google.cloud.resourcemanager.v3.Projects.ListProjects]
625 method.
627 A paginated response where more pages are available
628 has next_page_token set. This token can be used in a
629 subsequent request to retrieve the next request page.
631 NOTE: A response may contain fewer elements than the
632 request page_size and still have a next_page_token.
634 Iterating over this object will yield results and
635 resolve additional pages automatically.
637 """
638 # Create or coerce a protobuf request object.
639 # Quick check: If we got a request object, we should *not* have
640 # gotten any keyword arguments that map to the request.
641 has_flattened_params = any([parent])
642 if request is not None and has_flattened_params:
643 raise ValueError(
644 "If the `request` argument is set, then none of "
645 "the individual field arguments should be set."
646 )
648 # Minor optimization to avoid making a copy if the user passes
649 # in a projects.ListProjectsRequest.
650 # There's no risk of modifying the input as we've already verified
651 # there are no flattened fields.
652 if not isinstance(request, projects.ListProjectsRequest):
653 request = projects.ListProjectsRequest(request)
654 # If we have keyword arguments corresponding to fields on the
655 # request, apply these.
656 if parent is not None:
657 request.parent = parent
659 # Wrap the RPC method; this adds retry and timeout information,
660 # and friendly error handling.
661 rpc = self._transport._wrapped_methods[self._transport.list_projects]
663 # Send the request.
664 response = rpc(
665 request,
666 retry=retry,
667 timeout=timeout,
668 metadata=metadata,
669 )
671 # This method is paged; wrap the response in a pager, which provides
672 # an `__iter__` convenience method.
673 response = pagers.ListProjectsPager(
674 method=rpc,
675 request=request,
676 response=response,
677 metadata=metadata,
678 )
680 # Done; return the response.
681 return response
683 def search_projects(
684 self,
685 request: Optional[Union[projects.SearchProjectsRequest, dict]] = None,
686 *,
687 query: Optional[str] = None,
688 retry: OptionalRetry = gapic_v1.method.DEFAULT,
689 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
690 metadata: Sequence[Tuple[str, str]] = (),
691 ) -> pagers.SearchProjectsPager:
692 r"""Search for projects that the caller has both
693 ``resourcemanager.projects.get`` permission on, and also satisfy
694 the specified query.
696 This method returns projects in an unspecified order.
698 This method is eventually consistent with project mutations;
699 this means that a newly created project may not appear in the
700 results or recent updates to an existing project may not be
701 reflected in the results. To retrieve the latest state of a
702 project, use the
703 [GetProject][google.cloud.resourcemanager.v3.Projects.GetProject]
704 method.
706 .. code-block:: python
708 # This snippet has been automatically generated and should be regarded as a
709 # code template only.
710 # It will require modifications to work:
711 # - It may require correct/in-range values for request initialization.
712 # - It may require specifying regional endpoints when creating the service
713 # client as shown in:
714 # https://googleapis.dev/python/google-api-core/latest/client_options.html
715 from google.cloud import resourcemanager_v3
717 def sample_search_projects():
718 # Create a client
719 client = resourcemanager_v3.ProjectsClient()
721 # Initialize request argument(s)
722 request = resourcemanager_v3.SearchProjectsRequest(
723 )
725 # Make the request
726 page_result = client.search_projects(request=request)
728 # Handle the response
729 for response in page_result:
730 print(response)
732 Args:
733 request (Union[google.cloud.resourcemanager_v3.types.SearchProjectsRequest, dict]):
734 The request object. The request sent to the
735 [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
736 method.
737 query (str):
738 Optional. A query string for searching for projects that
739 the caller has ``resourcemanager.projects.get``
740 permission to. If multiple fields are included in the
741 query, then it will return results that match any of the
742 fields. Some eligible fields are:
744 - **``displayName``, ``name``**: Filters by
745 displayName.
746 - **``parent``**: Project's parent (for example:
747 ``folders/123``, ``organizations/*``). Prefer
748 ``parent`` field over ``parent.type`` and
749 ``parent.id``.
750 - **``parent.type``**: Parent's type: ``folder`` or
751 ``organization``.
752 - **``parent.id``**: Parent's id number (for example:
753 ``123``).
754 - **``id``, ``projectId``**: Filters by projectId.
755 - **``state``, ``lifecycleState``**: Filters by state.
756 - **``labels``**: Filters by label name or value.
757 - **``labels.<key>`` (where ``<key>`` is the name of a
758 label)**: Filters by label name.
760 Search expressions are case insensitive.
762 Some examples queries:
764 - **``name:how*``**: The project's name starts with
765 "how".
766 - **``name:Howl``**: The project's name is ``Howl`` or
767 ``howl``.
768 - **``name:HOWL``**: Equivalent to above.
769 - **``NAME:howl``**: Equivalent to above.
770 - **``labels.color:*``**: The project has the label
771 ``color``.
772 - **``labels.color:red``**: The project's label
773 ``color`` has the value ``red``.
774 - **``labels.color:red labels.size:big``**: The
775 project's label ``color`` has the value ``red`` or
776 its label ``size`` has the value ``big``.
778 If no query is specified, the call will return projects
779 for which the user has the
780 ``resourcemanager.projects.get`` permission.
782 This corresponds to the ``query`` field
783 on the ``request`` instance; if ``request`` is provided, this
784 should not be set.
785 retry (google.api_core.retry.Retry): Designation of what errors, if any,
786 should be retried.
787 timeout (float): The timeout for this request.
788 metadata (Sequence[Tuple[str, str]]): Strings which should be
789 sent along with the request as metadata.
791 Returns:
792 google.cloud.resourcemanager_v3.services.projects.pagers.SearchProjectsPager:
793 A page of the response received from the
794 [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
795 method.
797 A paginated response where more pages are available
798 has next_page_token set. This token can be used in a
799 subsequent request to retrieve the next request page.
801 Iterating over this object will yield results and
802 resolve additional pages automatically.
804 """
805 # Create or coerce a protobuf request object.
806 # Quick check: If we got a request object, we should *not* have
807 # gotten any keyword arguments that map to the request.
808 has_flattened_params = any([query])
809 if request is not None and has_flattened_params:
810 raise ValueError(
811 "If the `request` argument is set, then none of "
812 "the individual field arguments should be set."
813 )
815 # Minor optimization to avoid making a copy if the user passes
816 # in a projects.SearchProjectsRequest.
817 # There's no risk of modifying the input as we've already verified
818 # there are no flattened fields.
819 if not isinstance(request, projects.SearchProjectsRequest):
820 request = projects.SearchProjectsRequest(request)
821 # If we have keyword arguments corresponding to fields on the
822 # request, apply these.
823 if query is not None:
824 request.query = query
826 # Wrap the RPC method; this adds retry and timeout information,
827 # and friendly error handling.
828 rpc = self._transport._wrapped_methods[self._transport.search_projects]
830 # Send the request.
831 response = rpc(
832 request,
833 retry=retry,
834 timeout=timeout,
835 metadata=metadata,
836 )
838 # This method is paged; wrap the response in a pager, which provides
839 # an `__iter__` convenience method.
840 response = pagers.SearchProjectsPager(
841 method=rpc,
842 request=request,
843 response=response,
844 metadata=metadata,
845 )
847 # Done; return the response.
848 return response
850 def create_project(
851 self,
852 request: Optional[Union[projects.CreateProjectRequest, dict]] = None,
853 *,
854 project: Optional[projects.Project] = None,
855 retry: OptionalRetry = gapic_v1.method.DEFAULT,
856 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
857 metadata: Sequence[Tuple[str, str]] = (),
858 ) -> operation.Operation:
859 r"""Request that a new project be created. The result is an
860 ``Operation`` which can be used to track the creation process.
861 This process usually takes a few seconds, but can sometimes take
862 much longer. The tracking ``Operation`` is automatically deleted
863 after a few hours, so there is no need to call
864 ``DeleteOperation``.
866 .. code-block:: python
868 # This snippet has been automatically generated and should be regarded as a
869 # code template only.
870 # It will require modifications to work:
871 # - It may require correct/in-range values for request initialization.
872 # - It may require specifying regional endpoints when creating the service
873 # client as shown in:
874 # https://googleapis.dev/python/google-api-core/latest/client_options.html
875 from google.cloud import resourcemanager_v3
877 def sample_create_project():
878 # Create a client
879 client = resourcemanager_v3.ProjectsClient()
881 # Initialize request argument(s)
882 request = resourcemanager_v3.CreateProjectRequest(
883 )
885 # Make the request
886 operation = client.create_project(request=request)
888 print("Waiting for operation to complete...")
890 response = operation.result()
892 # Handle the response
893 print(response)
895 Args:
896 request (Union[google.cloud.resourcemanager_v3.types.CreateProjectRequest, dict]):
897 The request object. The request sent to the
898 [CreateProject][google.cloud.resourcemanager.v3.Projects.CreateProject]
899 method.
900 project (google.cloud.resourcemanager_v3.types.Project):
901 Required. The Project to create.
903 Project ID is required. If the requested ID is
904 unavailable, the request fails.
906 If the ``parent`` field is set, the
907 ``resourcemanager.projects.create`` permission is
908 checked on the parent resource. If no parent is set and
909 the authorization credentials belong to an Organization,
910 the parent will be set to that Organization.
912 This corresponds to the ``project`` field
913 on the ``request`` instance; if ``request`` is provided, this
914 should not be set.
915 retry (google.api_core.retry.Retry): Designation of what errors, if any,
916 should be retried.
917 timeout (float): The timeout for this request.
918 metadata (Sequence[Tuple[str, str]]): Strings which should be
919 sent along with the request as metadata.
921 Returns:
922 google.api_core.operation.Operation:
923 An object representing a long-running operation.
925 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a
926 container for ACLs, APIs, App Engine Apps, VMs, and
927 other Google Cloud Platform resources.
929 """
930 # Create or coerce a protobuf request object.
931 # Quick check: If we got a request object, we should *not* have
932 # gotten any keyword arguments that map to the request.
933 has_flattened_params = any([project])
934 if request is not None and has_flattened_params:
935 raise ValueError(
936 "If the `request` argument is set, then none of "
937 "the individual field arguments should be set."
938 )
940 # Minor optimization to avoid making a copy if the user passes
941 # in a projects.CreateProjectRequest.
942 # There's no risk of modifying the input as we've already verified
943 # there are no flattened fields.
944 if not isinstance(request, projects.CreateProjectRequest):
945 request = projects.CreateProjectRequest(request)
946 # If we have keyword arguments corresponding to fields on the
947 # request, apply these.
948 if project is not None:
949 request.project = project
951 # Wrap the RPC method; this adds retry and timeout information,
952 # and friendly error handling.
953 rpc = self._transport._wrapped_methods[self._transport.create_project]
955 # Send the request.
956 response = rpc(
957 request,
958 retry=retry,
959 timeout=timeout,
960 metadata=metadata,
961 )
963 # Wrap the response in an operation future.
964 response = operation.from_gapic(
965 response,
966 self._transport.operations_client,
967 projects.Project,
968 metadata_type=projects.CreateProjectMetadata,
969 )
971 # Done; return the response.
972 return response
974 def update_project(
975 self,
976 request: Optional[Union[projects.UpdateProjectRequest, dict]] = None,
977 *,
978 project: Optional[projects.Project] = None,
979 update_mask: Optional[field_mask_pb2.FieldMask] = None,
980 retry: OptionalRetry = gapic_v1.method.DEFAULT,
981 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
982 metadata: Sequence[Tuple[str, str]] = (),
983 ) -> operation.Operation:
984 r"""Updates the ``display_name`` and labels of the project
985 identified by the specified ``name`` (for example,
986 ``projects/415104041262``). Deleting all labels requires an
987 update mask for labels field.
989 The caller must have ``resourcemanager.projects.update``
990 permission for this project.
992 .. code-block:: python
994 # This snippet has been automatically generated and should be regarded as a
995 # code template only.
996 # It will require modifications to work:
997 # - It may require correct/in-range values for request initialization.
998 # - It may require specifying regional endpoints when creating the service
999 # client as shown in:
1000 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1001 from google.cloud import resourcemanager_v3
1003 def sample_update_project():
1004 # Create a client
1005 client = resourcemanager_v3.ProjectsClient()
1007 # Initialize request argument(s)
1008 request = resourcemanager_v3.UpdateProjectRequest(
1009 )
1011 # Make the request
1012 operation = client.update_project(request=request)
1014 print("Waiting for operation to complete...")
1016 response = operation.result()
1018 # Handle the response
1019 print(response)
1021 Args:
1022 request (Union[google.cloud.resourcemanager_v3.types.UpdateProjectRequest, dict]):
1023 The request object. The request sent to the
1024 [UpdateProject][google.cloud.resourcemanager.v3.Projects.UpdateProject]
1025 method.
1027 Only the ``display_name`` and ``labels`` fields can be
1028 change. Use the
1029 [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject]
1030 method to change the ``parent`` field.
1031 project (google.cloud.resourcemanager_v3.types.Project):
1032 Required. The new definition of the
1033 project.
1035 This corresponds to the ``project`` field
1036 on the ``request`` instance; if ``request`` is provided, this
1037 should not be set.
1038 update_mask (google.protobuf.field_mask_pb2.FieldMask):
1039 Optional. An update mask to
1040 selectively update fields.
1042 This corresponds to the ``update_mask`` field
1043 on the ``request`` instance; if ``request`` is provided, this
1044 should not be set.
1045 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1046 should be retried.
1047 timeout (float): The timeout for this request.
1048 metadata (Sequence[Tuple[str, str]]): Strings which should be
1049 sent along with the request as metadata.
1051 Returns:
1052 google.api_core.operation.Operation:
1053 An object representing a long-running operation.
1055 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a
1056 container for ACLs, APIs, App Engine Apps, VMs, and
1057 other Google Cloud Platform resources.
1059 """
1060 # Create or coerce a protobuf request object.
1061 # Quick check: If we got a request object, we should *not* have
1062 # gotten any keyword arguments that map to the request.
1063 has_flattened_params = any([project, update_mask])
1064 if request is not None and has_flattened_params:
1065 raise ValueError(
1066 "If the `request` argument is set, then none of "
1067 "the individual field arguments should be set."
1068 )
1070 # Minor optimization to avoid making a copy if the user passes
1071 # in a projects.UpdateProjectRequest.
1072 # There's no risk of modifying the input as we've already verified
1073 # there are no flattened fields.
1074 if not isinstance(request, projects.UpdateProjectRequest):
1075 request = projects.UpdateProjectRequest(request)
1076 # If we have keyword arguments corresponding to fields on the
1077 # request, apply these.
1078 if project is not None:
1079 request.project = project
1080 if update_mask is not None:
1081 request.update_mask = update_mask
1083 # Wrap the RPC method; this adds retry and timeout information,
1084 # and friendly error handling.
1085 rpc = self._transport._wrapped_methods[self._transport.update_project]
1087 # Certain fields should be provided within the metadata header;
1088 # add these here.
1089 metadata = tuple(metadata) + (
1090 gapic_v1.routing_header.to_grpc_metadata(
1091 (("project.name", request.project.name),)
1092 ),
1093 )
1095 # Send the request.
1096 response = rpc(
1097 request,
1098 retry=retry,
1099 timeout=timeout,
1100 metadata=metadata,
1101 )
1103 # Wrap the response in an operation future.
1104 response = operation.from_gapic(
1105 response,
1106 self._transport.operations_client,
1107 projects.Project,
1108 metadata_type=projects.UpdateProjectMetadata,
1109 )
1111 # Done; return the response.
1112 return response
1114 def move_project(
1115 self,
1116 request: Optional[Union[projects.MoveProjectRequest, dict]] = None,
1117 *,
1118 name: Optional[str] = None,
1119 destination_parent: Optional[str] = None,
1120 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1121 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1122 metadata: Sequence[Tuple[str, str]] = (),
1123 ) -> operation.Operation:
1124 r"""Move a project to another place in your resource hierarchy,
1125 under a new resource parent.
1127 Returns an operation which can be used to track the process of
1128 the project move workflow. Upon success, the
1129 ``Operation.response`` field will be populated with the moved
1130 project.
1132 The caller must have ``resourcemanager.projects.move``
1133 permission on the project, on the project's current and proposed
1134 new parent.
1136 If project has no current parent, or it currently does not have
1137 an associated organization resource, you will also need the
1138 ``resourcemanager.projects.setIamPolicy`` permission in the
1139 project.
1141 .. code-block:: python
1143 # This snippet has been automatically generated and should be regarded as a
1144 # code template only.
1145 # It will require modifications to work:
1146 # - It may require correct/in-range values for request initialization.
1147 # - It may require specifying regional endpoints when creating the service
1148 # client as shown in:
1149 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1150 from google.cloud import resourcemanager_v3
1152 def sample_move_project():
1153 # Create a client
1154 client = resourcemanager_v3.ProjectsClient()
1156 # Initialize request argument(s)
1157 request = resourcemanager_v3.MoveProjectRequest(
1158 name="name_value",
1159 destination_parent="destination_parent_value",
1160 )
1162 # Make the request
1163 operation = client.move_project(request=request)
1165 print("Waiting for operation to complete...")
1167 response = operation.result()
1169 # Handle the response
1170 print(response)
1172 Args:
1173 request (Union[google.cloud.resourcemanager_v3.types.MoveProjectRequest, dict]):
1174 The request object. The request sent to
1175 [MoveProject][google.cloud.resourcemanager.v3.Projects.MoveProject]
1176 method.
1177 name (str):
1178 Required. The name of the project to
1179 move.
1181 This corresponds to the ``name`` field
1182 on the ``request`` instance; if ``request`` is provided, this
1183 should not be set.
1184 destination_parent (str):
1185 Required. The new parent to move the
1186 Project under.
1188 This corresponds to the ``destination_parent`` 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.api_core.operation.Operation:
1199 An object representing a long-running operation.
1201 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a
1202 container for ACLs, APIs, App Engine Apps, VMs, and
1203 other Google Cloud Platform resources.
1205 """
1206 # Create or coerce a protobuf request object.
1207 # Quick check: If we got a request object, we should *not* have
1208 # gotten any keyword arguments that map to the request.
1209 has_flattened_params = any([name, destination_parent])
1210 if request is not None and has_flattened_params:
1211 raise ValueError(
1212 "If the `request` argument is set, then none of "
1213 "the individual field arguments should be set."
1214 )
1216 # Minor optimization to avoid making a copy if the user passes
1217 # in a projects.MoveProjectRequest.
1218 # There's no risk of modifying the input as we've already verified
1219 # there are no flattened fields.
1220 if not isinstance(request, projects.MoveProjectRequest):
1221 request = projects.MoveProjectRequest(request)
1222 # If we have keyword arguments corresponding to fields on the
1223 # request, apply these.
1224 if name is not None:
1225 request.name = name
1226 if destination_parent is not None:
1227 request.destination_parent = destination_parent
1229 # Wrap the RPC method; this adds retry and timeout information,
1230 # and friendly error handling.
1231 rpc = self._transport._wrapped_methods[self._transport.move_project]
1233 # Certain fields should be provided within the metadata header;
1234 # add these here.
1235 metadata = tuple(metadata) + (
1236 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1237 )
1239 # Send the request.
1240 response = rpc(
1241 request,
1242 retry=retry,
1243 timeout=timeout,
1244 metadata=metadata,
1245 )
1247 # Wrap the response in an operation future.
1248 response = operation.from_gapic(
1249 response,
1250 self._transport.operations_client,
1251 projects.Project,
1252 metadata_type=projects.MoveProjectMetadata,
1253 )
1255 # Done; return the response.
1256 return response
1258 def delete_project(
1259 self,
1260 request: Optional[Union[projects.DeleteProjectRequest, dict]] = None,
1261 *,
1262 name: Optional[str] = None,
1263 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1264 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1265 metadata: Sequence[Tuple[str, str]] = (),
1266 ) -> operation.Operation:
1267 r"""Marks the project identified by the specified ``name`` (for
1268 example, ``projects/415104041262``) for deletion.
1270 This method will only affect the project if it has a lifecycle
1271 state of
1272 [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE].
1274 This method changes the Project's lifecycle state from
1275 [ACTIVE][google.cloud.resourcemanager.v3.Project.State.ACTIVE]
1276 to
1277 [DELETE_REQUESTED][google.cloud.resourcemanager.v3.Project.State.DELETE_REQUESTED].
1278 The deletion starts at an unspecified time, at which point the
1279 Project is no longer accessible.
1281 Until the deletion completes, you can check the lifecycle state
1282 checked by retrieving the project with [GetProject]
1283 [google.cloud.resourcemanager.v3.Projects.GetProject], and the
1284 project remains visible to [ListProjects]
1285 [google.cloud.resourcemanager.v3.Projects.ListProjects].
1286 However, you cannot update the project.
1288 After the deletion completes, the project is not retrievable by
1289 the [GetProject]
1290 [google.cloud.resourcemanager.v3.Projects.GetProject],
1291 [ListProjects]
1292 [google.cloud.resourcemanager.v3.Projects.ListProjects], and
1293 [SearchProjects][google.cloud.resourcemanager.v3.Projects.SearchProjects]
1294 methods.
1296 This method behaves idempotently, such that deleting a
1297 ``DELETE_REQUESTED`` project will not cause an error, but also
1298 won't do anything.
1300 The caller must have ``resourcemanager.projects.delete``
1301 permissions for this project.
1303 .. code-block:: python
1305 # This snippet has been automatically generated and should be regarded as a
1306 # code template only.
1307 # It will require modifications to work:
1308 # - It may require correct/in-range values for request initialization.
1309 # - It may require specifying regional endpoints when creating the service
1310 # client as shown in:
1311 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1312 from google.cloud import resourcemanager_v3
1314 def sample_delete_project():
1315 # Create a client
1316 client = resourcemanager_v3.ProjectsClient()
1318 # Initialize request argument(s)
1319 request = resourcemanager_v3.DeleteProjectRequest(
1320 name="name_value",
1321 )
1323 # Make the request
1324 operation = client.delete_project(request=request)
1326 print("Waiting for operation to complete...")
1328 response = operation.result()
1330 # Handle the response
1331 print(response)
1333 Args:
1334 request (Union[google.cloud.resourcemanager_v3.types.DeleteProjectRequest, dict]):
1335 The request object. [DeleteProject][google.cloud.resourcemanager.v3.Projects.DeleteProject]
1336 method.
1337 name (str):
1338 Required. The name of the Project (for example,
1339 ``projects/415104041262``).
1341 This corresponds to the ``name`` field
1342 on the ``request`` instance; if ``request`` is provided, this
1343 should not be set.
1344 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1345 should be retried.
1346 timeout (float): The timeout for this request.
1347 metadata (Sequence[Tuple[str, str]]): Strings which should be
1348 sent along with the request as metadata.
1350 Returns:
1351 google.api_core.operation.Operation:
1352 An object representing a long-running operation.
1354 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a
1355 container for ACLs, APIs, App Engine Apps, VMs, and
1356 other Google Cloud Platform resources.
1358 """
1359 # Create or coerce a protobuf request object.
1360 # Quick check: If we got a request object, we should *not* have
1361 # gotten any keyword arguments that map to the request.
1362 has_flattened_params = any([name])
1363 if request is not None and has_flattened_params:
1364 raise ValueError(
1365 "If the `request` argument is set, then none of "
1366 "the individual field arguments should be set."
1367 )
1369 # Minor optimization to avoid making a copy if the user passes
1370 # in a projects.DeleteProjectRequest.
1371 # There's no risk of modifying the input as we've already verified
1372 # there are no flattened fields.
1373 if not isinstance(request, projects.DeleteProjectRequest):
1374 request = projects.DeleteProjectRequest(request)
1375 # If we have keyword arguments corresponding to fields on the
1376 # request, apply these.
1377 if name is not None:
1378 request.name = name
1380 # Wrap the RPC method; this adds retry and timeout information,
1381 # and friendly error handling.
1382 rpc = self._transport._wrapped_methods[self._transport.delete_project]
1384 # Certain fields should be provided within the metadata header;
1385 # add these here.
1386 metadata = tuple(metadata) + (
1387 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1388 )
1390 # Send the request.
1391 response = rpc(
1392 request,
1393 retry=retry,
1394 timeout=timeout,
1395 metadata=metadata,
1396 )
1398 # Wrap the response in an operation future.
1399 response = operation.from_gapic(
1400 response,
1401 self._transport.operations_client,
1402 projects.Project,
1403 metadata_type=projects.DeleteProjectMetadata,
1404 )
1406 # Done; return the response.
1407 return response
1409 def undelete_project(
1410 self,
1411 request: Optional[Union[projects.UndeleteProjectRequest, dict]] = None,
1412 *,
1413 name: Optional[str] = None,
1414 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1415 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1416 metadata: Sequence[Tuple[str, str]] = (),
1417 ) -> operation.Operation:
1418 r"""Restores the project identified by the specified ``name`` (for
1419 example, ``projects/415104041262``). You can only use this
1420 method for a project that has a lifecycle state of
1421 [DELETE_REQUESTED] [Projects.State.DELETE_REQUESTED]. After
1422 deletion starts, the project cannot be restored.
1424 The caller must have ``resourcemanager.projects.undelete``
1425 permission for this project.
1427 .. code-block:: python
1429 # This snippet has been automatically generated and should be regarded as a
1430 # code template only.
1431 # It will require modifications to work:
1432 # - It may require correct/in-range values for request initialization.
1433 # - It may require specifying regional endpoints when creating the service
1434 # client as shown in:
1435 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1436 from google.cloud import resourcemanager_v3
1438 def sample_undelete_project():
1439 # Create a client
1440 client = resourcemanager_v3.ProjectsClient()
1442 # Initialize request argument(s)
1443 request = resourcemanager_v3.UndeleteProjectRequest(
1444 name="name_value",
1445 )
1447 # Make the request
1448 operation = client.undelete_project(request=request)
1450 print("Waiting for operation to complete...")
1452 response = operation.result()
1454 # Handle the response
1455 print(response)
1457 Args:
1458 request (Union[google.cloud.resourcemanager_v3.types.UndeleteProjectRequest, dict]):
1459 The request object. The request sent to the [UndeleteProject]
1460 [google.cloud.resourcemanager.v3.Projects.UndeleteProject]
1461 method.
1462 name (str):
1463 Required. The name of the project (for example,
1464 ``projects/415104041262``).
1466 Required.
1468 This corresponds to the ``name`` field
1469 on the ``request`` instance; if ``request`` is provided, this
1470 should not be set.
1471 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1472 should be retried.
1473 timeout (float): The timeout for this request.
1474 metadata (Sequence[Tuple[str, str]]): Strings which should be
1475 sent along with the request as metadata.
1477 Returns:
1478 google.api_core.operation.Operation:
1479 An object representing a long-running operation.
1481 The result type for the operation will be :class:`google.cloud.resourcemanager_v3.types.Project` A project is a high-level Google Cloud entity. It is a
1482 container for ACLs, APIs, App Engine Apps, VMs, and
1483 other Google Cloud Platform resources.
1485 """
1486 # Create or coerce a protobuf request object.
1487 # Quick check: If we got a request object, we should *not* have
1488 # gotten any keyword arguments that map to the request.
1489 has_flattened_params = any([name])
1490 if request is not None and has_flattened_params:
1491 raise ValueError(
1492 "If the `request` argument is set, then none of "
1493 "the individual field arguments should be set."
1494 )
1496 # Minor optimization to avoid making a copy if the user passes
1497 # in a projects.UndeleteProjectRequest.
1498 # There's no risk of modifying the input as we've already verified
1499 # there are no flattened fields.
1500 if not isinstance(request, projects.UndeleteProjectRequest):
1501 request = projects.UndeleteProjectRequest(request)
1502 # If we have keyword arguments corresponding to fields on the
1503 # request, apply these.
1504 if name is not None:
1505 request.name = name
1507 # Wrap the RPC method; this adds retry and timeout information,
1508 # and friendly error handling.
1509 rpc = self._transport._wrapped_methods[self._transport.undelete_project]
1511 # Certain fields should be provided within the metadata header;
1512 # add these here.
1513 metadata = tuple(metadata) + (
1514 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1515 )
1517 # Send the request.
1518 response = rpc(
1519 request,
1520 retry=retry,
1521 timeout=timeout,
1522 metadata=metadata,
1523 )
1525 # Wrap the response in an operation future.
1526 response = operation.from_gapic(
1527 response,
1528 self._transport.operations_client,
1529 projects.Project,
1530 metadata_type=projects.UndeleteProjectMetadata,
1531 )
1533 # Done; return the response.
1534 return response
1536 def get_iam_policy(
1537 self,
1538 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
1539 *,
1540 resource: Optional[str] = None,
1541 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1542 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1543 metadata: Sequence[Tuple[str, str]] = (),
1544 ) -> policy_pb2.Policy:
1545 r"""Returns the IAM access control policy for the specified project,
1546 in the format ``projects/{ProjectIdOrNumber}`` e.g.
1547 projects/123. Permission is denied if the policy or the resource
1548 do not exist.
1550 .. code-block:: python
1552 # This snippet has been automatically generated and should be regarded as a
1553 # code template only.
1554 # It will require modifications to work:
1555 # - It may require correct/in-range values for request initialization.
1556 # - It may require specifying regional endpoints when creating the service
1557 # client as shown in:
1558 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1559 from google.cloud import resourcemanager_v3
1560 from google.iam.v1 import iam_policy_pb2 # type: ignore
1562 def sample_get_iam_policy():
1563 # Create a client
1564 client = resourcemanager_v3.ProjectsClient()
1566 # Initialize request argument(s)
1567 request = iam_policy_pb2.GetIamPolicyRequest(
1568 resource="resource_value",
1569 )
1571 # Make the request
1572 response = client.get_iam_policy(request=request)
1574 # Handle the response
1575 print(response)
1577 Args:
1578 request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
1579 The request object. Request message for ``GetIamPolicy`` method.
1580 resource (str):
1581 REQUIRED: The resource for which the
1582 policy is being requested. See the
1583 operation documentation for the
1584 appropriate value for this field.
1586 This corresponds to the ``resource`` field
1587 on the ``request`` instance; if ``request`` is provided, this
1588 should not be set.
1589 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1590 should be retried.
1591 timeout (float): The timeout for this request.
1592 metadata (Sequence[Tuple[str, str]]): Strings which should be
1593 sent along with the request as metadata.
1595 Returns:
1596 google.iam.v1.policy_pb2.Policy:
1597 An Identity and Access Management (IAM) policy, which specifies access
1598 controls for Google Cloud resources.
1600 A Policy is a collection of bindings. A binding binds
1601 one or more members, or principals, to a single role.
1602 Principals can be user accounts, service accounts,
1603 Google groups, and domains (such as G Suite). A role
1604 is a named list of permissions; each role can be an
1605 IAM predefined role or a user-created custom role.
1607 For some types of Google Cloud resources, a binding
1608 can also specify a condition, which is a logical
1609 expression that allows access to a resource only if
1610 the expression evaluates to true. A condition can add
1611 constraints based on attributes of the request, the
1612 resource, or both. To learn which resources support
1613 conditions in their IAM policies, see the [IAM
1614 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1616 **JSON example:**
1618 {
1619 "bindings": [
1620 {
1621 "role":
1622 "roles/resourcemanager.organizationAdmin",
1623 "members": [ "user:mike@example.com",
1624 "group:admins@example.com",
1625 "domain:google.com",
1626 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1627 ]
1629 }, { "role":
1630 "roles/resourcemanager.organizationViewer",
1631 "members": [ "user:eve@example.com" ],
1632 "condition": { "title": "expirable access",
1633 "description": "Does not grant access after
1634 Sep 2020", "expression": "request.time <
1635 timestamp('2020-10-01T00:00:00.000Z')", } }
1637 ], "etag": "BwWWja0YfJA=", "version": 3
1639 }
1641 **YAML example:**
1643 bindings: - members: - user:\ mike@example.com -
1644 group:\ admins@example.com - domain:google.com -
1645 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
1646 role: roles/resourcemanager.organizationAdmin -
1647 members: - user:\ eve@example.com role:
1648 roles/resourcemanager.organizationViewer
1649 condition: title: expirable access description:
1650 Does not grant access after Sep 2020 expression:
1651 request.time <
1652 timestamp('2020-10-01T00:00:00.000Z') etag:
1653 BwWWja0YfJA= version: 3
1655 For a description of IAM and its features, see the
1656 [IAM
1657 documentation](\ https://cloud.google.com/iam/docs/).
1659 """
1660 # Create or coerce a protobuf request object.
1661 # Quick check: If we got a request object, we should *not* have
1662 # gotten any keyword arguments that map to the request.
1663 has_flattened_params = any([resource])
1664 if request is not None and has_flattened_params:
1665 raise ValueError(
1666 "If the `request` argument is set, then none of "
1667 "the individual field arguments should be set."
1668 )
1670 if isinstance(request, dict):
1671 # The request isn't a proto-plus wrapped type,
1672 # so it must be constructed via keyword expansion.
1673 request = iam_policy_pb2.GetIamPolicyRequest(**request)
1674 elif not request:
1675 # Null request, just make one.
1676 request = iam_policy_pb2.GetIamPolicyRequest()
1677 if resource is not None:
1678 request.resource = resource
1680 # Wrap the RPC method; this adds retry and timeout information,
1681 # and friendly error handling.
1682 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
1684 # Certain fields should be provided within the metadata header;
1685 # add these here.
1686 metadata = tuple(metadata) + (
1687 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1688 )
1690 # Send the request.
1691 response = rpc(
1692 request,
1693 retry=retry,
1694 timeout=timeout,
1695 metadata=metadata,
1696 )
1698 # Done; return the response.
1699 return response
1701 def set_iam_policy(
1702 self,
1703 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
1704 *,
1705 resource: Optional[str] = None,
1706 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1707 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1708 metadata: Sequence[Tuple[str, str]] = (),
1709 ) -> policy_pb2.Policy:
1710 r"""Sets the IAM access control policy for the specified project, in
1711 the format ``projects/{ProjectIdOrNumber}`` e.g. projects/123.
1713 CAUTION: This method will replace the existing policy, and
1714 cannot be used to append additional IAM settings.
1716 Note: Removing service accounts from policies or changing their
1717 roles can render services completely inoperable. It is important
1718 to understand how the service account is being used before
1719 removing or updating its roles.
1721 The following constraints apply when using ``setIamPolicy()``:
1723 - Project does not support ``allUsers`` and
1724 ``allAuthenticatedUsers`` as ``members`` in a ``Binding`` of
1725 a ``Policy``.
1727 - The owner role can be granted to a ``user``,
1728 ``serviceAccount``, or a group that is part of an
1729 organization. For example, group@myownpersonaldomain.com
1730 could be added as an owner to a project in the
1731 myownpersonaldomain.com organization, but not the
1732 examplepetstore.com organization.
1734 - Service accounts can be made owners of a project directly
1735 without any restrictions. However, to be added as an owner, a
1736 user must be invited using the Cloud Platform console and
1737 must accept the invitation.
1739 - A user cannot be granted the owner role using
1740 ``setIamPolicy()``. The user must be granted the owner role
1741 using the Cloud Platform Console and must explicitly accept
1742 the invitation.
1744 - Invitations to grant the owner role cannot be sent using
1745 ``setIamPolicy()``; they must be sent only using the Cloud
1746 Platform Console.
1748 - If the project is not part of an organization, there must be
1749 at least one owner who has accepted the Terms of Service
1750 (ToS) agreement in the policy. Calling ``setIamPolicy()`` to
1751 remove the last ToS-accepted owner from the policy will fail.
1752 This restriction also applies to legacy projects that no
1753 longer have owners who have accepted the ToS. Edits to IAM
1754 policies will be rejected until the lack of a ToS-accepting
1755 owner is rectified. If the project is part of an
1756 organization, you can remove all owners, potentially making
1757 the organization inaccessible.
1759 .. code-block:: python
1761 # This snippet has been automatically generated and should be regarded as a
1762 # code template only.
1763 # It will require modifications to work:
1764 # - It may require correct/in-range values for request initialization.
1765 # - It may require specifying regional endpoints when creating the service
1766 # client as shown in:
1767 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1768 from google.cloud import resourcemanager_v3
1769 from google.iam.v1 import iam_policy_pb2 # type: ignore
1771 def sample_set_iam_policy():
1772 # Create a client
1773 client = resourcemanager_v3.ProjectsClient()
1775 # Initialize request argument(s)
1776 request = iam_policy_pb2.SetIamPolicyRequest(
1777 resource="resource_value",
1778 )
1780 # Make the request
1781 response = client.set_iam_policy(request=request)
1783 # Handle the response
1784 print(response)
1786 Args:
1787 request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
1788 The request object. Request message for ``SetIamPolicy`` method.
1789 resource (str):
1790 REQUIRED: The resource for which the
1791 policy is being specified. See the
1792 operation documentation for the
1793 appropriate value for this field.
1795 This corresponds to the ``resource`` field
1796 on the ``request`` instance; if ``request`` is provided, this
1797 should not be set.
1798 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1799 should be retried.
1800 timeout (float): The timeout for this request.
1801 metadata (Sequence[Tuple[str, str]]): Strings which should be
1802 sent along with the request as metadata.
1804 Returns:
1805 google.iam.v1.policy_pb2.Policy:
1806 An Identity and Access Management (IAM) policy, which specifies access
1807 controls for Google Cloud resources.
1809 A Policy is a collection of bindings. A binding binds
1810 one or more members, or principals, to a single role.
1811 Principals can be user accounts, service accounts,
1812 Google groups, and domains (such as G Suite). A role
1813 is a named list of permissions; each role can be an
1814 IAM predefined role or a user-created custom role.
1816 For some types of Google Cloud resources, a binding
1817 can also specify a condition, which is a logical
1818 expression that allows access to a resource only if
1819 the expression evaluates to true. A condition can add
1820 constraints based on attributes of the request, the
1821 resource, or both. To learn which resources support
1822 conditions in their IAM policies, see the [IAM
1823 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1825 **JSON example:**
1827 {
1828 "bindings": [
1829 {
1830 "role":
1831 "roles/resourcemanager.organizationAdmin",
1832 "members": [ "user:mike@example.com",
1833 "group:admins@example.com",
1834 "domain:google.com",
1835 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1836 ]
1838 }, { "role":
1839 "roles/resourcemanager.organizationViewer",
1840 "members": [ "user:eve@example.com" ],
1841 "condition": { "title": "expirable access",
1842 "description": "Does not grant access after
1843 Sep 2020", "expression": "request.time <
1844 timestamp('2020-10-01T00:00:00.000Z')", } }
1846 ], "etag": "BwWWja0YfJA=", "version": 3
1848 }
1850 **YAML example:**
1852 bindings: - members: - user:\ mike@example.com -
1853 group:\ admins@example.com - domain:google.com -
1854 serviceAccount:\ my-project-id@appspot.gserviceaccount.com
1855 role: roles/resourcemanager.organizationAdmin -
1856 members: - user:\ eve@example.com role:
1857 roles/resourcemanager.organizationViewer
1858 condition: title: expirable access description:
1859 Does not grant access after Sep 2020 expression:
1860 request.time <
1861 timestamp('2020-10-01T00:00:00.000Z') etag:
1862 BwWWja0YfJA= version: 3
1864 For a description of IAM and its features, see the
1865 [IAM
1866 documentation](\ https://cloud.google.com/iam/docs/).
1868 """
1869 # Create or coerce a protobuf request object.
1870 # Quick check: If we got a request object, we should *not* have
1871 # gotten any keyword arguments that map to the request.
1872 has_flattened_params = any([resource])
1873 if request is not None and has_flattened_params:
1874 raise ValueError(
1875 "If the `request` argument is set, then none of "
1876 "the individual field arguments should be set."
1877 )
1879 if isinstance(request, dict):
1880 # The request isn't a proto-plus wrapped type,
1881 # so it must be constructed via keyword expansion.
1882 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1883 elif not request:
1884 # Null request, just make one.
1885 request = iam_policy_pb2.SetIamPolicyRequest()
1886 if resource is not None:
1887 request.resource = resource
1889 # Wrap the RPC method; this adds retry and timeout information,
1890 # and friendly error handling.
1891 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
1893 # Certain fields should be provided within the metadata header;
1894 # add these here.
1895 metadata = tuple(metadata) + (
1896 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1897 )
1899 # Send the request.
1900 response = rpc(
1901 request,
1902 retry=retry,
1903 timeout=timeout,
1904 metadata=metadata,
1905 )
1907 # Done; return the response.
1908 return response
1910 def test_iam_permissions(
1911 self,
1912 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None,
1913 *,
1914 resource: Optional[str] = None,
1915 permissions: Optional[MutableSequence[str]] = None,
1916 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1917 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1918 metadata: Sequence[Tuple[str, str]] = (),
1919 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1920 r"""Returns permissions that a caller has on the specified project,
1921 in the format ``projects/{ProjectIdOrNumber}`` e.g.
1922 projects/123..
1924 .. code-block:: python
1926 # This snippet has been automatically generated and should be regarded as a
1927 # code template only.
1928 # It will require modifications to work:
1929 # - It may require correct/in-range values for request initialization.
1930 # - It may require specifying regional endpoints when creating the service
1931 # client as shown in:
1932 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1933 from google.cloud import resourcemanager_v3
1934 from google.iam.v1 import iam_policy_pb2 # type: ignore
1936 def sample_test_iam_permissions():
1937 # Create a client
1938 client = resourcemanager_v3.ProjectsClient()
1940 # Initialize request argument(s)
1941 request = iam_policy_pb2.TestIamPermissionsRequest(
1942 resource="resource_value",
1943 permissions=['permissions_value1', 'permissions_value2'],
1944 )
1946 # Make the request
1947 response = client.test_iam_permissions(request=request)
1949 # Handle the response
1950 print(response)
1952 Args:
1953 request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]):
1954 The request object. Request message for ``TestIamPermissions`` method.
1955 resource (str):
1956 REQUIRED: The resource for which the
1957 policy detail is being requested. See
1958 the operation documentation for the
1959 appropriate value for this field.
1961 This corresponds to the ``resource`` field
1962 on the ``request`` instance; if ``request`` is provided, this
1963 should not be set.
1964 permissions (MutableSequence[str]):
1965 The set of permissions to check for the ``resource``.
1966 Permissions with wildcards (such as '*' or 'storage.*')
1967 are not allowed. For more information see `IAM
1968 Overview <https://cloud.google.com/iam/docs/overview#permissions>`__.
1970 This corresponds to the ``permissions`` field
1971 on the ``request`` instance; if ``request`` is provided, this
1972 should not be set.
1973 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1974 should be retried.
1975 timeout (float): The timeout for this request.
1976 metadata (Sequence[Tuple[str, str]]): Strings which should be
1977 sent along with the request as metadata.
1979 Returns:
1980 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
1981 Response message for TestIamPermissions method.
1982 """
1983 # Create or coerce a protobuf request object.
1984 # Quick check: If we got a request object, we should *not* have
1985 # gotten any keyword arguments that map to the request.
1986 has_flattened_params = any([resource, permissions])
1987 if request is not None and has_flattened_params:
1988 raise ValueError(
1989 "If the `request` argument is set, then none of "
1990 "the individual field arguments should be set."
1991 )
1993 if isinstance(request, dict):
1994 # The request isn't a proto-plus wrapped type,
1995 # so it must be constructed via keyword expansion.
1996 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
1997 elif not request:
1998 # Null request, just make one.
1999 request = iam_policy_pb2.TestIamPermissionsRequest()
2000 if resource is not None:
2001 request.resource = resource
2002 if permissions:
2003 request.permissions.extend(permissions)
2005 # Wrap the RPC method; this adds retry and timeout information,
2006 # and friendly error handling.
2007 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
2009 # Certain fields should be provided within the metadata header;
2010 # add these here.
2011 metadata = tuple(metadata) + (
2012 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2013 )
2015 # Send the request.
2016 response = rpc(
2017 request,
2018 retry=retry,
2019 timeout=timeout,
2020 metadata=metadata,
2021 )
2023 # Done; return the response.
2024 return response
2026 def __enter__(self) -> "ProjectsClient":
2027 return self
2029 def __exit__(self, type, value, traceback):
2030 """Releases underlying transport's resources.
2032 .. warning::
2033 ONLY use as a context manager if the transport is NOT shared
2034 with other clients! Exiting the with block will CLOSE the transport
2035 and may cause errors in other clients!
2036 """
2037 self.transport.close()
2039 def get_operation(
2040 self,
2041 request: Optional[operations_pb2.GetOperationRequest] = None,
2042 *,
2043 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2044 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2045 metadata: Sequence[Tuple[str, str]] = (),
2046 ) -> operations_pb2.Operation:
2047 r"""Gets the latest state of a long-running operation.
2049 Args:
2050 request (:class:`~.operations_pb2.GetOperationRequest`):
2051 The request object. Request message for
2052 `GetOperation` method.
2053 retry (google.api_core.retry.Retry): Designation of what errors,
2054 if any, should be retried.
2055 timeout (float): The timeout for this request.
2056 metadata (Sequence[Tuple[str, str]]): Strings which should be
2057 sent along with the request as metadata.
2058 Returns:
2059 ~.operations_pb2.Operation:
2060 An ``Operation`` object.
2061 """
2062 # Create or coerce a protobuf request object.
2063 # The request isn't a proto-plus wrapped type,
2064 # so it must be constructed via keyword expansion.
2065 if isinstance(request, dict):
2066 request = operations_pb2.GetOperationRequest(**request)
2068 # Wrap the RPC method; this adds retry and timeout information,
2069 # and friendly error handling.
2070 rpc = gapic_v1.method.wrap_method(
2071 self._transport.get_operation,
2072 default_timeout=None,
2073 client_info=DEFAULT_CLIENT_INFO,
2074 )
2076 # Certain fields should be provided within the metadata header;
2077 # add these here.
2078 metadata = tuple(metadata) + (
2079 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2080 )
2082 # Send the request.
2083 response = rpc(
2084 request,
2085 retry=retry,
2086 timeout=timeout,
2087 metadata=metadata,
2088 )
2090 # Done; return the response.
2091 return response
2094DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2095 gapic_version=package_version.__version__
2096)
2099__all__ = ("ProjectsClient",)