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