1# ------------------------------------
2# Copyright (c) Microsoft Corporation.
3# Licensed under the MIT License.
4# ------------------------------------
5import asyncio
6import os
7from azure.identity.aio import DefaultAzureCredential
8from azure.keyvault.certificates.aio import CertificateClient
9from azure.keyvault.certificates import CertificatePolicy, CertificateContentType, WellKnownIssuerNames
10from azure.core.exceptions import HttpResponseError
11
12# ----------------------------------------------------------------------------------------------------------
13# Prerequisites:
14# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli)
15#
16# 2. azure-keyvault-certificates and azure-identity packages (pip install these)
17#
18# 3. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. (See
19#    https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#authenticate-the-client)
20#
21# ----------------------------------------------------------------------------------------------------------
22# Sample - demonstrates the basic CRUD operations on a vault(certificate) resource for Azure Key Vault
23#
24# 1. Create a new certificate (create_certificate)
25#
26# 2. Get an existing certificate (get_certificate)
27#
28# 3. Update an existing certificate (update_certificate)
29#
30# 4. Delete a certificate (delete_certificate)
31#
32# ----------------------------------------------------------------------------------------------------------
33
34
35async def run_sample():
36    # Instantiate a certificate client that will be used to call the service.
37    # Notice that the client is using default Azure credentials.
38    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
39    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
40    VAULT_URL = os.environ["VAULT_URL"]
41    credential = DefaultAzureCredential()
42    client = CertificateClient(vault_url=VAULT_URL, credential=credential)
43    try:
44        # Let's create a certificate for holding bank account credentials valid for 1 year.
45        # if the certificate already exists in the Key Vault, then a new version of the certificate is created.
46        print("\n.. Create certificate")
47
48        # Before creating your certificate, let's create the management policy for your certificate.
49        # Here you specify the properties of the key, secret, and issuer backing your certificate,
50        # the X509 component of your certificate, and any lifetime actions you would like to be taken
51        # on your certificate
52
53        # Alternatively, if you would like to use our default policy, use CertificatePolicy.get_default()
54        cert_policy = CertificatePolicy(
55            issuer_name=WellKnownIssuerNames.self,
56            subject="CN=*.microsoft.com",
57            san_dns_names=["sdk.azure-int.net"],
58            exportable=True,
59            key_type="RSA",
60            key_size=2048,
61            reuse_key=False,
62            content_type=CertificateContentType.pkcs12,
63            validity_in_months=24,
64        )
65        cert_name = "HelloWorldCertificate"
66
67        # Awaiting create_certificate will return the certificate as a KeyVaultCertificate
68        # if creation is successful, and the CertificateOperation if not.
69        certificate = await client.create_certificate(certificate_name=cert_name, policy=cert_policy)
70        print("Certificate with name '{0}' created".format(certificate.name))
71
72        # Let's get the bank certificate using its name
73        print("\n.. Get a certificate by name")
74        bank_certificate = await client.get_certificate(cert_name)
75        print("Certificate with name '{0}' was found.".format(bank_certificate.name))
76
77        # After one year, the bank account is still active, and we have decided to update the tags.
78        print("\n.. Update a certificate by name")
79        tags = {"a": "b"}
80        updated_certificate = await client.update_certificate_properties(
81            certificate_name=bank_certificate.name, tags=tags
82        )
83        print(
84            "Certificate with name '{0}' was updated on date '{1}'".format(
85                bank_certificate.name, updated_certificate.properties.updated_on
86            )
87        )
88        print(
89            "Certificate with name '{0}' was updated with tags '{1}'".format(
90                bank_certificate.name, updated_certificate.properties.tags
91            )
92        )
93
94        # The bank account was closed, need to delete its credentials from the Key Vault.
95        print("\n.. Delete certificate")
96        deleted_certificate = await client.delete_certificate(bank_certificate.name)
97        print("Deleting certificate..")
98        print("Certificate with name '{0}' was deleted.".format(deleted_certificate.name))
99
100    except HttpResponseError as e:
101        print("\nrun_sample has caught an error. {0}".format(e.message))
102
103    finally:
104        print("\nrun_sample done")
105        await credential.close()
106        await client.close()
107
108
109if __name__ == "__main__":
110    try:
111        loop = asyncio.get_event_loop()
112        loop.run_until_complete(run_sample())
113        loop.close()
114
115    except Exception as e:
116        print("Top level error: {0}".format(str(e)))
117