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