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