• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

azure/H03-May-2022-50,15640,473

azure_keyvault_secrets.egg-info/H03-May-2022-601492

samples/H03-May-2022-739331

tests/H03-May-2022-1,9891,277

CHANGELOG.mdH A D22-Jun-20216.3 KiB140118

MANIFEST.inH A D22-Jun-2021174 76

PKG-INFOH A D22-Jun-202130.5 KiB601492

README.mdH A D22-Jun-202118.8 KiB438353

migration_guide.mdH A D22-Jun-202110.3 KiB206143

setup.cfgH A D22-Jun-202167 85

setup.pyH A D22-Jun-20213 KiB9571

README.md

1# Azure Key Vault Secrets client library for Python
2Azure Key Vault helps solve the following problems:
3
4- Secrets management (this library) -
5securely store and control access to tokens, passwords, certificates, API keys,
6and other secrets
7- Cryptographic key management
8([azure-keyvault-keys](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-keys)) -
9create, store, and control access to the keys used to encrypt your data
10- Certificate management
11([azure-keyvault-certificates](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates)) -
12create, manage, and deploy public and private SSL/TLS certificates
13- Vault administration ([azure-keyvault-administration](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-administration)) - role-based access control (RBAC), and vault-level backup and restore options
14
15[Source code][secret_client_src] | [Package (PyPI)][pypi_package_secrets] | [API reference documentation][reference_docs] | [Product documentation][keyvault_docs] | [Samples][secret_samples]
16
17## Getting started
18### Install packages
19Install [azure-keyvault-secrets][pypi_package_secrets] and
20[azure-identity][azure_identity_pypi] with [pip][pip]:
21```Bash
22pip install azure-keyvault-secrets azure-identity
23```
24[azure-identity][azure_identity] is used for Azure Active Directory
25authentication as demonstrated below.
26
27### Prerequisites
28* An [Azure subscription][azure_sub]
29* Python 2.7, 3.5.3, or later
30* A Key Vault. If you need to create one, you can use the
31[Azure Cloud Shell][azure_cloud_shell] to create one with these commands
32(replace `"my-resource-group"` and `"my-key-vault"` with your own, unique
33names):
34
35  (Optional) if you want a new resource group to hold the Key Vault:
36  ```sh
37  az group create --name my-resource-group --location westus2
38  ```
39
40  Create the Key Vault:
41  ```Bash
42  az keyvault create --resource-group my-resource-group --name my-key-vault
43  ```
44
45  Output:
46  ```json
47  {
48      "id": "...",
49      "location": "westus2",
50      "name": "my-key-vault",
51      "properties": {
52          "accessPolicies": [...],
53          "createMode": null,
54          "enablePurgeProtection": null,
55          "enableSoftDelete": null,
56          "enabledForDeployment": false,
57          "enabledForDiskEncryption": null,
58          "enabledForTemplateDeployment": null,
59          "networkAcls": null,
60          "provisioningState": "Succeeded",
61          "sku": { "name": "standard" },
62          "tenantId": "...",
63          "vaultUri": "https://my-key-vault.vault.azure.net/"
64      },
65      "resourceGroup": "my-resource-group",
66      "type": "Microsoft.KeyVault/vaults"
67  }
68  ```
69
70  > The `"vaultUri"` property is the `vault_url` used by [SecretClient][secret_client_docs]
71
72### Authenticate the client
73This document demonstrates using [DefaultAzureCredential][default_cred_ref]
74to authenticate as a service principal. However, [SecretClient][secret_client_docs]
75accepts any [azure-identity][azure_identity] credential. See the
76[azure-identity][azure_identity] documentation for more information about other
77credentials.
78
79
80#### Create a service principal (optional)
81This [Azure Cloud Shell][azure_cloud_shell] snippet shows how to create a
82new service principal. Before using it, replace "your-application-name" with
83a more appropriate name for your service principal.
84
85Create a service principal:
86```Bash
87az ad sp create-for-rbac --name http://my-application --skip-assignment
88```
89
90> Output:
91> ```json
92> {
93>     "appId": "generated app id",
94>     "displayName": "my-application",
95>     "name": "http://my-application",
96>     "password": "random password",
97>     "tenant": "tenant id"
98> }
99> ```
100
101Use the output to set **AZURE_CLIENT_ID** ("appId" above), **AZURE_CLIENT_SECRET**
102("password" above) and **AZURE_TENANT_ID** ("tenant" above) environment variables.
103The following example shows a way to do this in Bash:
104```Bash
105export AZURE_CLIENT_ID="generated app id"
106export AZURE_CLIENT_SECRET="random password"
107export AZURE_TENANT_ID="tenant id"
108```
109
110Authorize the service principal to perform key operations in your Key Vault:
111```Bash
112az keyvault set-policy --name my-key-vault --spn $AZURE_CLIENT_ID --secret-permissions get set list delete backup recover restore purge
113```
114> Possible permissions:
115> - Secret management: set, backup, delete, get, list, purge, recover, restore
116
117If you have enabled role-based access control (RBAC) for Key Vault instead, you can find roles like "Key Vault Secrets Officer" in our [RBAC guide][rbac_guide].
118
119#### Create a client
120Once the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and
121**AZURE_TENANT_ID** environment variables are set,
122[DefaultAzureCredential][default_cred_ref] will be able to authenticate the
123[SecretClient][secret_client_docs].
124
125Constructing the client also requires your vault's URL, which you can
126get from the Azure CLI or the Azure Portal. In the Azure Portal, this URL is
127the vault's "DNS Name".
128
129```python
130from azure.identity import DefaultAzureCredential
131from azure.keyvault.secrets import SecretClient
132
133credential = DefaultAzureCredential()
134
135secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
136```
137
138## Key concepts
139### Secret
140A secret consists of a secret value and its associated metadata and management
141information. This library handles secret values as strings, but Azure Key Vault
142doesn't store them as such. For more information about secrets and how Key
143Vault stores and manages them, see the
144[Key Vault documentation](https://docs.microsoft.com/azure/key-vault/about-keys-secrets-and-certificates#key-vault-secrets).
145
146[SecretClient][secret_client_docs] can set secret values in the vault, update
147secret metadata, and delete secrets, as shown in the
148[examples](#examples "examples") below.
149
150## Examples
151This section contains code snippets covering common tasks:
152* [Set a Secret](#set-a-secret "Set a Secret")
153* [Retrieve a Secret](#retrieve-a-secret "Retrieve a Secret")
154* [Update Secret metadata](#update-secret-metadata "Update Secret metadata")
155* [Delete a Secret](#delete-a-secret "Delete a Secret")
156* [List Secrets](#list-secrets "List Secrets")
157* [Asynchronously create a Secret](#asynchronously-create-a-secret "Asynchronously create a Secret")
158* [Asynchronously list Secrets](#asynchronously-list-secrets "Asynchronously list Secrets")
159
160### Set a Secret
161[set_secret](https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient.set_secret)
162creates new secrets and changes the values of existing secrets. If no secret with the
163given name exists, `set_secret` creates a new secret with that name and the
164given value. If the given name is in use, `set_secret` creates a new version
165of that secret, with the given value.
166
167```python
168from azure.identity import DefaultAzureCredential
169from azure.keyvault.secrets import SecretClient
170
171credential = DefaultAzureCredential()
172
173secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
174secret = secret_client.set_secret("secret-name", "secret-value")
175
176print(secret.name)
177print(secret.value)
178print(secret.properties.version)
179```
180
181### Retrieve a Secret
182[get_secret](https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient.get_secret)
183retrieves a secret previously stored in the Key Vault.
184
185```python
186from azure.identity import DefaultAzureCredential
187from azure.keyvault.secrets import SecretClient
188
189credential = DefaultAzureCredential()
190
191secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
192secret = secret_client.get_secret("secret-name")
193
194print(secret.name)
195print(secret.value)
196```
197
198### Update Secret metadata
199[update_secret_properites](https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient.update_secret_properties)
200updates a secret's metadata. It cannot change the secret's value; use [set_secret](#set-a-secret) to set a secret's
201value.
202
203```python
204from azure.identity import DefaultAzureCredential
205from azure.keyvault.secrets import SecretClient
206
207credential = DefaultAzureCredential()
208
209secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
210
211# Clients may specify the content type of a secret to assist in interpreting the secret data when it's retrieved
212content_type = "text/plain"
213
214# We will also disable the secret for further use
215
216updated_secret_properties = secret_client.update_secret_properties("secret-name", content_type=content_type, enabled=False)
217
218print(updated_secret_properties.updated_on)
219print(updated_secret_properties.content_type)
220print(updated_secret_properties.enabled)
221```
222
223### Delete a Secret
224[begin_delete_secret](https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient.begin_delete_secret)
225requests Key Vault delete a secret, returning a poller which allows you to wait for the deletion to finish. Waiting is
226helpful when the vault has [soft-delete][soft_delete] enabled, and you want to purge (permanently delete) the secret as
227soon as possible. When [soft-delete][soft_delete] is disabled, `begin_delete_secret` itself is permanent.
228
229```python
230from azure.identity import DefaultAzureCredential
231from azure.keyvault.secrets import SecretClient
232
233credential = DefaultAzureCredential()
234
235secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
236deleted_secret = secret_client.begin_delete_secret("secret-name").result()
237
238print(deleted_secret.name)
239print(deleted_secret.deleted_date)
240```
241
242### List secrets
243[list_properties_of_secrets](https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient.list_properties_of_secrets)
244lists the properties of all of the secrets in the client's vault. This list doesn't include the secret's values.
245
246```python
247from azure.identity import DefaultAzureCredential
248from azure.keyvault.secrets import SecretClient
249
250credential = DefaultAzureCredential()
251
252secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
253secret_properties = secret_client.list_properties_of_secrets()
254
255for secret_property in secret_properties:
256    # the list doesn't include values or versions of the secrets
257    print(secret_property.name)
258```
259
260### Async API
261This library includes a complete async API supported on Python 3.5+. To use it, you must
262first install an async transport, such as [aiohttp](https://pypi.org/project/aiohttp/).
263See
264[azure-core documentation](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/CLIENT_LIBRARY_DEVELOPER.md#transport)
265for more information.
266
267Async clients and credentials should be closed when they're no longer needed. These
268objects are async context managers and define async `close` methods. For
269example:
270
271```py
272from azure.identity.aio import DefaultAzureCredential
273from azure.keyvault.secrets.aio import SecretClient
274
275credential = DefaultAzureCredential()
276
277# call close when the client and credential are no longer needed
278client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
279...
280await client.close()
281await credential.close()
282
283# alternatively, use them as async context managers (contextlib.AsyncExitStack can help)
284client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
285async with client:
286  async with credential:
287    ...
288```
289
290### Asynchronously create a secret
291[set_secret](https://aka.ms/azsdk/python/keyvault-secrets/aio/docs#azure.keyvault.secrets.aio.SecretClient.set_secret)
292creates a secret in the Key Vault with the specified optional arguments.
293```python
294from azure.identity.aio import DefaultAzureCredential
295from azure.keyvault.secrets.aio import SecretClient
296
297credential = DefaultAzureCredential()
298secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
299
300secret = await secret_client.set_secret("secret-name", "secret-value")
301
302print(secret.name)
303print(secret.value)
304print(secret.properties.version)
305```
306
307### Asynchronously list secrets
308[list_properties_of_secrets](https://aka.ms/azsdk/python/keyvault-secrets/aio/docs#azure.keyvault.secrets.aio.SecretClient.list_properties_of_secrets)
309lists the properties of all of the secrets in the client's vault.
310
311```python
312from azure.identity.aio import DefaultAzureCredential
313from azure.keyvault.secrets.aio import SecretClient
314
315credential = DefaultAzureCredential()
316secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
317secret_properties = secret_client.list_properties_of_secrets()
318
319async for secret_property in secret_properties:
320    # the list doesn't include values or versions of the secrets
321    print(secret_property.name)
322```
323
324## Troubleshooting
325### General
326Key Vault clients raise exceptions defined in [azure-core][azure_core_exceptions].
327For example, if you try to get a key that doesn't exist in the vault,
328[SecretClient][secret_client_docs] raises
329[ResourceNotFoundError](https://aka.ms/azsdk-python-core-exceptions-resource-not-found-error):
330
331```python
332from azure.identity import DefaultAzureCredential
333from azure.keyvault.secrets import SecretClient
334from azure.core.exceptions import ResourceNotFoundError
335
336credential = DefaultAzureCredential()
337secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential)
338
339try:
340    secret_client.get_secret("which-does-not-exist")
341except ResourceNotFoundError as e:
342    print(e.message)
343```
344
345### Logging
346This library uses the standard
347[logging](https://docs.python.org/3.5/library/logging.html) library for logging.
348Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
349level.
350
351Detailed DEBUG level logging, including request/response bodies and unredacted
352headers, can be enabled on a client with the `logging_enable` argument:
353```python
354from azure.identity import DefaultAzureCredential
355from azure.keyvault.secrets import SecretClient
356import sys
357import logging
358
359# Create a logger for the 'azure' SDK
360logger = logging.getLogger('azure')
361logger.setLevel(logging.DEBUG)
362
363# Configure a console output
364handler = logging.StreamHandler(stream=sys.stdout)
365logger.addHandler(handler)
366
367credential = DefaultAzureCredential()
368
369# This client will log detailed information about its HTTP sessions, at DEBUG level
370secret_client = SecretClient(vault_url="https://my-key-vault.vault.azure.net/", credential=credential, logging_enable=True)
371```
372
373Similarly, `logging_enable` can enable detailed logging for a single operation,
374even when it isn't enabled for the client:
375```py
376secret_client.get_secret("my-secret", logging_enable=True)
377```
378
379## Next steps
380Several samples are available in the Azure SDK for Python GitHub repository.
381These provide example code for additional Key Vault scenarios:
382* [hello_world.py][hello_world_sample] and
383[hello_world_async.py][hello_world_async_sample] - create/get/update/delete secrets
384* [list_operations.py][list_operations_sample] and
385[list_operations_async.py][list_operations_async_sample] - basic list operations for secrets
386* [backup_restore_operations.py][backup_operations_sample] and
387[backup_restore_operations_async.py][backup_operations_async_sample] - backup and
388restore secrets
389* [recover_purge_operations.py][recover_purge_sample] and
390[recover_purge_operations_async.py][recover_purge_async_sample] - recovering and purging secrets
391
392###  Additional Documentation
393For more extensive documentation on Azure Key Vault, see the
394[API reference documentation][reference_docs].
395
396## Contributing
397This project welcomes contributions and suggestions. Most contributions require
398you to agree to a Contributor License Agreement (CLA) declaring that you have
399the right to, and actually do, grant us the rights to use your contribution.
400For details, visit https://cla.microsoft.com.
401
402When you submit a pull request, a CLA-bot will automatically determine whether
403you need to provide a CLA and decorate the PR appropriately (e.g., label,
404comment). Simply follow the instructions provided by the bot. You will only
405need to do this once across all repos using our CLA.
406
407This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct].
408For more information, see the
409[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
410contact opencode@microsoft.com with any additional questions or comments.
411
412[azure_cloud_shell]: https://shell.azure.com/bash
413[azure_core_exceptions]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/core/azure-core#azure-core-library-exceptions
414[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity
415[azure_identity_pypi]: https://pypi.org/project/azure-identity/
416[azure_sub]: https://azure.microsoft.com/free/
417[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
418[default_cred_ref]: https://aka.ms/azsdk/python/identity/docs#azure.identity.DefaultAzureCredential
419[hello_world_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/hello_world.py
420[hello_world_async_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/hello_world_async.py
421[backup_operations_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/backup_restore_operations.py
422[backup_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/backup_restore_operations_async.py
423[list_operations_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/list_operations.py
424[list_operations_async_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/list_operations_async.py
425[recover_purge_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/recover_purge_operations.py
426[recover_purge_async_sample]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/keyvault/azure-keyvault-secrets/samples/recover_purge_operations_async.py
427[keyvault_docs]: https://docs.microsoft.com/azure/key-vault/
428[pip]: https://pypi.org/project/pip/
429[pypi_package_secrets]: https://pypi.org/project/azure-keyvault-secrets/
430[rbac_guide]: https://docs.microsoft.com/azure/key-vault/general/rbac-guide
431[reference_docs]: https://aka.ms/azsdk/python/keyvault-secrets/docs
432[secret_client_src]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets
433[secret_client_docs]: https://aka.ms/azsdk/python/keyvault-secrets/docs#azure.keyvault.secrets.SecretClient
434[secret_samples]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-secrets/samples
435[soft_delete]: https://docs.microsoft.com/azure/key-vault/key-vault-ovw-soft-delete
436
437![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fsdk%2Fkeyvault%2Fazure-keyvault-secrets%2FREADME.png)
438