azure.keyvault.secrets package¶
- class azure.keyvault.secrets.ApiVersion(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]¶
Key Vault API versions supported by this package
- capitalize()¶
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower case.
- casefold()¶
Return a version of the string suitable for caseless comparisons.
- center(width, fillchar=' ', /)¶
Return a centered string of length width.
Padding is done using the specified fill character (default is a space).
- count(sub[, start[, end]]) int ¶
Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.
- encode(encoding='utf-8', errors='strict')¶
Encode the string using the codec registered for encoding.
- encoding
The encoding in which to encode the string.
- errors
The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.
- endswith(suffix[, start[, end]]) bool ¶
Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.
- expandtabs(tabsize=8)¶
Return a copy where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
- find(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- format(*args, **kwargs) str ¶
Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).
- format_map(mapping) str ¶
Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).
- index(sub[, start[, end]]) int ¶
Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- isalnum()¶
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.
- isalpha()¶
Return True if the string is an alphabetic string, False otherwise.
A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.
- isascii()¶
Return True if all characters in the string are ASCII, False otherwise.
ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.
- isdecimal()¶
Return True if the string is a decimal string, False otherwise.
A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
- isdigit()¶
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
- isidentifier()¶
Return True if the string is a valid Python identifier, False otherwise.
Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.
- islower()¶
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
- isnumeric()¶
Return True if the string is a numeric string, False otherwise.
A string is numeric if all characters in the string are numeric and there is at least one character in the string.
- isprintable()¶
Return True if the string is printable, False otherwise.
A string is printable if all of its characters are considered printable in repr() or if it is empty.
- isspace()¶
Return True if the string is a whitespace string, False otherwise.
A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.
- istitle()¶
Return True if the string is a title-cased string, False otherwise.
In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.
- isupper()¶
Return True if the string is an uppercase string, False otherwise.
A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.
- join(iterable, /)¶
Concatenate any number of strings.
The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’
- ljust(width, fillchar=' ', /)¶
Return a left-justified string of length width.
Padding is done using the specified fill character (default is a space).
- lower()¶
Return a copy of the string converted to lowercase.
- lstrip(chars=None, /)¶
Return a copy of the string with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
- static maketrans()¶
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
- partition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original string and two empty strings.
- removeprefix(prefix, /)¶
Return a str with the given prefix string removed if present.
If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.
- removesuffix(suffix, /)¶
Return a str with the given suffix string removed if present.
If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.
- replace(old, new, count=-1, /)¶
Return a copy with all occurrences of substring old replaced by new.
- count
Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are replaced.
- rfind(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Return -1 on failure.
- rindex(sub[, start[, end]]) int ¶
Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.
Raises ValueError when the substring is not found.
- rjust(width, fillchar=' ', /)¶
Return a right-justified string of length width.
Padding is done using the specified fill character (default is a space).
- rpartition(sep, /)¶
Partition the string into three parts using the given separator.
This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty strings and the original string.
- rsplit(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the end of the string and works to the front.
- rstrip(chars=None, /)¶
Return a copy of the string with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- split(sep=None, maxsplit=-1)¶
Return a list of the substrings in the string, using sep as the separator string.
- sep
The separator used to split the string.
When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.
- maxsplit
Maximum number of splits. -1 (the default value) means no limit.
Splitting starts at the front of the string and works to the end.
Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.
- splitlines(keepends=False)¶
Return a list of the lines in the string, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and true.
- startswith(prefix[, start[, end]]) bool ¶
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
- strip(chars=None, /)¶
Return a copy of the string with leading and trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
- swapcase()¶
Convert uppercase characters to lowercase and lowercase characters to uppercase.
- title()¶
Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.
- translate(table, /)¶
Replace each character in the string using the given translation table.
- table
Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.
- upper()¶
Return a copy of the string converted to uppercase.
- zfill(width, /)¶
Pad a numeric string with zeros on the left, to fill a field of the given width.
The string is never truncated.
- V2016_10_01 = '2016-10-01'¶
- V7_0 = '7.0'¶
- V7_1 = '7.1'¶
- V7_2 = '7.2'¶
- V7_3 = '7.3'¶
- V7_4 = '7.4'¶
- V7_5 = '7.5'¶
this is the default version
- class azure.keyvault.secrets.DeletedSecret(properties: SecretProperties, deleted_date: datetime | None = None, recovery_id: str | None = None, scheduled_purge_date: datetime | None = None)[source]¶
A deleted secret’s properties and information about its deletion.
If soft-delete is enabled, returns information about its recovery as well.
- Parameters:
properties (SecretProperties) – The deleted secret’s properties.
deleted_date (datetime or None) – When the secret was deleted, in UTC.
recovery_id (str or None) – An identifier used to recover the deleted secret.
scheduled_purge_date (datetime or None) – When the secret is scheduled to be purged by Key Vault, in UTC.
- property deleted_date: datetime | None¶
When the secret was deleted, in UTC.
- Returns:
When the secret was deleted, in UTC.
- Return type:
datetime or None
- property properties: SecretProperties¶
The properties of the deleted secret.
- Returns:
The properties of the deleted secret.
- Return type:
- class azure.keyvault.secrets.KeyVaultSecret(properties: SecretProperties, value: str | None)[source]¶
All of a secret’s properties, and its value.
- Parameters:
properties (SecretProperties) – The secret’s properties.
value (str or None) – The value of the secret.
- property properties: SecretProperties¶
The secret’s properties.
- Returns:
The secret’s properties.
- Return type:
- class azure.keyvault.secrets.KeyVaultSecretIdentifier(source_id: str)[source]¶
Information about a KeyVaultSecret parsed from a secret ID.
- Parameters:
source_id (str) – the full original identifier of a secret
- Raises:
ValueError – if the secret ID is improperly formatted
Example
secret = client.get_secret(secret_name) parsed_secret_id = KeyVaultSecretIdentifier(secret.id) print(parsed_secret_id.name) print(parsed_secret_id.vault_url) print(parsed_secret_id.version) print(parsed_secret_id.source_id)
- class azure.keyvault.secrets.SecretClient(vault_url: str, credential: TokenCredential, **kwargs: Any)[source]¶
A high-level interface for managing a vault’s secrets.
- Parameters:
vault_url (str) – URL of the vault the client will access. This is also called the vault’s “DNS Name”. You should validate that this URL references a valid Key Vault resource. See https://aka.ms/azsdk/blog/vault-uri for details.
credential (TokenCredential) – An object which can provide an access token for the vault, such as a credential from
azure.identity
- Keyword Arguments:
api_version (ApiVersion or str) – Version of the service API to use. Defaults to the most recent.
verify_challenge_resource (bool) – Whether to verify the authentication challenge resource matches the Key Vault domain. Defaults to True.
Example
from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient # Create a SecretClient using default Azure credentials credential = DefaultAzureCredential() secret_client = SecretClient(vault_url, credential)
- backup_secret(name: str, **kwargs: Any) bytes [source]¶
Back up a secret in a protected form useable only by Azure Key Vault. Requires secrets/backup permission.
- Parameters:
name (str) – Name of the secret to back up
- Returns:
The backup result, in a protected bytes format that can only be used by Azure Key Vault.
- Return type:
- Raises:
ResourceNotFoundError or HttpResponseError – the former if the secret doesn’t exist; the latter for other errors
Example
# backup secret # returns the raw bytes of the backed up secret secret_backup = secret_client.backup_secret(secret_name) print(secret_backup)
- begin_delete_secret(name: str, **kwargs: Any) LROPoller[DeletedSecret] [source]¶
Delete all versions of a secret. Requires secrets/delete permission.
When this method returns Key Vault has begun deleting the secret. Deletion may take several seconds in a vault with soft-delete enabled. This method therefore returns a poller enabling you to wait for deletion to complete.
- Parameters:
name (str) – Name of the secret to delete.
- Returns:
A poller for the delete operation. The poller’s result method returns the
DeletedSecret
without waiting for deletion to complete. If the vault has soft-delete enabled and you want to permanently delete the secret withpurge_deleted_secret()
, call the poller’s wait method first. It will block until the deletion is complete. The wait method requires secrets/get permission.- Return type:
- Raises:
ResourceNotFoundError or HttpResponseError – the former if the secret doesn’t exist; the latter for other errors
Example
# delete a secret deleted_secret_poller = secret_client.begin_delete_secret(secret_name) deleted_secret = deleted_secret_poller.result() print(deleted_secret.name) # if the vault has soft-delete enabled, the secret's, deleted_date # scheduled purge date and recovery id are set print(deleted_secret.deleted_date) print(deleted_secret.scheduled_purge_date) print(deleted_secret.recovery_id) # if you want to block until secret is deleted server-side, call wait() on the poller deleted_secret_poller.wait()
- begin_recover_deleted_secret(name: str, **kwargs: Any) LROPoller[SecretProperties] [source]¶
Recover a deleted secret to its latest version. Possible only in a vault with soft-delete enabled.
Requires the secrets/recover permission. If the vault does not have soft-delete enabled,
begin_delete_secret()
is permanent, and this method will return an error. Attempting to recover a non-deleted secret will also return an error. When this method returns Key Vault has begun recovering the secret. Recovery may take several seconds. This method therefore returns a poller enabling you to wait for recovery to complete. Waiting is only necessary when you want to use the recovered secret in another operation immediately.- Parameters:
name (str) – Name of the deleted secret to recover
- Returns:
A poller for the recovery operation. The poller’s result method returns the recovered secret’s
SecretProperties
without waiting for recovery to complete. If you want to use the recovered secret immediately, call the poller’s wait method, which blocks until the secret is ready to use. The wait method requires secrets/get permission.- Return type:
- Raises:
Example
# recover deleted secret to the latest version recover_secret_poller = secret_client.begin_recover_deleted_secret(secret_name) recovered_secret = recover_secret_poller.result() print(recovered_secret.id) print(recovered_secret.name) # if you want to block until secret is recovered server-side, call wait() on the poller recover_secret_poller.wait()
- close() None ¶
Close sockets opened by the client.
Calling this method is unnecessary when using the client as a context manager.
- get_deleted_secret(name: str, **kwargs: Any) DeletedSecret [source]¶
Get a deleted secret. Possible only in vaults with soft-delete enabled. Requires secrets/get permission.
- Parameters:
name (str) – Name of the deleted secret
- Returns:
The deleted secret.
- Return type:
- Raises:
ResourceNotFoundError or HttpResponseError – the former if the deleted secret doesn’t exist; the latter for other errors
Example
# gets a deleted secret (requires soft-delete enabled for the vault) deleted_secret = secret_client.get_deleted_secret(secret_name) print(deleted_secret.name)
- get_secret(name: str, version: str | None = None, **kwargs: Any) KeyVaultSecret [source]¶
Get a secret. Requires the secrets/get permission.
- Parameters:
- Returns:
The fetched secret.
- Return type:
- Raises:
ResourceNotFoundError or HttpResponseError – the former if the secret doesn’t exist; the latter for other errors
Example
# get the latest version of a secret secret = secret_client.get_secret(secret_name) # alternatively, specify a version secret = secret_client.get_secret(secret_name, secret.properties.version) print(secret.id) print(secret.name) print(secret.properties.version) print(secret.properties.vault_url)
- list_deleted_secrets(**kwargs: Any) ItemPaged[DeletedSecret] [source]¶
Lists all deleted secrets. Possible only in vaults with soft-delete enabled.
Requires secrets/list permission.
- Returns:
An iterator of deleted secrets, excluding their values
- Return type:
Example
# gets an iterator of deleted secrets (requires soft-delete enabled for the vault) deleted_secrets = secret_client.list_deleted_secrets() for secret in deleted_secrets: # the list doesn't include values or versions of the deleted secrets print(secret.id) print(secret.name) print(secret.scheduled_purge_date) print(secret.recovery_id) print(secret.deleted_date)
- list_properties_of_secret_versions(name: str, **kwargs: Any) ItemPaged[SecretProperties] [source]¶
List properties of all versions of a secret, excluding their values. Requires secrets/list permission.
List items don’t include secret values. Use
get_secret()
to get a secret’s value.- Parameters:
name (str) – Name of the secret
- Returns:
An iterator of secrets, excluding their values
- Return type:
Example
secret_versions = secret_client.list_properties_of_secret_versions("secret-name") for secret in secret_versions: # the list doesn't include the values at each version print(secret.id) print(secret.enabled) print(secret.updated_on)
- list_properties_of_secrets(**kwargs: Any) ItemPaged[SecretProperties] [source]¶
List identifiers and attributes of all secrets in the vault. Requires secrets/list permission.
List items don’t include secret values. Use
get_secret()
to get a secret’s value.- Returns:
An iterator of secrets, excluding their values
- Return type:
Example
# list secrets secrets = secret_client.list_properties_of_secrets() for secret in secrets: # the list doesn't include values or versions of the secrets print(secret.id) print(secret.name) print(secret.enabled)
- purge_deleted_secret(name: str, **kwargs: Any) None [source]¶
Permanently deletes a deleted secret. Possible only in vaults with soft-delete enabled.
Performs an irreversible deletion of the specified secret, without possibility for recovery. The operation is not available if the
recovery_level
does not specify ‘Purgeable’. This method is only necessary for purging a secret before itsscheduled_purge_date
.Requires secrets/purge permission.
- Parameters:
name (str) – Name of the deleted secret to purge
- Returns:
None
- Raises:
Example
# if the vault has soft-delete enabled, purge permanently deletes the secret # (with soft-delete disabled, begin_delete_secret is permanent) secret_client.purge_deleted_secret("secret-name")
- restore_secret_backup(backup: bytes, **kwargs: Any) SecretProperties [source]¶
Restore a backed up secret. Requires the secrets/restore permission.
- Parameters:
backup (bytes) – A secret backup as returned by
backup_secret()
- Returns:
The restored secret
- Return type:
- Raises:
ResourceExistsError or HttpResponseError – the former if the secret’s name is already in use; the latter for other errors
Example
# restores a backed up secret restored_secret = secret_client.restore_secret_backup(secret_backup) print(restored_secret.id) print(restored_secret.version)
- send_request(request: HttpRequest, *, stream: bool = False, **kwargs: Any) HttpResponse ¶
Runs a network request using the client’s existing pipeline.
The request URL can be relative to the vault URL. The service API version used for the request is the same as the client’s unless otherwise specified. This method does not raise if the response is an error; to raise an exception, call raise_for_status() on the returned response object. For more information about how to send custom requests with this method, see https://aka.ms/azsdk/dpcodegen/python/send_request.
- Parameters:
request (HttpRequest) – The network request you want to make.
- Keyword Arguments:
stream (bool) – Whether the response payload will be streamed. Defaults to False.
- Returns:
The response of your network call. Does not do error handling on your response.
- Return type:
- set_secret(name: str, value: str, *, enabled: bool | None = None, tags: Dict[str, str] | None = None, content_type: str | None = None, not_before: datetime | None = None, expires_on: datetime | None = None, **kwargs: Any) KeyVaultSecret [source]¶
Set a secret value. If name is in use, create a new version of the secret. If not, create a new secret.
Requires secrets/set permission.
- Parameters:
- Keyword Arguments:
enabled (bool) – Whether the secret is enabled for use.
tags (Dict[str, str] or None) – Application specific metadata in the form of key-value pairs.
content_type (str) – An arbitrary string indicating the type of the secret, e.g. ‘password’
not_before (datetime) – Not before date of the secret in UTC
expires_on (datetime) – Expiry date of the secret in UTC
- Returns:
The created or updated secret.
- Return type:
- Raises:
Example
from dateutil import parser as date_parse expires_on = date_parse.parse("2050-02-02T08:00:00.000Z") # create a secret, setting optional arguments secret = secret_client.set_secret(secret_name, "secret-value", expires_on=expires_on) print(secret.name) print(secret.properties.version) print(secret.properties.expires_on)
- update_secret_properties(name: str, version: str | None = None, *, enabled: bool | None = None, tags: Dict[str, str] | None = None, content_type: str | None = None, not_before: datetime | None = None, expires_on: datetime | None = None, **kwargs: Any) SecretProperties [source]¶
Update properties of a secret other than its value. Requires secrets/set permission.
This method updates properties of the secret, such as whether it’s enabled, but can’t change the secret’s value. Use
set_secret()
to change the secret’s value.- Parameters:
- Keyword Arguments:
enabled (bool) – Whether the secret is enabled for use.
tags (Dict[str, str] or None) – Application specific metadata in the form of key-value pairs.
content_type (str) – An arbitrary string indicating the type of the secret, e.g. ‘password’
not_before (datetime) – Not before date of the secret in UTC
expires_on (datetime) – Expiry date of the secret in UTC
- Returns:
The updated secret properties.
- Return type:
- Raises:
ResourceNotFoundError or HttpResponseError – the former if the secret doesn’t exist; the latter for other errors
Example
# update attributes of an existing secret content_type = "text/plain" tags = {"foo": "updated tag"} updated_secret_properties = secret_client.update_secret_properties( secret_name, content_type=content_type, tags=tags ) print(updated_secret_properties.version) print(updated_secret_properties.updated_on) print(updated_secret_properties.content_type) print(updated_secret_properties.tags)
- class azure.keyvault.secrets.SecretProperties(*args: Any, **kwargs: Any)[source]¶
A secret’s ID and attributes.
- property content_type: str | None¶
An arbitrary string indicating the type of the secret.
- Returns:
The content type of the secret.
- Return type:
str or None
- property created_on: datetime | None¶
When the secret was created, in UTC.
- Returns:
When the secret was created, in UTC.
- Return type:
datetime or None
- property enabled: bool | None¶
Whether the secret is enabled for use.
- Returns:
True if the secret is enabled for use; False otherwise.
- Return type:
bool or None
- property expires_on: datetime | None¶
When the secret expires, in UTC.
- Returns:
When the secret expires, in UTC.
- Return type:
datetime or None
- property key_id: str | None¶
If this secret backs a certificate, this property is the identifier of the corresponding key.
- Returns:
The ID of the key backing the certificate that’s backed by this secret. If the secret isn’t backing a certificate, this is None.
- Return type:
str or None
- property managed: bool | None¶
Whether the secret’s lifetime is managed by Key Vault. If the secret backs a certificate, this will be true.
- Returns:
True if the secret’s lifetime is managed by Key Vault; False otherwise.
- Return type:
bool or None
- property not_before: datetime | None¶
The time before which the secret cannot be used, in UTC.
- Returns:
The time before which the secret cannot be used, in UTC.
- Return type:
datetime or None
- property recoverable_days: int | None¶
The number of days the key is retained before being deleted from a soft-delete enabled Key Vault.
- Returns:
The number of days the key is retained before being deleted from a soft-delete enabled Key Vault.
- Return type:
int or None
- property recovery_level: str | None¶
The vault’s deletion recovery level for secrets.
- Returns:
The vault’s deletion recovery level for secrets.
- Return type:
str or None
- property tags: Dict[str, str] | None¶
Application specific metadata in the form of key-value pairs.
- Returns:
A dictionary of tags attached to this secret.
- Return type:
dict or None
- property updated_on: datetime | None¶
When the secret was last updated, in UTC.
- Returns:
When the secret was last updated, in UTC.
- Return type:
datetime or None
Subpackages¶
- azure.keyvault.secrets.aio package
SecretClient
SecretClient.backup_secret()
SecretClient.close()
SecretClient.delete_secret()
SecretClient.get_deleted_secret()
SecretClient.get_secret()
SecretClient.list_deleted_secrets()
SecretClient.list_properties_of_secret_versions()
SecretClient.list_properties_of_secrets()
SecretClient.purge_deleted_secret()
SecretClient.recover_deleted_secret()
SecretClient.restore_secret_backup()
SecretClient.send_request()
SecretClient.set_secret()
SecretClient.update_secret_properties()
SecretClient.vault_url