1# ------------------------------------
2# Copyright (c) Microsoft Corporation.
3# Licensed under the MIT License.
4# ------------------------------------
5import datetime
6import os
7from azure.keyvault.certificates import CertificateClient, CertificatePolicy
8from azure.identity import DefaultAzureCredential
9from azure.core.exceptions import HttpResponseError
10
11# ----------------------------------------------------------------------------------------------------------
12# Prerequisites:
13# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli)
14#
15# 2. azure-keyvault-certificates and azure-identity packages (pip install these)
16#
17# 3. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL
18#    (See https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-keys#authenticate-the-client)
19#
20# ----------------------------------------------------------------------------------------------------------
21# Sample - demonstrates the basic list operations on a vault(certificate) resource for Azure Key Vault.
22# The vault has to be soft-delete enabled to perform one of the following operations: https://docs.microsoft.com/en-us/azure/key-vault/key-vault-ovw-soft-delete
23#
24# 1. Create certificate (begin_create_certificate)
25#
26# 2. List certificates from the Key Vault (list_properties_of_certificates)
27#
28# 3. List certificate versions from the Key Vault (list_properties_of_certificate_versions)
29#
30# 4. List deleted certificates from the Key Vault (list_deleted_certificates). The vault has to be soft-delete enabled
31# to perform this operation.
32#
33# ----------------------------------------------------------------------------------------------------------
34
35# Instantiate a certificate client that will be used to call the service. Notice that the client is using default
36# Azure credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
37# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
38VAULT_URL = os.environ["VAULT_URL"]
39credential = DefaultAzureCredential()
40client = CertificateClient(vault_url=VAULT_URL, credential=credential)
41try:
42    # Let's create a certificate for holding storage and bank accounts credentials. If the certificate
43    # already exists in the Key Vault, then a new version of the certificate is created.
44    print("\n.. Create Certificate")
45    bank_cert_name = "BankListCertificate"
46    storage_cert_name = "StorageListCertificate"
47
48    bank_certificate_poller = client.begin_create_certificate(
49        certificate_name=bank_cert_name, policy=CertificatePolicy.get_default()
50    )
51    storage_certificate_poller = client.begin_create_certificate(
52        certificate_name=storage_cert_name, policy=CertificatePolicy.get_default()
53    )
54
55    # await the creation of the bank and storage certificate
56    bank_certificate = bank_certificate_poller.result()
57    storage_certificate = storage_certificate_poller.result()
58
59    print("Certificate with name '{0}' was created.".format(bank_certificate.name))
60    print("Certificate with name '{0}' was created.".format(storage_certificate.name))
61
62    # Let's list the certificates.
63    print("\n.. List certificates from the Key Vault")
64    certificates = client.list_properties_of_certificates()
65    for certificate in certificates:
66        print("Certificate with name '{0}' was found.".format(certificate.name))
67
68    # You've decided to add tags to the certificate you created. Calling begin_create_certificate on an existing
69    # certificate creates a new version of the certificate in the Key Vault with the new value.
70
71    tags = {"a": "b"}
72    bank_certificate_poller = client.begin_create_certificate(
73        certificate_name=bank_cert_name, policy=CertificatePolicy.get_default(), tags=tags
74    )
75    bank_certificate = bank_certificate_poller.result()
76    print(
77        "Certificate with name '{0}' was created again with tags '{1}'".format(
78            bank_certificate.name, bank_certificate.properties.tags
79        )
80    )
81
82    # You need to check all the different tags your bank account certificate had previously. Let's print
83    # all the versions of this certificate.
84    print("\n.. List versions of the certificate using its name")
85    certificate_versions = client.list_properties_of_certificate_versions(bank_cert_name)
86    for certificate_version in certificate_versions:
87        print(
88            "Bank Certificate with name '{0}' with version '{1}' has tags: '{2}'.".format(
89                certificate_version.name, certificate_version.version, certificate_version.tags
90            )
91        )
92
93    # The bank account and storage accounts got closed. Let's delete bank and storage accounts certificates.
94    # We call wait() to ensure the certificate is deleted server side because the following method requires
95    # server-side deletion to run properly. In most situations you will not have to call wait().
96    client.begin_delete_certificate(bank_cert_name).wait()
97    client.begin_delete_certificate(storage_cert_name).wait()
98
99    # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled.
100    print("\n.. List deleted certificates from the Key Vault")
101    deleted_certificates = client.list_deleted_certificates()
102    for deleted_certificate in deleted_certificates:
103        print(
104            "Certificate with name '{0}' has recovery id '{1}'".format(
105                deleted_certificate.name, deleted_certificate.recovery_id
106            )
107        )
108
109except HttpResponseError as e:
110    if "(NotSupported)" in e.message:
111        print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message))
112    else:
113        print("\nrun_sample has caught an error. {0}".format(e.message))
114
115finally:
116    print("\nrun_sample done")
117