1# -*- coding: utf-8 -*-
2# Copyright 2023 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.secretmanager_v1beta1 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.protobuf import field_mask_pb2 # type: ignore
52from google.protobuf import timestamp_pb2 # type: ignore
53
54from google.cloud.secretmanager_v1beta1.services.secret_manager_service import pagers
55from google.cloud.secretmanager_v1beta1.types import resources, service
56
57from .transports.base import DEFAULT_CLIENT_INFO, SecretManagerServiceTransport
58from .transports.grpc import SecretManagerServiceGrpcTransport
59from .transports.grpc_asyncio import SecretManagerServiceGrpcAsyncIOTransport
60from .transports.rest import SecretManagerServiceRestTransport
61
62
63class SecretManagerServiceClientMeta(type):
64 """Metaclass for the SecretManagerService 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 = (
72 OrderedDict()
73 ) # type: Dict[str, Type[SecretManagerServiceTransport]]
74 _transport_registry["grpc"] = SecretManagerServiceGrpcTransport
75 _transport_registry["grpc_asyncio"] = SecretManagerServiceGrpcAsyncIOTransport
76 _transport_registry["rest"] = SecretManagerServiceRestTransport
77
78 def get_transport_class(
79 cls,
80 label: Optional[str] = None,
81 ) -> Type[SecretManagerServiceTransport]:
82 """Returns an appropriate transport class.
83
84 Args:
85 label: The name of the desired transport. If none is
86 provided, then the first transport in the registry is used.
87
88 Returns:
89 The transport class to use.
90 """
91 # If a specific transport is requested, return that one.
92 if label:
93 return cls._transport_registry[label]
94
95 # No transport is requested; return the default (that is, the first one
96 # in the dictionary).
97 return next(iter(cls._transport_registry.values()))
98
99
100class SecretManagerServiceClient(metaclass=SecretManagerServiceClientMeta):
101 """Secret Manager Service
102
103 Manages secrets and operations using those secrets. Implements a
104 REST model with the following objects:
105
106 - [Secret][google.cloud.secrets.v1beta1.Secret]
107 - [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
108 """
109
110 @staticmethod
111 def _get_default_mtls_endpoint(api_endpoint):
112 """Converts api endpoint to mTLS endpoint.
113
114 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
115 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
116 Args:
117 api_endpoint (Optional[str]): the api endpoint to convert.
118 Returns:
119 str: converted mTLS api endpoint.
120 """
121 if not api_endpoint:
122 return api_endpoint
123
124 mtls_endpoint_re = re.compile(
125 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
126 )
127
128 m = mtls_endpoint_re.match(api_endpoint)
129 name, mtls, sandbox, googledomain = m.groups()
130 if mtls or not googledomain:
131 return api_endpoint
132
133 if sandbox:
134 return api_endpoint.replace(
135 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
136 )
137
138 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
139
140 DEFAULT_ENDPOINT = "secretmanager.googleapis.com"
141 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
142 DEFAULT_ENDPOINT
143 )
144
145 @classmethod
146 def from_service_account_info(cls, info: dict, *args, **kwargs):
147 """Creates an instance of this client using the provided credentials
148 info.
149
150 Args:
151 info (dict): The service account private key info.
152 args: Additional arguments to pass to the constructor.
153 kwargs: Additional arguments to pass to the constructor.
154
155 Returns:
156 SecretManagerServiceClient: The constructed client.
157 """
158 credentials = service_account.Credentials.from_service_account_info(info)
159 kwargs["credentials"] = credentials
160 return cls(*args, **kwargs)
161
162 @classmethod
163 def from_service_account_file(cls, filename: str, *args, **kwargs):
164 """Creates an instance of this client using the provided credentials
165 file.
166
167 Args:
168 filename (str): The path to the service account private key json
169 file.
170 args: Additional arguments to pass to the constructor.
171 kwargs: Additional arguments to pass to the constructor.
172
173 Returns:
174 SecretManagerServiceClient: The constructed client.
175 """
176 credentials = service_account.Credentials.from_service_account_file(filename)
177 kwargs["credentials"] = credentials
178 return cls(*args, **kwargs)
179
180 from_service_account_json = from_service_account_file
181
182 @property
183 def transport(self) -> SecretManagerServiceTransport:
184 """Returns the transport used by the client instance.
185
186 Returns:
187 SecretManagerServiceTransport: The transport used by the client
188 instance.
189 """
190 return self._transport
191
192 @staticmethod
193 def secret_path(
194 project: str,
195 secret: str,
196 ) -> str:
197 """Returns a fully-qualified secret string."""
198 return "projects/{project}/secrets/{secret}".format(
199 project=project,
200 secret=secret,
201 )
202
203 @staticmethod
204 def parse_secret_path(path: str) -> Dict[str, str]:
205 """Parses a secret path into its component segments."""
206 m = re.match(r"^projects/(?P<project>.+?)/secrets/(?P<secret>.+?)$", path)
207 return m.groupdict() if m else {}
208
209 @staticmethod
210 def secret_version_path(
211 project: str,
212 secret: str,
213 secret_version: str,
214 ) -> str:
215 """Returns a fully-qualified secret_version string."""
216 return "projects/{project}/secrets/{secret}/versions/{secret_version}".format(
217 project=project,
218 secret=secret,
219 secret_version=secret_version,
220 )
221
222 @staticmethod
223 def parse_secret_version_path(path: str) -> Dict[str, str]:
224 """Parses a secret_version path into its component segments."""
225 m = re.match(
226 r"^projects/(?P<project>.+?)/secrets/(?P<secret>.+?)/versions/(?P<secret_version>.+?)$",
227 path,
228 )
229 return m.groupdict() if m else {}
230
231 @staticmethod
232 def common_billing_account_path(
233 billing_account: str,
234 ) -> str:
235 """Returns a fully-qualified billing_account string."""
236 return "billingAccounts/{billing_account}".format(
237 billing_account=billing_account,
238 )
239
240 @staticmethod
241 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
242 """Parse a billing_account path into its component segments."""
243 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
244 return m.groupdict() if m else {}
245
246 @staticmethod
247 def common_folder_path(
248 folder: str,
249 ) -> str:
250 """Returns a fully-qualified folder string."""
251 return "folders/{folder}".format(
252 folder=folder,
253 )
254
255 @staticmethod
256 def parse_common_folder_path(path: str) -> Dict[str, str]:
257 """Parse a folder path into its component segments."""
258 m = re.match(r"^folders/(?P<folder>.+?)$", path)
259 return m.groupdict() if m else {}
260
261 @staticmethod
262 def common_organization_path(
263 organization: str,
264 ) -> str:
265 """Returns a fully-qualified organization string."""
266 return "organizations/{organization}".format(
267 organization=organization,
268 )
269
270 @staticmethod
271 def parse_common_organization_path(path: str) -> Dict[str, str]:
272 """Parse a organization path into its component segments."""
273 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
274 return m.groupdict() if m else {}
275
276 @staticmethod
277 def common_project_path(
278 project: str,
279 ) -> str:
280 """Returns a fully-qualified project string."""
281 return "projects/{project}".format(
282 project=project,
283 )
284
285 @staticmethod
286 def parse_common_project_path(path: str) -> Dict[str, str]:
287 """Parse a project path into its component segments."""
288 m = re.match(r"^projects/(?P<project>.+?)$", path)
289 return m.groupdict() if m else {}
290
291 @staticmethod
292 def common_location_path(
293 project: str,
294 location: str,
295 ) -> str:
296 """Returns a fully-qualified location string."""
297 return "projects/{project}/locations/{location}".format(
298 project=project,
299 location=location,
300 )
301
302 @staticmethod
303 def parse_common_location_path(path: str) -> Dict[str, str]:
304 """Parse a location path into its component segments."""
305 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
306 return m.groupdict() if m else {}
307
308 @classmethod
309 def get_mtls_endpoint_and_cert_source(
310 cls, client_options: Optional[client_options_lib.ClientOptions] = None
311 ):
312 """Return the API endpoint and client cert source for mutual TLS.
313
314 The client cert source is determined in the following order:
315 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
316 client cert source is None.
317 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
318 default client cert source exists, use the default one; otherwise the client cert
319 source is None.
320
321 The API endpoint is determined in the following order:
322 (1) if `client_options.api_endpoint` if provided, use the provided one.
323 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
324 default mTLS endpoint; if the environment variable is "never", use the default API
325 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
326 use the default API endpoint.
327
328 More details can be found at https://google.aip.dev/auth/4114.
329
330 Args:
331 client_options (google.api_core.client_options.ClientOptions): Custom options for the
332 client. Only the `api_endpoint` and `client_cert_source` properties may be used
333 in this method.
334
335 Returns:
336 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
337 client cert source to use.
338
339 Raises:
340 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
341 """
342 if client_options is None:
343 client_options = client_options_lib.ClientOptions()
344 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
345 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
346 if use_client_cert not in ("true", "false"):
347 raise ValueError(
348 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
349 )
350 if use_mtls_endpoint not in ("auto", "never", "always"):
351 raise MutualTLSChannelError(
352 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
353 )
354
355 # Figure out the client cert source to use.
356 client_cert_source = None
357 if use_client_cert == "true":
358 if client_options.client_cert_source:
359 client_cert_source = client_options.client_cert_source
360 elif mtls.has_default_client_cert_source():
361 client_cert_source = mtls.default_client_cert_source()
362
363 # Figure out which api endpoint to use.
364 if client_options.api_endpoint is not None:
365 api_endpoint = client_options.api_endpoint
366 elif use_mtls_endpoint == "always" or (
367 use_mtls_endpoint == "auto" and client_cert_source
368 ):
369 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
370 else:
371 api_endpoint = cls.DEFAULT_ENDPOINT
372
373 return api_endpoint, client_cert_source
374
375 def __init__(
376 self,
377 *,
378 credentials: Optional[ga_credentials.Credentials] = None,
379 transport: Optional[Union[str, SecretManagerServiceTransport]] = None,
380 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
381 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
382 ) -> None:
383 """Instantiates the secret manager service client.
384
385 Args:
386 credentials (Optional[google.auth.credentials.Credentials]): The
387 authorization credentials to attach to requests. These
388 credentials identify the application to the service; if none
389 are specified, the client will attempt to ascertain the
390 credentials from the environment.
391 transport (Union[str, SecretManagerServiceTransport]): The
392 transport to use. If set to None, a transport is chosen
393 automatically.
394 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
395 client. It won't take effect if a ``transport`` instance is provided.
396 (1) The ``api_endpoint`` property can be used to override the
397 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
398 environment variable can also be used to override the endpoint:
399 "always" (always use the default mTLS endpoint), "never" (always
400 use the default regular endpoint) and "auto" (auto switch to the
401 default mTLS endpoint if client certificate is present, this is
402 the default value). However, the ``api_endpoint`` property takes
403 precedence if provided.
404 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
405 is "true", then the ``client_cert_source`` property can be used
406 to provide client certificate for mutual TLS transport. If
407 not provided, the default SSL client certificate will be used if
408 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
409 set, no client certificate will be used.
410 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
411 The client info used to send a user-agent string along with
412 API requests. If ``None``, then default info will be used.
413 Generally, you only need to set this if you're developing
414 your own client library.
415
416 Raises:
417 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
418 creation failed for any reason.
419 """
420 if isinstance(client_options, dict):
421 client_options = client_options_lib.from_dict(client_options)
422 if client_options is None:
423 client_options = client_options_lib.ClientOptions()
424 client_options = cast(client_options_lib.ClientOptions, client_options)
425
426 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
427 client_options
428 )
429
430 api_key_value = getattr(client_options, "api_key", None)
431 if api_key_value and credentials:
432 raise ValueError(
433 "client_options.api_key and credentials are mutually exclusive"
434 )
435
436 # Save or instantiate the transport.
437 # Ordinarily, we provide the transport, but allowing a custom transport
438 # instance provides an extensibility point for unusual situations.
439 if isinstance(transport, SecretManagerServiceTransport):
440 # transport is a SecretManagerServiceTransport instance.
441 if credentials or client_options.credentials_file or api_key_value:
442 raise ValueError(
443 "When providing a transport instance, "
444 "provide its credentials directly."
445 )
446 if client_options.scopes:
447 raise ValueError(
448 "When providing a transport instance, provide its scopes "
449 "directly."
450 )
451 self._transport = transport
452 else:
453 import google.auth._default # type: ignore
454
455 if api_key_value and hasattr(
456 google.auth._default, "get_api_key_credentials"
457 ):
458 credentials = google.auth._default.get_api_key_credentials(
459 api_key_value
460 )
461
462 Transport = type(self).get_transport_class(transport)
463 self._transport = Transport(
464 credentials=credentials,
465 credentials_file=client_options.credentials_file,
466 host=api_endpoint,
467 scopes=client_options.scopes,
468 client_cert_source_for_mtls=client_cert_source_func,
469 quota_project_id=client_options.quota_project_id,
470 client_info=client_info,
471 always_use_jwt_access=True,
472 api_audience=client_options.api_audience,
473 )
474
475 def list_secrets(
476 self,
477 request: Optional[Union[service.ListSecretsRequest, dict]] = None,
478 *,
479 parent: Optional[str] = None,
480 retry: OptionalRetry = gapic_v1.method.DEFAULT,
481 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
482 metadata: Sequence[Tuple[str, str]] = (),
483 ) -> pagers.ListSecretsPager:
484 r"""Lists [Secrets][google.cloud.secrets.v1beta1.Secret].
485
486 .. code-block:: python
487
488 # This snippet has been automatically generated and should be regarded as a
489 # code template only.
490 # It will require modifications to work:
491 # - It may require correct/in-range values for request initialization.
492 # - It may require specifying regional endpoints when creating the service
493 # client as shown in:
494 # https://googleapis.dev/python/google-api-core/latest/client_options.html
495 from google.cloud import secretmanager_v1beta1
496
497 def sample_list_secrets():
498 # Create a client
499 client = secretmanager_v1beta1.SecretManagerServiceClient()
500
501 # Initialize request argument(s)
502 request = secretmanager_v1beta1.ListSecretsRequest(
503 parent="parent_value",
504 )
505
506 # Make the request
507 page_result = client.list_secrets(request=request)
508
509 # Handle the response
510 for response in page_result:
511 print(response)
512
513 Args:
514 request (Union[google.cloud.secretmanager_v1beta1.types.ListSecretsRequest, dict]):
515 The request object. Request message for
516 [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets].
517 parent (str):
518 Required. The resource name of the project associated
519 with the [Secrets][google.cloud.secrets.v1beta1.Secret],
520 in the format ``projects/*``.
521
522 This corresponds to the ``parent`` field
523 on the ``request`` instance; if ``request`` is provided, this
524 should not be set.
525 retry (google.api_core.retry.Retry): Designation of what errors, if any,
526 should be retried.
527 timeout (float): The timeout for this request.
528 metadata (Sequence[Tuple[str, str]]): Strings which should be
529 sent along with the request as metadata.
530
531 Returns:
532 google.cloud.secretmanager_v1beta1.services.secret_manager_service.pagers.ListSecretsPager:
533 Response message for
534 [SecretManagerService.ListSecrets][google.cloud.secrets.v1beta1.SecretManagerService.ListSecrets].
535
536 Iterating over this object will yield results and
537 resolve additional pages automatically.
538
539 """
540 # Create or coerce a protobuf request object.
541 # Quick check: If we got a request object, we should *not* have
542 # gotten any keyword arguments that map to the request.
543 has_flattened_params = any([parent])
544 if request is not None and has_flattened_params:
545 raise ValueError(
546 "If the `request` argument is set, then none of "
547 "the individual field arguments should be set."
548 )
549
550 # Minor optimization to avoid making a copy if the user passes
551 # in a service.ListSecretsRequest.
552 # There's no risk of modifying the input as we've already verified
553 # there are no flattened fields.
554 if not isinstance(request, service.ListSecretsRequest):
555 request = service.ListSecretsRequest(request)
556 # If we have keyword arguments corresponding to fields on the
557 # request, apply these.
558 if parent is not None:
559 request.parent = parent
560
561 # Wrap the RPC method; this adds retry and timeout information,
562 # and friendly error handling.
563 rpc = self._transport._wrapped_methods[self._transport.list_secrets]
564
565 # Certain fields should be provided within the metadata header;
566 # add these here.
567 metadata = tuple(metadata) + (
568 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
569 )
570
571 # Send the request.
572 response = rpc(
573 request,
574 retry=retry,
575 timeout=timeout,
576 metadata=metadata,
577 )
578
579 # This method is paged; wrap the response in a pager, which provides
580 # an `__iter__` convenience method.
581 response = pagers.ListSecretsPager(
582 method=rpc,
583 request=request,
584 response=response,
585 metadata=metadata,
586 )
587
588 # Done; return the response.
589 return response
590
591 def create_secret(
592 self,
593 request: Optional[Union[service.CreateSecretRequest, dict]] = None,
594 *,
595 parent: Optional[str] = None,
596 secret_id: Optional[str] = None,
597 secret: Optional[resources.Secret] = None,
598 retry: OptionalRetry = gapic_v1.method.DEFAULT,
599 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
600 metadata: Sequence[Tuple[str, str]] = (),
601 ) -> resources.Secret:
602 r"""Creates a new [Secret][google.cloud.secrets.v1beta1.Secret]
603 containing no
604 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion].
605
606 .. code-block:: python
607
608 # This snippet has been automatically generated and should be regarded as a
609 # code template only.
610 # It will require modifications to work:
611 # - It may require correct/in-range values for request initialization.
612 # - It may require specifying regional endpoints when creating the service
613 # client as shown in:
614 # https://googleapis.dev/python/google-api-core/latest/client_options.html
615 from google.cloud import secretmanager_v1beta1
616
617 def sample_create_secret():
618 # Create a client
619 client = secretmanager_v1beta1.SecretManagerServiceClient()
620
621 # Initialize request argument(s)
622 request = secretmanager_v1beta1.CreateSecretRequest(
623 parent="parent_value",
624 secret_id="secret_id_value",
625 )
626
627 # Make the request
628 response = client.create_secret(request=request)
629
630 # Handle the response
631 print(response)
632
633 Args:
634 request (Union[google.cloud.secretmanager_v1beta1.types.CreateSecretRequest, dict]):
635 The request object. Request message for
636 [SecretManagerService.CreateSecret][google.cloud.secrets.v1beta1.SecretManagerService.CreateSecret].
637 parent (str):
638 Required. The resource name of the project to associate
639 with the [Secret][google.cloud.secrets.v1beta1.Secret],
640 in the format ``projects/*``.
641
642 This corresponds to the ``parent`` field
643 on the ``request`` instance; if ``request`` is provided, this
644 should not be set.
645 secret_id (str):
646 Required. This must be unique within the project.
647
648 A secret ID is a string with a maximum length of 255
649 characters and can contain uppercase and lowercase
650 letters, numerals, and the hyphen (``-``) and underscore
651 (``_``) characters.
652
653 This corresponds to the ``secret_id`` field
654 on the ``request`` instance; if ``request`` is provided, this
655 should not be set.
656 secret (google.cloud.secretmanager_v1beta1.types.Secret):
657 Required. A
658 [Secret][google.cloud.secrets.v1beta1.Secret] with
659 initial field values.
660
661 This corresponds to the ``secret`` field
662 on the ``request`` instance; if ``request`` is provided, this
663 should not be set.
664 retry (google.api_core.retry.Retry): Designation of what errors, if any,
665 should be retried.
666 timeout (float): The timeout for this request.
667 metadata (Sequence[Tuple[str, str]]): Strings which should be
668 sent along with the request as metadata.
669
670 Returns:
671 google.cloud.secretmanager_v1beta1.types.Secret:
672 A [Secret][google.cloud.secrets.v1beta1.Secret] is a logical secret whose value and versions can
673 be accessed.
674
675 A [Secret][google.cloud.secrets.v1beta1.Secret] is
676 made up of zero or more
677 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]
678 that represent the secret data.
679
680 """
681 # Create or coerce a protobuf request object.
682 # Quick check: If we got a request object, we should *not* have
683 # gotten any keyword arguments that map to the request.
684 has_flattened_params = any([parent, secret_id, secret])
685 if request is not None and has_flattened_params:
686 raise ValueError(
687 "If the `request` argument is set, then none of "
688 "the individual field arguments should be set."
689 )
690
691 # Minor optimization to avoid making a copy if the user passes
692 # in a service.CreateSecretRequest.
693 # There's no risk of modifying the input as we've already verified
694 # there are no flattened fields.
695 if not isinstance(request, service.CreateSecretRequest):
696 request = service.CreateSecretRequest(request)
697 # If we have keyword arguments corresponding to fields on the
698 # request, apply these.
699 if parent is not None:
700 request.parent = parent
701 if secret_id is not None:
702 request.secret_id = secret_id
703 if secret is not None:
704 request.secret = secret
705
706 # Wrap the RPC method; this adds retry and timeout information,
707 # and friendly error handling.
708 rpc = self._transport._wrapped_methods[self._transport.create_secret]
709
710 # Certain fields should be provided within the metadata header;
711 # add these here.
712 metadata = tuple(metadata) + (
713 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
714 )
715
716 # Send the request.
717 response = rpc(
718 request,
719 retry=retry,
720 timeout=timeout,
721 metadata=metadata,
722 )
723
724 # Done; return the response.
725 return response
726
727 def add_secret_version(
728 self,
729 request: Optional[Union[service.AddSecretVersionRequest, dict]] = None,
730 *,
731 parent: Optional[str] = None,
732 payload: Optional[resources.SecretPayload] = None,
733 retry: OptionalRetry = gapic_v1.method.DEFAULT,
734 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
735 metadata: Sequence[Tuple[str, str]] = (),
736 ) -> resources.SecretVersion:
737 r"""Creates a new
738 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
739 containing secret data and attaches it to an existing
740 [Secret][google.cloud.secrets.v1beta1.Secret].
741
742 .. code-block:: python
743
744 # This snippet has been automatically generated and should be regarded as a
745 # code template only.
746 # It will require modifications to work:
747 # - It may require correct/in-range values for request initialization.
748 # - It may require specifying regional endpoints when creating the service
749 # client as shown in:
750 # https://googleapis.dev/python/google-api-core/latest/client_options.html
751 from google.cloud import secretmanager_v1beta1
752
753 def sample_add_secret_version():
754 # Create a client
755 client = secretmanager_v1beta1.SecretManagerServiceClient()
756
757 # Initialize request argument(s)
758 request = secretmanager_v1beta1.AddSecretVersionRequest(
759 parent="parent_value",
760 )
761
762 # Make the request
763 response = client.add_secret_version(request=request)
764
765 # Handle the response
766 print(response)
767
768 Args:
769 request (Union[google.cloud.secretmanager_v1beta1.types.AddSecretVersionRequest, dict]):
770 The request object. Request message for
771 [SecretManagerService.AddSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AddSecretVersion].
772 parent (str):
773 Required. The resource name of the
774 [Secret][google.cloud.secrets.v1beta1.Secret] to
775 associate with the
776 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
777 in the format ``projects/*/secrets/*``.
778
779 This corresponds to the ``parent`` field
780 on the ``request`` instance; if ``request`` is provided, this
781 should not be set.
782 payload (google.cloud.secretmanager_v1beta1.types.SecretPayload):
783 Required. The secret payload of the
784 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
785
786 This corresponds to the ``payload`` field
787 on the ``request`` instance; if ``request`` is provided, this
788 should not be set.
789 retry (google.api_core.retry.Retry): Designation of what errors, if any,
790 should be retried.
791 timeout (float): The timeout for this request.
792 metadata (Sequence[Tuple[str, str]]): Strings which should be
793 sent along with the request as metadata.
794
795 Returns:
796 google.cloud.secretmanager_v1beta1.types.SecretVersion:
797 A secret version resource in the
798 Secret Manager API.
799
800 """
801 # Create or coerce a protobuf request object.
802 # Quick check: If we got a request object, we should *not* have
803 # gotten any keyword arguments that map to the request.
804 has_flattened_params = any([parent, payload])
805 if request is not None and has_flattened_params:
806 raise ValueError(
807 "If the `request` argument is set, then none of "
808 "the individual field arguments should be set."
809 )
810
811 # Minor optimization to avoid making a copy if the user passes
812 # in a service.AddSecretVersionRequest.
813 # There's no risk of modifying the input as we've already verified
814 # there are no flattened fields.
815 if not isinstance(request, service.AddSecretVersionRequest):
816 request = service.AddSecretVersionRequest(request)
817 # If we have keyword arguments corresponding to fields on the
818 # request, apply these.
819 if parent is not None:
820 request.parent = parent
821 if payload is not None:
822 request.payload = payload
823
824 # Wrap the RPC method; this adds retry and timeout information,
825 # and friendly error handling.
826 rpc = self._transport._wrapped_methods[self._transport.add_secret_version]
827
828 # Certain fields should be provided within the metadata header;
829 # add these here.
830 metadata = tuple(metadata) + (
831 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
832 )
833
834 # Send the request.
835 response = rpc(
836 request,
837 retry=retry,
838 timeout=timeout,
839 metadata=metadata,
840 )
841
842 # Done; return the response.
843 return response
844
845 def get_secret(
846 self,
847 request: Optional[Union[service.GetSecretRequest, dict]] = None,
848 *,
849 name: Optional[str] = None,
850 retry: OptionalRetry = gapic_v1.method.DEFAULT,
851 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
852 metadata: Sequence[Tuple[str, str]] = (),
853 ) -> resources.Secret:
854 r"""Gets metadata for a given
855 [Secret][google.cloud.secrets.v1beta1.Secret].
856
857 .. code-block:: python
858
859 # This snippet has been automatically generated and should be regarded as a
860 # code template only.
861 # It will require modifications to work:
862 # - It may require correct/in-range values for request initialization.
863 # - It may require specifying regional endpoints when creating the service
864 # client as shown in:
865 # https://googleapis.dev/python/google-api-core/latest/client_options.html
866 from google.cloud import secretmanager_v1beta1
867
868 def sample_get_secret():
869 # Create a client
870 client = secretmanager_v1beta1.SecretManagerServiceClient()
871
872 # Initialize request argument(s)
873 request = secretmanager_v1beta1.GetSecretRequest(
874 name="name_value",
875 )
876
877 # Make the request
878 response = client.get_secret(request=request)
879
880 # Handle the response
881 print(response)
882
883 Args:
884 request (Union[google.cloud.secretmanager_v1beta1.types.GetSecretRequest, dict]):
885 The request object. Request message for
886 [SecretManagerService.GetSecret][google.cloud.secrets.v1beta1.SecretManagerService.GetSecret].
887 name (str):
888 Required. The resource name of the
889 [Secret][google.cloud.secrets.v1beta1.Secret], in the
890 format ``projects/*/secrets/*``.
891
892 This corresponds to the ``name`` field
893 on the ``request`` instance; if ``request`` is provided, this
894 should not be set.
895 retry (google.api_core.retry.Retry): Designation of what errors, if any,
896 should be retried.
897 timeout (float): The timeout for this request.
898 metadata (Sequence[Tuple[str, str]]): Strings which should be
899 sent along with the request as metadata.
900
901 Returns:
902 google.cloud.secretmanager_v1beta1.types.Secret:
903 A [Secret][google.cloud.secrets.v1beta1.Secret] is a logical secret whose value and versions can
904 be accessed.
905
906 A [Secret][google.cloud.secrets.v1beta1.Secret] is
907 made up of zero or more
908 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]
909 that represent the secret data.
910
911 """
912 # Create or coerce a protobuf request object.
913 # Quick check: If we got a request object, we should *not* have
914 # gotten any keyword arguments that map to the request.
915 has_flattened_params = any([name])
916 if request is not None and has_flattened_params:
917 raise ValueError(
918 "If the `request` argument is set, then none of "
919 "the individual field arguments should be set."
920 )
921
922 # Minor optimization to avoid making a copy if the user passes
923 # in a service.GetSecretRequest.
924 # There's no risk of modifying the input as we've already verified
925 # there are no flattened fields.
926 if not isinstance(request, service.GetSecretRequest):
927 request = service.GetSecretRequest(request)
928 # If we have keyword arguments corresponding to fields on the
929 # request, apply these.
930 if name is not None:
931 request.name = name
932
933 # Wrap the RPC method; this adds retry and timeout information,
934 # and friendly error handling.
935 rpc = self._transport._wrapped_methods[self._transport.get_secret]
936
937 # Certain fields should be provided within the metadata header;
938 # add these here.
939 metadata = tuple(metadata) + (
940 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
941 )
942
943 # Send the request.
944 response = rpc(
945 request,
946 retry=retry,
947 timeout=timeout,
948 metadata=metadata,
949 )
950
951 # Done; return the response.
952 return response
953
954 def update_secret(
955 self,
956 request: Optional[Union[service.UpdateSecretRequest, dict]] = None,
957 *,
958 secret: Optional[resources.Secret] = None,
959 update_mask: Optional[field_mask_pb2.FieldMask] = None,
960 retry: OptionalRetry = gapic_v1.method.DEFAULT,
961 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
962 metadata: Sequence[Tuple[str, str]] = (),
963 ) -> resources.Secret:
964 r"""Updates metadata of an existing
965 [Secret][google.cloud.secrets.v1beta1.Secret].
966
967 .. code-block:: python
968
969 # This snippet has been automatically generated and should be regarded as a
970 # code template only.
971 # It will require modifications to work:
972 # - It may require correct/in-range values for request initialization.
973 # - It may require specifying regional endpoints when creating the service
974 # client as shown in:
975 # https://googleapis.dev/python/google-api-core/latest/client_options.html
976 from google.cloud import secretmanager_v1beta1
977
978 def sample_update_secret():
979 # Create a client
980 client = secretmanager_v1beta1.SecretManagerServiceClient()
981
982 # Initialize request argument(s)
983 request = secretmanager_v1beta1.UpdateSecretRequest(
984 )
985
986 # Make the request
987 response = client.update_secret(request=request)
988
989 # Handle the response
990 print(response)
991
992 Args:
993 request (Union[google.cloud.secretmanager_v1beta1.types.UpdateSecretRequest, dict]):
994 The request object. Request message for
995 [SecretManagerService.UpdateSecret][google.cloud.secrets.v1beta1.SecretManagerService.UpdateSecret].
996 secret (google.cloud.secretmanager_v1beta1.types.Secret):
997 Required. [Secret][google.cloud.secrets.v1beta1.Secret]
998 with updated field values.
999
1000 This corresponds to the ``secret`` field
1001 on the ``request`` instance; if ``request`` is provided, this
1002 should not be set.
1003 update_mask (google.protobuf.field_mask_pb2.FieldMask):
1004 Required. Specifies the fields to be
1005 updated.
1006
1007 This corresponds to the ``update_mask`` field
1008 on the ``request`` instance; if ``request`` is provided, this
1009 should not be set.
1010 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1011 should be retried.
1012 timeout (float): The timeout for this request.
1013 metadata (Sequence[Tuple[str, str]]): Strings which should be
1014 sent along with the request as metadata.
1015
1016 Returns:
1017 google.cloud.secretmanager_v1beta1.types.Secret:
1018 A [Secret][google.cloud.secrets.v1beta1.Secret] is a logical secret whose value and versions can
1019 be accessed.
1020
1021 A [Secret][google.cloud.secrets.v1beta1.Secret] is
1022 made up of zero or more
1023 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]
1024 that represent the secret data.
1025
1026 """
1027 # Create or coerce a protobuf request object.
1028 # Quick check: If we got a request object, we should *not* have
1029 # gotten any keyword arguments that map to the request.
1030 has_flattened_params = any([secret, update_mask])
1031 if request is not None and has_flattened_params:
1032 raise ValueError(
1033 "If the `request` argument is set, then none of "
1034 "the individual field arguments should be set."
1035 )
1036
1037 # Minor optimization to avoid making a copy if the user passes
1038 # in a service.UpdateSecretRequest.
1039 # There's no risk of modifying the input as we've already verified
1040 # there are no flattened fields.
1041 if not isinstance(request, service.UpdateSecretRequest):
1042 request = service.UpdateSecretRequest(request)
1043 # If we have keyword arguments corresponding to fields on the
1044 # request, apply these.
1045 if secret is not None:
1046 request.secret = secret
1047 if update_mask is not None:
1048 request.update_mask = update_mask
1049
1050 # Wrap the RPC method; this adds retry and timeout information,
1051 # and friendly error handling.
1052 rpc = self._transport._wrapped_methods[self._transport.update_secret]
1053
1054 # Certain fields should be provided within the metadata header;
1055 # add these here.
1056 metadata = tuple(metadata) + (
1057 gapic_v1.routing_header.to_grpc_metadata(
1058 (("secret.name", request.secret.name),)
1059 ),
1060 )
1061
1062 # Send the request.
1063 response = rpc(
1064 request,
1065 retry=retry,
1066 timeout=timeout,
1067 metadata=metadata,
1068 )
1069
1070 # Done; return the response.
1071 return response
1072
1073 def delete_secret(
1074 self,
1075 request: Optional[Union[service.DeleteSecretRequest, dict]] = None,
1076 *,
1077 name: Optional[str] = None,
1078 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1079 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1080 metadata: Sequence[Tuple[str, str]] = (),
1081 ) -> None:
1082 r"""Deletes a [Secret][google.cloud.secrets.v1beta1.Secret].
1083
1084 .. code-block:: python
1085
1086 # This snippet has been automatically generated and should be regarded as a
1087 # code template only.
1088 # It will require modifications to work:
1089 # - It may require correct/in-range values for request initialization.
1090 # - It may require specifying regional endpoints when creating the service
1091 # client as shown in:
1092 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1093 from google.cloud import secretmanager_v1beta1
1094
1095 def sample_delete_secret():
1096 # Create a client
1097 client = secretmanager_v1beta1.SecretManagerServiceClient()
1098
1099 # Initialize request argument(s)
1100 request = secretmanager_v1beta1.DeleteSecretRequest(
1101 name="name_value",
1102 )
1103
1104 # Make the request
1105 client.delete_secret(request=request)
1106
1107 Args:
1108 request (Union[google.cloud.secretmanager_v1beta1.types.DeleteSecretRequest, dict]):
1109 The request object. Request message for
1110 [SecretManagerService.DeleteSecret][google.cloud.secrets.v1beta1.SecretManagerService.DeleteSecret].
1111 name (str):
1112 Required. The resource name of the
1113 [Secret][google.cloud.secrets.v1beta1.Secret] to delete
1114 in the format ``projects/*/secrets/*``.
1115
1116 This corresponds to the ``name`` field
1117 on the ``request`` instance; if ``request`` is provided, this
1118 should not be set.
1119 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1120 should be retried.
1121 timeout (float): The timeout for this request.
1122 metadata (Sequence[Tuple[str, str]]): Strings which should be
1123 sent along with the request as metadata.
1124 """
1125 # Create or coerce a protobuf request object.
1126 # Quick check: If we got a request object, we should *not* have
1127 # gotten any keyword arguments that map to the request.
1128 has_flattened_params = any([name])
1129 if request is not None and has_flattened_params:
1130 raise ValueError(
1131 "If the `request` argument is set, then none of "
1132 "the individual field arguments should be set."
1133 )
1134
1135 # Minor optimization to avoid making a copy if the user passes
1136 # in a service.DeleteSecretRequest.
1137 # There's no risk of modifying the input as we've already verified
1138 # there are no flattened fields.
1139 if not isinstance(request, service.DeleteSecretRequest):
1140 request = service.DeleteSecretRequest(request)
1141 # If we have keyword arguments corresponding to fields on the
1142 # request, apply these.
1143 if name is not None:
1144 request.name = name
1145
1146 # Wrap the RPC method; this adds retry and timeout information,
1147 # and friendly error handling.
1148 rpc = self._transport._wrapped_methods[self._transport.delete_secret]
1149
1150 # Certain fields should be provided within the metadata header;
1151 # add these here.
1152 metadata = tuple(metadata) + (
1153 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1154 )
1155
1156 # Send the request.
1157 rpc(
1158 request,
1159 retry=retry,
1160 timeout=timeout,
1161 metadata=metadata,
1162 )
1163
1164 def list_secret_versions(
1165 self,
1166 request: Optional[Union[service.ListSecretVersionsRequest, dict]] = None,
1167 *,
1168 parent: Optional[str] = None,
1169 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1170 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1171 metadata: Sequence[Tuple[str, str]] = (),
1172 ) -> pagers.ListSecretVersionsPager:
1173 r"""Lists
1174 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion].
1175 This call does not return secret data.
1176
1177 .. code-block:: python
1178
1179 # This snippet has been automatically generated and should be regarded as a
1180 # code template only.
1181 # It will require modifications to work:
1182 # - It may require correct/in-range values for request initialization.
1183 # - It may require specifying regional endpoints when creating the service
1184 # client as shown in:
1185 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1186 from google.cloud import secretmanager_v1beta1
1187
1188 def sample_list_secret_versions():
1189 # Create a client
1190 client = secretmanager_v1beta1.SecretManagerServiceClient()
1191
1192 # Initialize request argument(s)
1193 request = secretmanager_v1beta1.ListSecretVersionsRequest(
1194 parent="parent_value",
1195 )
1196
1197 # Make the request
1198 page_result = client.list_secret_versions(request=request)
1199
1200 # Handle the response
1201 for response in page_result:
1202 print(response)
1203
1204 Args:
1205 request (Union[google.cloud.secretmanager_v1beta1.types.ListSecretVersionsRequest, dict]):
1206 The request object. Request message for
1207 [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions].
1208 parent (str):
1209 Required. The resource name of the
1210 [Secret][google.cloud.secrets.v1beta1.Secret] associated
1211 with the
1212 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion]
1213 to list, in the format ``projects/*/secrets/*``.
1214
1215 This corresponds to the ``parent`` field
1216 on the ``request`` instance; if ``request`` is provided, this
1217 should not be set.
1218 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1219 should be retried.
1220 timeout (float): The timeout for this request.
1221 metadata (Sequence[Tuple[str, str]]): Strings which should be
1222 sent along with the request as metadata.
1223
1224 Returns:
1225 google.cloud.secretmanager_v1beta1.services.secret_manager_service.pagers.ListSecretVersionsPager:
1226 Response message for
1227 [SecretManagerService.ListSecretVersions][google.cloud.secrets.v1beta1.SecretManagerService.ListSecretVersions].
1228
1229 Iterating over this object will yield results and
1230 resolve additional pages automatically.
1231
1232 """
1233 # Create or coerce a protobuf request object.
1234 # Quick check: If we got a request object, we should *not* have
1235 # gotten any keyword arguments that map to the request.
1236 has_flattened_params = any([parent])
1237 if request is not None and has_flattened_params:
1238 raise ValueError(
1239 "If the `request` argument is set, then none of "
1240 "the individual field arguments should be set."
1241 )
1242
1243 # Minor optimization to avoid making a copy if the user passes
1244 # in a service.ListSecretVersionsRequest.
1245 # There's no risk of modifying the input as we've already verified
1246 # there are no flattened fields.
1247 if not isinstance(request, service.ListSecretVersionsRequest):
1248 request = service.ListSecretVersionsRequest(request)
1249 # If we have keyword arguments corresponding to fields on the
1250 # request, apply these.
1251 if parent is not None:
1252 request.parent = parent
1253
1254 # Wrap the RPC method; this adds retry and timeout information,
1255 # and friendly error handling.
1256 rpc = self._transport._wrapped_methods[self._transport.list_secret_versions]
1257
1258 # Certain fields should be provided within the metadata header;
1259 # add these here.
1260 metadata = tuple(metadata) + (
1261 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1262 )
1263
1264 # Send the request.
1265 response = rpc(
1266 request,
1267 retry=retry,
1268 timeout=timeout,
1269 metadata=metadata,
1270 )
1271
1272 # This method is paged; wrap the response in a pager, which provides
1273 # an `__iter__` convenience method.
1274 response = pagers.ListSecretVersionsPager(
1275 method=rpc,
1276 request=request,
1277 response=response,
1278 metadata=metadata,
1279 )
1280
1281 # Done; return the response.
1282 return response
1283
1284 def get_secret_version(
1285 self,
1286 request: Optional[Union[service.GetSecretVersionRequest, dict]] = None,
1287 *,
1288 name: Optional[str] = None,
1289 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1290 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1291 metadata: Sequence[Tuple[str, str]] = (),
1292 ) -> resources.SecretVersion:
1293 r"""Gets metadata for a
1294 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1295
1296 ``projects/*/secrets/*/versions/latest`` is an alias to the
1297 ``latest``
1298 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1299
1300 .. code-block:: python
1301
1302 # This snippet has been automatically generated and should be regarded as a
1303 # code template only.
1304 # It will require modifications to work:
1305 # - It may require correct/in-range values for request initialization.
1306 # - It may require specifying regional endpoints when creating the service
1307 # client as shown in:
1308 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1309 from google.cloud import secretmanager_v1beta1
1310
1311 def sample_get_secret_version():
1312 # Create a client
1313 client = secretmanager_v1beta1.SecretManagerServiceClient()
1314
1315 # Initialize request argument(s)
1316 request = secretmanager_v1beta1.GetSecretVersionRequest(
1317 name="name_value",
1318 )
1319
1320 # Make the request
1321 response = client.get_secret_version(request=request)
1322
1323 # Handle the response
1324 print(response)
1325
1326 Args:
1327 request (Union[google.cloud.secretmanager_v1beta1.types.GetSecretVersionRequest, dict]):
1328 The request object. Request message for
1329 [SecretManagerService.GetSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.GetSecretVersion].
1330 name (str):
1331 Required. The resource name of the
1332 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
1333 in the format ``projects/*/secrets/*/versions/*``.
1334 ``projects/*/secrets/*/versions/latest`` is an alias to
1335 the ``latest``
1336 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1337
1338 This corresponds to the ``name`` field
1339 on the ``request`` instance; if ``request`` is provided, this
1340 should not be set.
1341 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1342 should be retried.
1343 timeout (float): The timeout for this request.
1344 metadata (Sequence[Tuple[str, str]]): Strings which should be
1345 sent along with the request as metadata.
1346
1347 Returns:
1348 google.cloud.secretmanager_v1beta1.types.SecretVersion:
1349 A secret version resource in the
1350 Secret Manager API.
1351
1352 """
1353 # Create or coerce a protobuf request object.
1354 # Quick check: If we got a request object, we should *not* have
1355 # gotten any keyword arguments that map to the request.
1356 has_flattened_params = any([name])
1357 if request is not None and has_flattened_params:
1358 raise ValueError(
1359 "If the `request` argument is set, then none of "
1360 "the individual field arguments should be set."
1361 )
1362
1363 # Minor optimization to avoid making a copy if the user passes
1364 # in a service.GetSecretVersionRequest.
1365 # There's no risk of modifying the input as we've already verified
1366 # there are no flattened fields.
1367 if not isinstance(request, service.GetSecretVersionRequest):
1368 request = service.GetSecretVersionRequest(request)
1369 # If we have keyword arguments corresponding to fields on the
1370 # request, apply these.
1371 if name is not None:
1372 request.name = name
1373
1374 # Wrap the RPC method; this adds retry and timeout information,
1375 # and friendly error handling.
1376 rpc = self._transport._wrapped_methods[self._transport.get_secret_version]
1377
1378 # Certain fields should be provided within the metadata header;
1379 # add these here.
1380 metadata = tuple(metadata) + (
1381 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1382 )
1383
1384 # Send the request.
1385 response = rpc(
1386 request,
1387 retry=retry,
1388 timeout=timeout,
1389 metadata=metadata,
1390 )
1391
1392 # Done; return the response.
1393 return response
1394
1395 def access_secret_version(
1396 self,
1397 request: Optional[Union[service.AccessSecretVersionRequest, dict]] = None,
1398 *,
1399 name: Optional[str] = None,
1400 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1401 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1402 metadata: Sequence[Tuple[str, str]] = (),
1403 ) -> service.AccessSecretVersionResponse:
1404 r"""Accesses a
1405 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1406 This call returns the secret data.
1407
1408 ``projects/*/secrets/*/versions/latest`` is an alias to the
1409 ``latest``
1410 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1411
1412 .. code-block:: python
1413
1414 # This snippet has been automatically generated and should be regarded as a
1415 # code template only.
1416 # It will require modifications to work:
1417 # - It may require correct/in-range values for request initialization.
1418 # - It may require specifying regional endpoints when creating the service
1419 # client as shown in:
1420 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1421 from google.cloud import secretmanager_v1beta1
1422
1423 def sample_access_secret_version():
1424 # Create a client
1425 client = secretmanager_v1beta1.SecretManagerServiceClient()
1426
1427 # Initialize request argument(s)
1428 request = secretmanager_v1beta1.AccessSecretVersionRequest(
1429 name="name_value",
1430 )
1431
1432 # Make the request
1433 response = client.access_secret_version(request=request)
1434
1435 # Handle the response
1436 print(response)
1437
1438 Args:
1439 request (Union[google.cloud.secretmanager_v1beta1.types.AccessSecretVersionRequest, dict]):
1440 The request object. Request message for
1441 [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion].
1442 name (str):
1443 Required. The resource name of the
1444 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
1445 in the format ``projects/*/secrets/*/versions/*``.
1446
1447 This corresponds to the ``name`` field
1448 on the ``request`` instance; if ``request`` is provided, this
1449 should not be set.
1450 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1451 should be retried.
1452 timeout (float): The timeout for this request.
1453 metadata (Sequence[Tuple[str, str]]): Strings which should be
1454 sent along with the request as metadata.
1455
1456 Returns:
1457 google.cloud.secretmanager_v1beta1.types.AccessSecretVersionResponse:
1458 Response message for
1459 [SecretManagerService.AccessSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.AccessSecretVersion].
1460
1461 """
1462 # Create or coerce a protobuf request object.
1463 # Quick check: If we got a request object, we should *not* have
1464 # gotten any keyword arguments that map to the request.
1465 has_flattened_params = any([name])
1466 if request is not None and has_flattened_params:
1467 raise ValueError(
1468 "If the `request` argument is set, then none of "
1469 "the individual field arguments should be set."
1470 )
1471
1472 # Minor optimization to avoid making a copy if the user passes
1473 # in a service.AccessSecretVersionRequest.
1474 # There's no risk of modifying the input as we've already verified
1475 # there are no flattened fields.
1476 if not isinstance(request, service.AccessSecretVersionRequest):
1477 request = service.AccessSecretVersionRequest(request)
1478 # If we have keyword arguments corresponding to fields on the
1479 # request, apply these.
1480 if name is not None:
1481 request.name = name
1482
1483 # Wrap the RPC method; this adds retry and timeout information,
1484 # and friendly error handling.
1485 rpc = self._transport._wrapped_methods[self._transport.access_secret_version]
1486
1487 # Certain fields should be provided within the metadata header;
1488 # add these here.
1489 metadata = tuple(metadata) + (
1490 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1491 )
1492
1493 # Send the request.
1494 response = rpc(
1495 request,
1496 retry=retry,
1497 timeout=timeout,
1498 metadata=metadata,
1499 )
1500
1501 # Done; return the response.
1502 return response
1503
1504 def disable_secret_version(
1505 self,
1506 request: Optional[Union[service.DisableSecretVersionRequest, dict]] = None,
1507 *,
1508 name: Optional[str] = None,
1509 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1510 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1511 metadata: Sequence[Tuple[str, str]] = (),
1512 ) -> resources.SecretVersion:
1513 r"""Disables a
1514 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1515
1516 Sets the
1517 [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the
1518 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to
1519 [DISABLED][google.cloud.secrets.v1beta1.SecretVersion.State.DISABLED].
1520
1521 .. code-block:: python
1522
1523 # This snippet has been automatically generated and should be regarded as a
1524 # code template only.
1525 # It will require modifications to work:
1526 # - It may require correct/in-range values for request initialization.
1527 # - It may require specifying regional endpoints when creating the service
1528 # client as shown in:
1529 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1530 from google.cloud import secretmanager_v1beta1
1531
1532 def sample_disable_secret_version():
1533 # Create a client
1534 client = secretmanager_v1beta1.SecretManagerServiceClient()
1535
1536 # Initialize request argument(s)
1537 request = secretmanager_v1beta1.DisableSecretVersionRequest(
1538 name="name_value",
1539 )
1540
1541 # Make the request
1542 response = client.disable_secret_version(request=request)
1543
1544 # Handle the response
1545 print(response)
1546
1547 Args:
1548 request (Union[google.cloud.secretmanager_v1beta1.types.DisableSecretVersionRequest, dict]):
1549 The request object. Request message for
1550 [SecretManagerService.DisableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DisableSecretVersion].
1551 name (str):
1552 Required. The resource name of the
1553 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
1554 to disable in the format
1555 ``projects/*/secrets/*/versions/*``.
1556
1557 This corresponds to the ``name`` field
1558 on the ``request`` instance; if ``request`` is provided, this
1559 should not be set.
1560 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1561 should be retried.
1562 timeout (float): The timeout for this request.
1563 metadata (Sequence[Tuple[str, str]]): Strings which should be
1564 sent along with the request as metadata.
1565
1566 Returns:
1567 google.cloud.secretmanager_v1beta1.types.SecretVersion:
1568 A secret version resource in the
1569 Secret Manager API.
1570
1571 """
1572 # Create or coerce a protobuf request object.
1573 # Quick check: If we got a request object, we should *not* have
1574 # gotten any keyword arguments that map to the request.
1575 has_flattened_params = any([name])
1576 if request is not None and has_flattened_params:
1577 raise ValueError(
1578 "If the `request` argument is set, then none of "
1579 "the individual field arguments should be set."
1580 )
1581
1582 # Minor optimization to avoid making a copy if the user passes
1583 # in a service.DisableSecretVersionRequest.
1584 # There's no risk of modifying the input as we've already verified
1585 # there are no flattened fields.
1586 if not isinstance(request, service.DisableSecretVersionRequest):
1587 request = service.DisableSecretVersionRequest(request)
1588 # If we have keyword arguments corresponding to fields on the
1589 # request, apply these.
1590 if name is not None:
1591 request.name = name
1592
1593 # Wrap the RPC method; this adds retry and timeout information,
1594 # and friendly error handling.
1595 rpc = self._transport._wrapped_methods[self._transport.disable_secret_version]
1596
1597 # Certain fields should be provided within the metadata header;
1598 # add these here.
1599 metadata = tuple(metadata) + (
1600 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1601 )
1602
1603 # Send the request.
1604 response = rpc(
1605 request,
1606 retry=retry,
1607 timeout=timeout,
1608 metadata=metadata,
1609 )
1610
1611 # Done; return the response.
1612 return response
1613
1614 def enable_secret_version(
1615 self,
1616 request: Optional[Union[service.EnableSecretVersionRequest, dict]] = None,
1617 *,
1618 name: Optional[str] = None,
1619 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1620 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1621 metadata: Sequence[Tuple[str, str]] = (),
1622 ) -> resources.SecretVersion:
1623 r"""Enables a
1624 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1625
1626 Sets the
1627 [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the
1628 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to
1629 [ENABLED][google.cloud.secrets.v1beta1.SecretVersion.State.ENABLED].
1630
1631 .. code-block:: python
1632
1633 # This snippet has been automatically generated and should be regarded as a
1634 # code template only.
1635 # It will require modifications to work:
1636 # - It may require correct/in-range values for request initialization.
1637 # - It may require specifying regional endpoints when creating the service
1638 # client as shown in:
1639 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1640 from google.cloud import secretmanager_v1beta1
1641
1642 def sample_enable_secret_version():
1643 # Create a client
1644 client = secretmanager_v1beta1.SecretManagerServiceClient()
1645
1646 # Initialize request argument(s)
1647 request = secretmanager_v1beta1.EnableSecretVersionRequest(
1648 name="name_value",
1649 )
1650
1651 # Make the request
1652 response = client.enable_secret_version(request=request)
1653
1654 # Handle the response
1655 print(response)
1656
1657 Args:
1658 request (Union[google.cloud.secretmanager_v1beta1.types.EnableSecretVersionRequest, dict]):
1659 The request object. Request message for
1660 [SecretManagerService.EnableSecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.EnableSecretVersion].
1661 name (str):
1662 Required. The resource name of the
1663 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
1664 to enable in the format
1665 ``projects/*/secrets/*/versions/*``.
1666
1667 This corresponds to the ``name`` field
1668 on the ``request`` instance; if ``request`` is provided, this
1669 should not be set.
1670 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1671 should be retried.
1672 timeout (float): The timeout for this request.
1673 metadata (Sequence[Tuple[str, str]]): Strings which should be
1674 sent along with the request as metadata.
1675
1676 Returns:
1677 google.cloud.secretmanager_v1beta1.types.SecretVersion:
1678 A secret version resource in the
1679 Secret Manager API.
1680
1681 """
1682 # Create or coerce a protobuf request object.
1683 # Quick check: If we got a request object, we should *not* have
1684 # gotten any keyword arguments that map to the request.
1685 has_flattened_params = any([name])
1686 if request is not None and has_flattened_params:
1687 raise ValueError(
1688 "If the `request` argument is set, then none of "
1689 "the individual field arguments should be set."
1690 )
1691
1692 # Minor optimization to avoid making a copy if the user passes
1693 # in a service.EnableSecretVersionRequest.
1694 # There's no risk of modifying the input as we've already verified
1695 # there are no flattened fields.
1696 if not isinstance(request, service.EnableSecretVersionRequest):
1697 request = service.EnableSecretVersionRequest(request)
1698 # If we have keyword arguments corresponding to fields on the
1699 # request, apply these.
1700 if name is not None:
1701 request.name = name
1702
1703 # Wrap the RPC method; this adds retry and timeout information,
1704 # and friendly error handling.
1705 rpc = self._transport._wrapped_methods[self._transport.enable_secret_version]
1706
1707 # Certain fields should be provided within the metadata header;
1708 # add these here.
1709 metadata = tuple(metadata) + (
1710 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1711 )
1712
1713 # Send the request.
1714 response = rpc(
1715 request,
1716 retry=retry,
1717 timeout=timeout,
1718 metadata=metadata,
1719 )
1720
1721 # Done; return the response.
1722 return response
1723
1724 def destroy_secret_version(
1725 self,
1726 request: Optional[Union[service.DestroySecretVersionRequest, dict]] = None,
1727 *,
1728 name: Optional[str] = None,
1729 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1730 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1731 metadata: Sequence[Tuple[str, str]] = (),
1732 ) -> resources.SecretVersion:
1733 r"""Destroys a
1734 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion].
1735
1736 Sets the
1737 [state][google.cloud.secrets.v1beta1.SecretVersion.state] of the
1738 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion] to
1739 [DESTROYED][google.cloud.secrets.v1beta1.SecretVersion.State.DESTROYED]
1740 and irrevocably destroys the secret data.
1741
1742 .. code-block:: python
1743
1744 # This snippet has been automatically generated and should be regarded as a
1745 # code template only.
1746 # It will require modifications to work:
1747 # - It may require correct/in-range values for request initialization.
1748 # - It may require specifying regional endpoints when creating the service
1749 # client as shown in:
1750 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1751 from google.cloud import secretmanager_v1beta1
1752
1753 def sample_destroy_secret_version():
1754 # Create a client
1755 client = secretmanager_v1beta1.SecretManagerServiceClient()
1756
1757 # Initialize request argument(s)
1758 request = secretmanager_v1beta1.DestroySecretVersionRequest(
1759 name="name_value",
1760 )
1761
1762 # Make the request
1763 response = client.destroy_secret_version(request=request)
1764
1765 # Handle the response
1766 print(response)
1767
1768 Args:
1769 request (Union[google.cloud.secretmanager_v1beta1.types.DestroySecretVersionRequest, dict]):
1770 The request object. Request message for
1771 [SecretManagerService.DestroySecretVersion][google.cloud.secrets.v1beta1.SecretManagerService.DestroySecretVersion].
1772 name (str):
1773 Required. The resource name of the
1774 [SecretVersion][google.cloud.secrets.v1beta1.SecretVersion]
1775 to destroy in the format
1776 ``projects/*/secrets/*/versions/*``.
1777
1778 This corresponds to the ``name`` field
1779 on the ``request`` instance; if ``request`` is provided, this
1780 should not be set.
1781 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1782 should be retried.
1783 timeout (float): The timeout for this request.
1784 metadata (Sequence[Tuple[str, str]]): Strings which should be
1785 sent along with the request as metadata.
1786
1787 Returns:
1788 google.cloud.secretmanager_v1beta1.types.SecretVersion:
1789 A secret version resource in the
1790 Secret Manager API.
1791
1792 """
1793 # Create or coerce a protobuf request object.
1794 # Quick check: If we got a request object, we should *not* have
1795 # gotten any keyword arguments that map to the request.
1796 has_flattened_params = any([name])
1797 if request is not None and has_flattened_params:
1798 raise ValueError(
1799 "If the `request` argument is set, then none of "
1800 "the individual field arguments should be set."
1801 )
1802
1803 # Minor optimization to avoid making a copy if the user passes
1804 # in a service.DestroySecretVersionRequest.
1805 # There's no risk of modifying the input as we've already verified
1806 # there are no flattened fields.
1807 if not isinstance(request, service.DestroySecretVersionRequest):
1808 request = service.DestroySecretVersionRequest(request)
1809 # If we have keyword arguments corresponding to fields on the
1810 # request, apply these.
1811 if name is not None:
1812 request.name = name
1813
1814 # Wrap the RPC method; this adds retry and timeout information,
1815 # and friendly error handling.
1816 rpc = self._transport._wrapped_methods[self._transport.destroy_secret_version]
1817
1818 # Certain fields should be provided within the metadata header;
1819 # add these here.
1820 metadata = tuple(metadata) + (
1821 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1822 )
1823
1824 # Send the request.
1825 response = rpc(
1826 request,
1827 retry=retry,
1828 timeout=timeout,
1829 metadata=metadata,
1830 )
1831
1832 # Done; return the response.
1833 return response
1834
1835 def set_iam_policy(
1836 self,
1837 request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
1838 *,
1839 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1840 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1841 metadata: Sequence[Tuple[str, str]] = (),
1842 ) -> policy_pb2.Policy:
1843 r"""Sets the access control policy on the specified secret. Replaces
1844 any existing policy.
1845
1846 Permissions on
1847 [SecretVersions][google.cloud.secrets.v1beta1.SecretVersion] are
1848 enforced according to the policy set on the associated
1849 [Secret][google.cloud.secrets.v1beta1.Secret].
1850
1851 .. code-block:: python
1852
1853 # This snippet has been automatically generated and should be regarded as a
1854 # code template only.
1855 # It will require modifications to work:
1856 # - It may require correct/in-range values for request initialization.
1857 # - It may require specifying regional endpoints when creating the service
1858 # client as shown in:
1859 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1860 from google.cloud import secretmanager_v1beta1
1861 from google.iam.v1 import iam_policy_pb2 # type: ignore
1862
1863 def sample_set_iam_policy():
1864 # Create a client
1865 client = secretmanager_v1beta1.SecretManagerServiceClient()
1866
1867 # Initialize request argument(s)
1868 request = iam_policy_pb2.SetIamPolicyRequest(
1869 resource="resource_value",
1870 )
1871
1872 # Make the request
1873 response = client.set_iam_policy(request=request)
1874
1875 # Handle the response
1876 print(response)
1877
1878 Args:
1879 request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
1880 The request object. Request message for ``SetIamPolicy`` method.
1881 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1882 should be retried.
1883 timeout (float): The timeout for this request.
1884 metadata (Sequence[Tuple[str, str]]): Strings which should be
1885 sent along with the request as metadata.
1886
1887 Returns:
1888 google.iam.v1.policy_pb2.Policy:
1889 An Identity and Access Management (IAM) policy, which specifies access
1890 controls for Google Cloud resources.
1891
1892 A Policy is a collection of bindings. A binding binds
1893 one or more members, or principals, to a single role.
1894 Principals can be user accounts, service accounts,
1895 Google groups, and domains (such as G Suite). A role
1896 is a named list of permissions; each role can be an
1897 IAM predefined role or a user-created custom role.
1898
1899 For some types of Google Cloud resources, a binding
1900 can also specify a condition, which is a logical
1901 expression that allows access to a resource only if
1902 the expression evaluates to true. A condition can add
1903 constraints based on attributes of the request, the
1904 resource, or both. To learn which resources support
1905 conditions in their IAM policies, see the [IAM
1906 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
1907
1908 **JSON example:**
1909
1910 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
1911
1912 **YAML example:**
1913
1914 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
1915
1916 For a description of IAM and its features, see the
1917 [IAM
1918 documentation](\ https://cloud.google.com/iam/docs/).
1919
1920 """
1921 # Create or coerce a protobuf request object.
1922 if isinstance(request, dict):
1923 # The request isn't a proto-plus wrapped type,
1924 # so it must be constructed via keyword expansion.
1925 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1926 elif not request:
1927 # Null request, just make one.
1928 request = iam_policy_pb2.SetIamPolicyRequest()
1929
1930 # Wrap the RPC method; this adds retry and timeout information,
1931 # and friendly error handling.
1932 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
1933
1934 # Certain fields should be provided within the metadata header;
1935 # add these here.
1936 metadata = tuple(metadata) + (
1937 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1938 )
1939
1940 # Send the request.
1941 response = rpc(
1942 request,
1943 retry=retry,
1944 timeout=timeout,
1945 metadata=metadata,
1946 )
1947
1948 # Done; return the response.
1949 return response
1950
1951 def get_iam_policy(
1952 self,
1953 request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
1954 *,
1955 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1956 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1957 metadata: Sequence[Tuple[str, str]] = (),
1958 ) -> policy_pb2.Policy:
1959 r"""Gets the access control policy for a secret.
1960 Returns empty policy if the secret exists and does not
1961 have a policy set.
1962
1963 .. code-block:: python
1964
1965 # This snippet has been automatically generated and should be regarded as a
1966 # code template only.
1967 # It will require modifications to work:
1968 # - It may require correct/in-range values for request initialization.
1969 # - It may require specifying regional endpoints when creating the service
1970 # client as shown in:
1971 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1972 from google.cloud import secretmanager_v1beta1
1973 from google.iam.v1 import iam_policy_pb2 # type: ignore
1974
1975 def sample_get_iam_policy():
1976 # Create a client
1977 client = secretmanager_v1beta1.SecretManagerServiceClient()
1978
1979 # Initialize request argument(s)
1980 request = iam_policy_pb2.GetIamPolicyRequest(
1981 resource="resource_value",
1982 )
1983
1984 # Make the request
1985 response = client.get_iam_policy(request=request)
1986
1987 # Handle the response
1988 print(response)
1989
1990 Args:
1991 request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
1992 The request object. Request message for ``GetIamPolicy`` method.
1993 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1994 should be retried.
1995 timeout (float): The timeout for this request.
1996 metadata (Sequence[Tuple[str, str]]): Strings which should be
1997 sent along with the request as metadata.
1998
1999 Returns:
2000 google.iam.v1.policy_pb2.Policy:
2001 An Identity and Access Management (IAM) policy, which specifies access
2002 controls for Google Cloud resources.
2003
2004 A Policy is a collection of bindings. A binding binds
2005 one or more members, or principals, to a single role.
2006 Principals can be user accounts, service accounts,
2007 Google groups, and domains (such as G Suite). A role
2008 is a named list of permissions; each role can be an
2009 IAM predefined role or a user-created custom role.
2010
2011 For some types of Google Cloud resources, a binding
2012 can also specify a condition, which is a logical
2013 expression that allows access to a resource only if
2014 the expression evaluates to true. A condition can add
2015 constraints based on attributes of the request, the
2016 resource, or both. To learn which resources support
2017 conditions in their IAM policies, see the [IAM
2018 documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies).
2019
2020 **JSON example:**
2021
2022 :literal:`\` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
2023
2024 **YAML example:**
2025
2026 :literal:`\` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
2027
2028 For a description of IAM and its features, see the
2029 [IAM
2030 documentation](\ https://cloud.google.com/iam/docs/).
2031
2032 """
2033 # Create or coerce a protobuf request object.
2034 if isinstance(request, dict):
2035 # The request isn't a proto-plus wrapped type,
2036 # so it must be constructed via keyword expansion.
2037 request = iam_policy_pb2.GetIamPolicyRequest(**request)
2038 elif not request:
2039 # Null request, just make one.
2040 request = iam_policy_pb2.GetIamPolicyRequest()
2041
2042 # Wrap the RPC method; this adds retry and timeout information,
2043 # and friendly error handling.
2044 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
2045
2046 # Certain fields should be provided within the metadata header;
2047 # add these here.
2048 metadata = tuple(metadata) + (
2049 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2050 )
2051
2052 # Send the request.
2053 response = rpc(
2054 request,
2055 retry=retry,
2056 timeout=timeout,
2057 metadata=metadata,
2058 )
2059
2060 # Done; return the response.
2061 return response
2062
2063 def test_iam_permissions(
2064 self,
2065 request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None,
2066 *,
2067 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2068 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2069 metadata: Sequence[Tuple[str, str]] = (),
2070 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2071 r"""Returns permissions that a caller has for the specified secret.
2072 If the secret does not exist, this call returns an empty set of
2073 permissions, not a NOT_FOUND error.
2074
2075 Note: This operation is designed to be used for building
2076 permission-aware UIs and command-line tools, not for
2077 authorization checking. This operation may "fail open" without
2078 warning.
2079
2080 .. code-block:: python
2081
2082 # This snippet has been automatically generated and should be regarded as a
2083 # code template only.
2084 # It will require modifications to work:
2085 # - It may require correct/in-range values for request initialization.
2086 # - It may require specifying regional endpoints when creating the service
2087 # client as shown in:
2088 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2089 from google.cloud import secretmanager_v1beta1
2090 from google.iam.v1 import iam_policy_pb2 # type: ignore
2091
2092 def sample_test_iam_permissions():
2093 # Create a client
2094 client = secretmanager_v1beta1.SecretManagerServiceClient()
2095
2096 # Initialize request argument(s)
2097 request = iam_policy_pb2.TestIamPermissionsRequest(
2098 resource="resource_value",
2099 permissions=['permissions_value1', 'permissions_value2'],
2100 )
2101
2102 # Make the request
2103 response = client.test_iam_permissions(request=request)
2104
2105 # Handle the response
2106 print(response)
2107
2108 Args:
2109 request (Union[google.iam.v1.iam_policy_pb2.TestIamPermissionsRequest, dict]):
2110 The request object. Request message for ``TestIamPermissions`` method.
2111 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2112 should be retried.
2113 timeout (float): The timeout for this request.
2114 metadata (Sequence[Tuple[str, str]]): Strings which should be
2115 sent along with the request as metadata.
2116
2117 Returns:
2118 google.iam.v1.iam_policy_pb2.TestIamPermissionsResponse:
2119 Response message for TestIamPermissions method.
2120 """
2121 # Create or coerce a protobuf request object.
2122 if isinstance(request, dict):
2123 # The request isn't a proto-plus wrapped type,
2124 # so it must be constructed via keyword expansion.
2125 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
2126 elif not request:
2127 # Null request, just make one.
2128 request = iam_policy_pb2.TestIamPermissionsRequest()
2129
2130 # Wrap the RPC method; this adds retry and timeout information,
2131 # and friendly error handling.
2132 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
2133
2134 # Certain fields should be provided within the metadata header;
2135 # add these here.
2136 metadata = tuple(metadata) + (
2137 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2138 )
2139
2140 # Send the request.
2141 response = rpc(
2142 request,
2143 retry=retry,
2144 timeout=timeout,
2145 metadata=metadata,
2146 )
2147
2148 # Done; return the response.
2149 return response
2150
2151 def __enter__(self) -> "SecretManagerServiceClient":
2152 return self
2153
2154 def __exit__(self, type, value, traceback):
2155 """Releases underlying transport's resources.
2156
2157 .. warning::
2158 ONLY use as a context manager if the transport is NOT shared
2159 with other clients! Exiting the with block will CLOSE the transport
2160 and may cause errors in other clients!
2161 """
2162 self.transport.close()
2163
2164
2165DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2166 gapic_version=package_version.__version__
2167)
2168
2169
2170__all__ = ("SecretManagerServiceClient",)