File: hello_world_async.py

package info (click to toggle)
python-azure 20201208%2Bgit-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,437,920 kB
  • sloc: python: 4,287,452; javascript: 269; makefile: 198; sh: 187; xml: 106
file content (99 lines) | stat: -rw-r--r-- 4,869 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import datetime
import os
import asyncio
from azure.keyvault.secrets.aio import SecretClient
from azure.identity.aio import DefaultAzureCredential
from azure.core.exceptions import HttpResponseError

# ----------------------------------------------------------------------------------------------------------
# Prerequisites:
# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli)
#
# 2. azure-keyvault-secrets and azure-identity libraries (pip install these)
#
# 3. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL
#    (See https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-keys#authenticate-the-client)
#
# ----------------------------------------------------------------------------------------------------------
# Sample - demonstrates the basic CRUD operations on a vault(secret) resource for Azure Key Vault
#
# 1. Create a new secret (set_secret)
#
# 2. Get an existing secret (get_secret)
#
# 3. Update an existing secret's properties (update_secret_properties)
#
# 4. Delete a secret (delete_secret)
#
# ----------------------------------------------------------------------------------------------------------
async def run_sample():
    # Instantiate a secret client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = SecretClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a secret holding bank account credentials valid for 1 year.
        # if the secret already exists in the key vault, then a new version of the secret is created.
        print("\n.. Create Secret")
        expires_on = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        secret = await client.set_secret("helloWorldSecretName", "helloWorldSecretValue", expires_on=expires_on)
        print("Secret with name '{0}' created with value '{1}'".format(secret.name, secret.value))
        print("Secret with name '{0}' expires on '{1}'".format(secret.name, secret.properties.expires_on))

        # Let's get the bank secret using its name
        print("\n.. Get a Secret by name")
        bank_secret = await client.get_secret(secret.name)
        print("Secret with name '{0}' was found with value '{1}'.".format(bank_secret.name, bank_secret.value))

        # After one year, the bank account is still active, we need to update the expiry time of the secret.
        # The update method can be used to update the expiry attribute of the secret. It cannot be used to update
        # the value of the secret.
        print("\n.. Update a Secret by name")
        expires_on = bank_secret.properties.expires_on + datetime.timedelta(days=365)
        updated_secret_properties = await client.update_secret_properties(secret.name, expires_on=expires_on)
        print(
            "Secret with name '{0}' was updated on date '{1}'".format(
                updated_secret_properties.name, updated_secret_properties.updated_on
            )
        )
        print(
            "Secret with name '{0}' was updated to expire on '{1}'".format(
                updated_secret_properties.name, updated_secret_properties.expires_on
            )
        )

        # Bank forced a password update for security purposes. Let's change the value of the secret in the key vault.
        # To achieve this, we need to create a new version of the secret in the key vault. The update operation cannot
        # change the value of the secret.
        new_secret = await client.set_secret(secret.name, "newSecretValue")
        print("Secret with name '{0}' created with value '{1}'".format(new_secret.name, new_secret.value))

        # The bank account was closed, need to delete its credentials from the Key Vault.
        print("\n.. Deleting Secret...")
        deleted_secret = await client.delete_secret(secret.name)
        print("Secret with name '{0}' was deleted.".format(deleted_secret.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
        await credential.close()
        await client.close()


if __name__ == "__main__":
    try:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(run_sample())
        loop.close()

    except Exception as e:
        print("Top level Error: {0}".format(str(e)))