diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations.py b/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations.py index 1f55b29ac9b8..e734217220b0 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations.py @@ -3,24 +3,19 @@ # Licensed under the MIT License. # ------------------------------------ import os +import time from azure.keyvault.certificates import CertificateClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 backup and restore operations on a vault(certificates) resource for Azure Key Vault @@ -36,53 +31,55 @@ # 5. Restore a certificate (restore_certificate) # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - - print("\n1. Create Certificate") - cert_name = 'BackupRestoreCertificate' - - # Let's create a certificate for your key vault. - # if the certificate already exists in the Key Vault, then a new version of the certificate is created. - # A long running poller is returned for the create certificate operation. - create_certificate_poller = client.create_certificate(name=cert_name) +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: - # the wait call awaits the completion of the create certificate operation - create_certificate_poller.wait() - print("Certificate with name '{0}' created.".format(cert_name)) + print("\n.. Create Certificate") + cert_name = 'BackupRestoreCertificate' - # Backups are good to have, if in case certificates gets deleted accidentally. - # For long term storage, it is ideal to write the backup to a file. - print("\n2. Create a backup for an existing certificate") - certificate_backup = client.backup_certificate(name=cert_name) - print("Backup created for certificate with name '{0}'.".format(cert_name)) + # Let's create a certificate for your key vault. + # if the certificate already exists in the Key Vault, then a new version of the certificate is created. + # A long running poller is returned for the create certificate operation. + create_certificate_poller = client.create_certificate(name=cert_name) - # The storage account certificate is no longer in use, so you can delete it. - client.delete_certificate(name=cert_name) - print("Deleted Certificate with name '{0}'".format(cert_name)) + # The wait call awaits the completion of the create certificate operation + create_certificate_poller.wait() + print("Certificate with name '{0}' created.".format(cert_name)) - # In future, if the certificate is required again, we can use the backup value to restore it in the Key Vault. - print("\n3. Restore the certificate using the backed up certificate bytes") - certificate = client.restore_certificate(certificate_backup) - print("Restored Certificate with name '{0}'".format(certificate.name)) + # Backups are good to have, if in case certificates gets deleted accidentally. + # For long term storage, it is ideal to write the backup to a file. + print("\n.. Create a backup for an existing certificate") + certificate_backup = client.backup_certificate(name=cert_name) + print("Backup created for certificate with name '{0}'.".format(cert_name)) - except HttpResponseError as e: - print("\nrun_sample has caught an error. {0}".format(e.message)) + # The storage account certificate is no longer in use, so you can delete it. + client.delete_certificate(name=cert_name) + # To ensure certificate is deleted on the server side. + time.sleep(30) + print("Deleted Certificate with name '{0}'".format(cert_name)) - finally: - print("\nrun_sample done") + # Even though the certificate is deleted, it can still be recovered so its name cannot be reused. + # In order to be able to reuse the name during restoration, we must purge the certificate + # after the initial deletion. + print("\nPurging certificate...") + client.purge_deleted_certificate(name=cert_name) + # To ensure certificate is purged on the server side. + time.sleep(30) + print("Purged Certificate with name '{0}'".format(cert_name)) + # In future, if the certificate is required again, we can use the backup value to restore it in the Key Vault. + print("\n.. Restore the certificate using the backed up certificate bytes") + certificate = client.restore_certificate(certificate_backup) + print("Restored Certificate with name '{0}'".format(certificate.name)) -if __name__ == "__main__": - try: - run_sample() +except HttpResponseError as e: + print("\nrun_sample has caught an error. {0}".format(e.message)) - except Exception as e: - print("Top level Error: {0}".format(str(e))) +finally: + print("\nrun_sample done") diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations_async.py index f49cedef1202..3e224c78a810 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/backup_restore_operations_async.py @@ -3,26 +3,19 @@ # Licensed under the MIT License. # ------------------------------------ import asyncio -import time import os from azure.keyvault.certificates.aio import CertificateClient from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 backup and restore operations on a vault(certificates) resource for Azure Key Vault @@ -48,7 +41,7 @@ async def run_sample(): client = CertificateClient(vault_url=VAULT_URL, credential=credential) try: - print("\n1. Create Certificate") + print("\n.. Create Certificate") cert_name = 'BackupRestoreCertificate' # Let's create a certificate for your key vault. @@ -60,12 +53,14 @@ async def run_sample(): # Backups are good to have, if in case certificates gets deleted accidentally. # For long term storage, it is ideal to write the backup to a file. - print("\n2. Create a backup for an existing certificate") + print("\n.. Create a backup for an existing certificate") certificate_backup = await client.backup_certificate(name=cert_name) print("Backup created for certificate with name '{0}'.".format(cert_name)) # The storage account certificate is no longer in use, so you can delete it. await client.delete_certificate(name=cert_name) + # To ensure certificate is deleted on the server side. + await asyncio.sleep(30) print("Deleted Certificate with name '{0}'".format(cert_name)) # Even though the certificate is deleted, it can still be recovered so its name cannot be reused. @@ -74,11 +69,11 @@ async def run_sample(): print ("\nPurging certificate...") await client.purge_deleted_certificate(name=cert_name) # To ensure certificate is purged on the server side. - time.sleep(30) + await asyncio.sleep(30) print("Purged Certificate with name '{0}'".format(cert_name)) # In future, if the certificate is required again, we can use the backup value to restore it in the Key Vault. - print("\n3. Restore the certificate using the backed up certificate bytes") + print("\n.. Restore the certificate using the backed up certificate bytes") certificate = await client.restore_certificate(certificate_backup) print("Restored Certificate with name '{0}'".format(certificate.name)) diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/contacts.py b/sdk/keyvault/azure-keyvault-certificates/samples/contacts.py index 42282c4c8978..7397e7bc2ab4 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/contacts.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/contacts.py @@ -8,19 +8,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 basic CRUD operations for the certificate contacts for a key vault. @@ -32,48 +26,39 @@ # 3. Delete contacts (delete_contacts) # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - # First we create a list of Contacts that we would like to make the certificate contacts for this key vault. - contact_list = [ - Contact(email='admin@contoso.com', - name='John Doe', - phone='1111111111'), - Contact(email='admin2@contoso.com', - name='John Doe2', - phone='2222222222') - ] - - # Creates and sets the certificate contacts for this key vault. - client.create_contacts(contacts=contact_list) - - # Gets the certificate contacts for this key vault. - contacts = client.get_contacts() - for contact in contacts: - print(contact.name) - print(contact.email) - print(contact.phone) - - # Deletes all of the certificate contacts for this key vault. - client.delete_contacts() +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: + # First we create a list of Contacts that we would like to make the certificate contacts for this key vault. + contact_list = [ + Contact(email='admin@contoso.com', + name='John Doe', + phone='1111111111'), + Contact(email='admin2@contoso.com', + name='John Doe2', + phone='2222222222') + ] - except HttpResponseError as e: - print("\nrun_sample has caught an error. {0}".format(e.message)) + # Creates and sets the certificate contacts for this key vault. + client.create_contacts(contacts=contact_list) - finally: - print("\nrun_sample done") + # Gets the certificate contacts for this key vault. + contacts = client.get_contacts() + for contact in contacts: + print(contact.name) + print(contact.email) + print(contact.phone) + # Deletes all of the certificate contacts for this key vault. + client.delete_contacts() -if __name__ == "__main__": - try: - run_sample() +except HttpResponseError as e: + print("\nrun_sample has caught an error. {0}".format(e.message)) - except Exception as e: - print("Top level Error: {0}".format(str(e))) \ No newline at end of file +finally: + print("\nrun_sample done") \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/contacts_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/contacts_async.py index 5d7677a9f406..d4d908338b98 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/contacts_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/contacts_async.py @@ -9,19 +9,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 basic CRUD operations for the certificate contacts for a key vault. diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/hello_world.py b/sdk/keyvault/azure-keyvault-certificates/samples/hello_world.py index 66756ccd81c7..da023bb7546e 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/hello_world.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/hello_world.py @@ -2,26 +2,19 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -import datetime import os from azure.identity import DefaultAzureCredential from azure.keyvault.certificates import CertificateClient, CertificatePolicy, KeyProperties, SecretContentType from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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(certificate) resource for Azure Key Vault @@ -36,80 +29,66 @@ # # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - # Let's create a certificate for holding bank account credentials valid for 1 year. - # if the certificate already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificate") - - # Before creating your certificate, let's create the management policy for your certificate. - # Here you specify the properties of the key, secret, and issuer backing your certificate, - # the X509 component of your certificate, and any lifetime actions you would like to be taken - # on your certificate - - # Alternatively, if you would like to use our default policy, don't pass a policy parameter to - # our certificate creation method - cert_policy = CertificatePolicy(key_properties=KeyProperties(exportable=True, - key_type='RSA', - key_size=2048, - reuse_key=False), - content_type=SecretContentType.PKCS12, - issuer_name='Self', - subject_name='CN=*.microsoft.com', - validity_in_months=24, - san_dns_names=['sdk.azure-int.net'] - ) - cert_name = "HelloWorldCertificate" - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) - create_certificate_poller = client.create_certificate(name=cert_name, policy=cert_policy, expires=expires) - create_certificate_poller.wait() - print("Certificate with name '{0}' created".format(cert_name)) - - # Let's get the bank certificate using its name - print("\n2. Get a Certificate by name") - bank_certificate = client.get_certificate(name=cert_name) - print("Certificate with name '{0}' was found with expiration date '{1}'.".format( - bank_certificate.name, - bank_certificate.expires) - ) +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: + # Let's create a certificate for holding bank account credentials valid for 1 year. + # if the certificate already exists in the Key Vault, then a new version of the certificate is created. + print("\n.. Create Certificate") - # After one year, the bank account is still active, we need to update the expiry time of the certificate. - # The update method can be used to update the expiry attribute of the certificate. - print("\n3. Update a Certificate by name") - expires = bank_certificate.expires + datetime.timedelta(days=365) - updated_certificate = client.update_certificate(name=bank_certificate.name, expires=expires) - print("Certificate with name '{0}' was updated on date '{1}'".format( - bank_certificate.name, - updated_certificate.updated) - ) - print("Certificate with name '{0}' was updated to expire on '{1}'".format( - bank_certificate.name, - updated_certificate.expires) - ) + # Before creating your certificate, let's create the management policy for your certificate. + # Here you specify the properties of the key, secret, and issuer backing your certificate, + # the X509 component of your certificate, and any lifetime actions you would like to be taken + # on your certificate - # The bank account was closed, need to delete its credentials from the Key Vault. - print("\n4. Delete Certificate") - deleted_certificate = client.delete_certificate(name=bank_certificate.name) - print("Deleting Certificate..") - print("Certificate with name '{0}' was deleted.".format(deleted_certificate.name)) + # Alternatively, if you would like to use our default policy, don't pass a policy parameter to + # our certificate creation method + cert_policy = CertificatePolicy(key_properties=KeyProperties(exportable=True, + key_type='RSA', + key_size=2048, + reuse_key=False), + content_type=SecretContentType.PKCS12, + issuer_name='Self', + subject_name='CN=*.microsoft.com', + validity_in_months=24, + san_dns_names=['sdk.azure-int.net'] + ) + cert_name = "HelloWorldCertificate" + create_certificate_poller = client.create_certificate(name=cert_name, policy=cert_policy) + create_certificate_poller.wait() + print("Certificate with name '{0}' created".format(cert_name)) - except HttpResponseError as e: - print("\nrun_sample has caught an error. {0}".format(e.message)) + # Let's get the bank certificate using its name + print("\n.. Get a Certificate by name") + bank_certificate = client.get_certificate_with_policy(name=cert_name) + print("Certificate with name '{0}' was found'.".format(bank_certificate.name)) - finally: - print("\nrun_sample done") + # After one year, the bank account is still active, and we have decided to update the tags. + print("\n.. Update a Certificate by name") + tags = {"a": "b"} + updated_certificate = client.update_certificate(name=bank_certificate.name, tags=tags) + print("Certificate with name '{0}' was updated on date '{1}'".format( + bank_certificate.name, + updated_certificate.updated) + ) + print("Certificate with name '{0}' was updated with tags '{1}'".format( + bank_certificate.name, + updated_certificate.tags) + ) + # The bank account was closed, need to delete its credentials from the Key Vault. + print("\n.. Delete Certificate") + deleted_certificate = client.delete_certificate(name=bank_certificate.name) + print("Deleting Certificate..") + print("Certificate with name '{0}' was deleted.".format(deleted_certificate.name)) -if __name__ == "__main__": - try: - run_sample() +except HttpResponseError as e: + print("\nrun_sample has caught an error. {0}".format(e.message)) - except Exception as e: - print("Top level Error: {0}".format(str(e))) +finally: + print("\nrun_sample done") diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/hello_world_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/hello_world_async.py index a0e329697fe5..63c05d32f592 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/hello_world_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/hello_world_async.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. # ------------------------------------ import asyncio -import datetime import os from azure.identity.aio import DefaultAzureCredential from azure.keyvault.certificates.aio import CertificateClient @@ -11,19 +10,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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(certificate) resource for Azure Key Vault @@ -49,7 +42,7 @@ async def run_sample(): try: # Let's create a certificate for holding bank account credentials valid for 1 year. # if the certificate already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificate") + print("\n.. Create Certificate") # Before creating your certificate, let's create the management policy for your certificate. # Here you specify the properties of the key, secret, and issuer backing your certificate, @@ -68,27 +61,31 @@ async def run_sample(): validity_in_months=24, san_dns_names=['sdk.azure-int.net'] ) - cert_name="HelloWorldCertificate" - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) - create_certificate_poller = await client.create_certificate(name=cert_name, policy=cert_policy, expires=expires) + cert_name = "HelloWorldCertificate" + create_certificate_poller = await client.create_certificate(name=cert_name, policy=cert_policy) await create_certificate_poller print("Certificate with name '{0}' created".format(cert_name)) # Let's get the bank certificate using its name - print("\n2. Get a Certificate by name") - bank_certificate = await client.get_certificate(name=cert_name) - print("Certificate with name '{0}' was found with expiration date '{1}'.".format(bank_certificate.name, bank_certificate.expires)) + print("\n.. Get a Certificate by name") + bank_certificate = await client.get_certificate_with_policy(name=cert_name) + print("Certificate with name '{0}' was found.".format(bank_certificate.name)) - # After one year, the bank account is still active, we need to update the expiry time of the certificate. - # The update method can be used to update the expiry attribute of the certificate. - print("\n3. Update a Certificate by name") - expires = bank_certificate.expires + datetime.timedelta(days=365) - updated_certificate = await client.update_certificate(name=bank_certificate.name, expires=expires) - print("Certificate with name '{0}' was updated on date '{1}'".format(bank_certificate.name, updated_certificate.updated)) - print("Certificate with name '{0}' was updated to expire on '{1}'".format(bank_certificate.name, updated_certificate.expires)) + # After one year, the bank account is still active, and we have decided to update the tags. + print("\n.. Update a Certificate by name") + tags = {"a": "b"} + updated_certificate = await client.update_certificate(name=bank_certificate.name, tags=tags) + print("Certificate with name '{0}' was updated on date '{1}'".format( + bank_certificate.name, + updated_certificate.updated) + ) + print("Certificate with name '{0}' was updated with tags '{1}'".format( + bank_certificate.name, + updated_certificate.tags) + ) # The bank account was closed, need to delete its credentials from the Key Vault. - print("\n4. Delete Certificate") + print("\n.. Delete Certificate") deleted_certificate = await client.delete_certificate(name=bank_certificate.name) print("Deleting Certificate..") print("Certificate with name '{0}' was deleted.".format(deleted_certificate.name)) diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/issuers.py b/sdk/keyvault/azure-keyvault-certificates/samples/issuers.py index 950bdd085600..ede1213a03a0 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/issuers.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/issuers.py @@ -8,19 +8,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 basic CRUD operations for certificate issuers. @@ -36,72 +30,66 @@ # 5. Delete an issuer (delete_issuer) # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - # First we specify the AdministratorDetails for our issuers. - admin_details = [AdministratorDetails( - first_name="John", - last_name="Doe", - email="admin@microsoft.com", - phone="4255555555" - )] - - # Next we create an issuer with these administrator details - # The name field refers to the name you would like to get the issuer. There are also pre-set names, such as 'Self' and 'Unknown' - # The provider for your issuer must exist for your vault location and tenant id. - client.create_issuer( - name="issuer1", - provider="Test", - account_id="keyvaultuser", - admin_details=admin_details, - enabled=True - ) +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: + # First we specify the AdministratorDetails for our issuers. + admin_details = [AdministratorDetails( + first_name="John", + last_name="Doe", + email="admin@microsoft.com", + phone="4255555555" + )] - # Now we get this issuer by name - issuer1 = client.get_issuer(name="issuer1") + # Next we create an issuer with these administrator details + # The name field refers to the name you would like to get the issuer. There are also pre-set names, such as 'Self' and 'Unknown' + # The provider for your issuer must exist for your vault location and tenant id. + client.create_issuer( + name="issuer1", + provider="Test", + account_id="keyvaultuser", + admin_details=admin_details, + enabled=True + ) - print(issuer1.name) - print(issuer1.provider) - print(issuer1.account_id) - print(issuer1.admin_details.first_name) - print(issuer1.admin_details.last_name) - print(issuer1.admin_details.email) - print(issuer1.admin_details.phone) + # Now we get this issuer by name + issuer1 = client.get_issuer(name="issuer1") - # Now we will list all of the certificate issuers for this key vault. To better demonstrate this, we will first create another issuer. - client.create_issuer( - name="issuer2", - provider="Test", - account_id="keyvaultuser", - enabled=True - ) + print(issuer1.name) + print(issuer1.provider) + print(issuer1.account_id) - issuers = client.list_issuers() + for admin_detail in issuer1.admin_details: + print(admin_detail.first_name) + print(admin_detail.last_name) + print(admin_detail.email) + print(admin_detail.phone) - for issuer in issuers: - print(issuer.name) - print(issuer.provider) + # Now we will list all of the certificate issuers for this key vault. To better demonstrate this, we will first create another issuer. + client.create_issuer( + name="issuer2", + provider="Test", + account_id="keyvaultuser", + enabled=True + ) - # Finally, we delete our first issuer by name. - client.delete_issuer(name="issuer1") + issuers = client.list_issuers() - except HttpResponseError as e: - print("\nrun_sample has caught an error. {0}".format(e.message)) + for issuer in issuers: + print(issuer.name) + print(issuer.provider) - finally: - print("\nrun_sample done") + # Finally, we delete our first issuer by name. + client.delete_issuer(name="issuer1") +except HttpResponseError as e: + print("\nrun_sample has caught an error. {0}".format(e.message)) -if __name__ == "__main__": - try: - run_sample() +finally: + print("\nrun_sample done") - except Exception as e: - print("Top level Error: {0}".format(str(e))) \ No newline at end of file diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/issuers_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/issuers_async.py index 9ae0969e801e..33893b093961 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/issuers_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/issuers_async.py @@ -9,19 +9,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 basic CRUD operations for certificate issuers. @@ -58,7 +52,7 @@ async def run_sample(): # The name field refers to the name you would like to get the issuer. There are also pre-set names, such as 'Self' and 'Unknown' await client.create_issuer( name="issuer1", - provider="Sample", + provider="Test", account_id="keyvaultuser", admin_details=admin_details, enabled=True @@ -70,15 +64,17 @@ async def run_sample(): print(issuer1.name) print(issuer1.provider) print(issuer1.account_id) - print(issuer1.admin_details.first_name) - print(issuer1.admin_details.last_name) - print(issuer1.admin_details.email) - print(issuer1.admin_details.phone) + + for admin_detail in issuer1.admin_details: + print(admin_detail.first_name) + print(admin_detail.last_name) + print(admin_detail.email) + print(admin_detail.phone) # Now we will list all of the certificate issuers for this key vault. To better demonstrate this, we will first create another issuer. await client.create_issuer( name="issuer2", - provider="Sample", + provider="Test", account_id="keyvaultuser", enabled=True ) diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/list_operations.py b/sdk/keyvault/azure-keyvault-certificates/samples/list_operations.py index c5e21ce7b7d7..ce931c17adfe 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/list_operations.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/list_operations.py @@ -9,19 +9,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 list operations on a vault(certificate) resource for Azure Key Vault. @@ -38,89 +32,75 @@ # # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - # Let's create a certificate for holding storage and bank accounts credentials. If the certificate - # already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificate") - bank_cert_name = "BankListCertificate" - storage_cert_name = "StorageListCertificate" - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) - - bank_certificate_poller = client.create_certificate(name=bank_cert_name, expires=expires) - storage_certificate_poller = client.create_certificate(name=storage_cert_name) - - # await the creation of the bank and storage certificate - bank_certificate_poller.wait() - storage_certificate_poller.wait() - - print("Certificate with name '{0}' was created.".format(bank_cert_name)) - print("Certificate with name '{0}' was created.".format(storage_cert_name)) - - # Let's list the certificates. - print("\n2. List certificates from the Key Vault") - certificates = client.list_certificates() - for certificate in certificates: - print("Certificate with name '{0}' was found.".format(certificate.name)) - - # You find the bank certificate needs to change the expiration date because the bank account credentials will be - # valid for an extra year. Calling create_certificate on an existing certificate creates a new version of the - # certificate in the Key Vault with the new value. - - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) - - client.create_certificate( - name=bank_cert_name, - expires=expires - ).wait() - print( - "Certificate with name '{0}' was updated with expiration date '{1}'".format( - bank_cert_name, - expires - ) +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: + # Let's create a certificate for holding storage and bank accounts credentials. If the certificate + # already exists in the Key Vault, then a new version of the certificate is created. + print("\n.. Create Certificate") + bank_cert_name = "BankListCertificate" + storage_cert_name = "StorageListCertificate" + + bank_certificate_poller = client.create_certificate(name=bank_cert_name) + storage_certificate_poller = client.create_certificate(name=storage_cert_name) + + # await the creation of the bank and storage certificate + bank_certificate_poller.wait() + storage_certificate_poller.wait() + + print("Certificate with name '{0}' was created.".format(bank_cert_name)) + print("Certificate with name '{0}' was created.".format(storage_cert_name)) + + # Let's list the certificates. + print("\n.. List certificates from the Key Vault") + certificates = client.list_certificates() + for certificate in certificates: + print("Certificate with name '{0}' was found.".format(certificate.name)) + + # You've decided to add tags to the certificate you created. Calling create_certificate on an existing + # certificate creates a new version of the certificate in the Key Vault with the new value. + + tags = {"a": "b"} + client.create_certificate(name=bank_cert_name, tags=tags).wait() + print( + "Certificate with name '{0}' was created again with tags '{1}'".format( + bank_cert_name, + tags ) + ) + + # You need to check all the different tags your bank account certificate had previously. Let's print + # all the versions of this certificate. + print("\n.. List versions of the certificate using its name") + certificate_versions = client.list_certificate_versions(bank_cert_name) + for certificate_version in certificate_versions: + print("Bank Certificate with name '{0}' with version '{1}' has tags: '{2}'.".format( + certificate_version.name, + certificate_version.version, + certificate_version.tags)) + + # The bank account and storage accounts got closed. Let's delete bank and storage accounts certificates. + client.delete_certificate(name=bank_cert_name) + client.delete_certificate(name=storage_cert_name) + + # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled. + print("\n.. List deleted certificates from the Key Vault") + deleted_certificates = client.list_deleted_certificates() + for deleted_certificate in deleted_certificates: + print("Certificate with name '{0}' has recovery id '{1}'".format( + deleted_certificate.name, + deleted_certificate.recovery_id)) + +except HttpResponseError as e: + if "(NotSupported)" in e.message: + print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message)) + else: + print("\nrun_sample has caught an error. {0}".format(e.message)) + +finally: + print("\nrun_sample done") - # You need to check all the different expiration dates your bank account certificate had previously. Let's print - # all the versions of this certificate. - print("\n3. List versions of the certificate using its name") - certificate_versions = client.list_certificate_versions(bank_cert_name) - for certificate_version in certificate_versions: - print("Bank Certificate with name '{0}' with version '{1}' has expiration date: '{2}'.".format( - certificate_version.name, - certificate_version.version, - certificate_version.expires)) - - # The bank acoount and storage accounts got closed. Let's delete bank and storage accounts certificates. - client.delete_certificate(name=bank_cert_name) - client.delete_certificate(name=storage_cert_name) - - # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled. - print("\n3. List deleted certificates from the Key Vault") - deleted_certificates = client.list_deleted_certificates() - for deleted_certificate in deleted_certificates: - print("Certificate with name '{0}' has recovery id '{1}'".format( - deleted_certificate.name, - deleted_certificate.recovery_id)) - - except HttpResponseError as e: - if "(NotSupported)" in e.message: - print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message)) - else: - print("\nrun_sample has caught an error. {0}".format(e.message)) - - finally: - print("\nrun_sample done") - - -if __name__ == "__main__": - try: - run_sample() - - except Exception as e: - print("Top level Error: {0}".format(str(e))) diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/list_operations_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/list_operations_async.py index 215198a576b9..1367423c431d 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/list_operations_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/list_operations_async.py @@ -3,27 +3,19 @@ # Licensed under the MIT License. # ------------------------------------ import asyncio -import datetime -import time import os from azure.keyvault.certificates.aio import CertificateClient from azure.identity.aio import DefaultAzureCredential from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 list operations on a vault(certificate) resource for Azure Key Vault. @@ -49,12 +41,11 @@ async def run_sample(): try: # Let's create a certificate for holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificate") + print("\n.. Create Certificate") bank_cert_name = "BankListCertificate" storage_cert_name = "StorageListCertificate" - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) - bank_certificate_poller = await client.create_certificate(name=bank_cert_name, expires=expires) + bank_certificate_poller = await client.create_certificate(name=bank_cert_name) storage_certificate_poller = await client.create_certificate(name=storage_cert_name) # await the creation of the bank and storage certificate @@ -65,38 +56,37 @@ async def run_sample(): print("Certificate with name '{0}' was created.".format(storage_cert_name)) # Let's list the certificates. - print("\n2. List certificates from the Key Vault") + print("\n.. List certificates from the Key Vault") certificates = client.list_certificates() async for certificate in certificates: print("Certificate with name '{0}' was found.".format(certificate.name)) - # You find the bank certificate needs to change the expiration date because the bank account credentials will be valid for an extra year. - # Calling create_certificate on an existing certificate creates a new version of the certificate in the Key Vault with the new value. + # You've decided to add tags to the certificate you created. Calling create_certificate on an existing + # certificate creates a new version of the certificate in the Key Vault with the new value. - expires = datetime.datetime.utcnow() + datetime.timedelta(days=365) + tags = {"a": "b"} - updated_bank_certificate_poller = await client.create_certificate(name=bank_cert_name, expires=expires) + updated_bank_certificate_poller = await client.create_certificate(name=bank_cert_name, tags=tags) await updated_bank_certificate_poller print( - "Certificate with name '{0}' was updated with expiration date '{1}'".format(bank_cert_name, expires) + "Certificate with name '{0}' was created again with tags '{1}'".format(bank_cert_name, tags) ) - # You need to check all the different expiration dates your bank account certificate had previously. Lets print all the versions of this certificate. - print("\n3. List versions of the certificate using its name") + # You need to check all the different tags your bank account certificate had previously. Lets print all the versions of this certificate. + print("\n.. List versions of the certificate using its name") certificate_versions = client.list_certificate_versions(bank_cert_name) async for certificate_version in certificate_versions: - print("Bank Certificate with name '{0}' with version '{1}' has expiration date: '{2}'.".format(certificate_version.name, certificate_version.version, certificate_version.expires)) + print("Bank Certificate with name '{0}' with version '{1}' has tags: '{2}'.".format( + certificate_version.name, + certificate_version.version, + certificate_version.tags)) - # The bank acoount and storage accounts got closed. Let's delete bank and storage accounts certificates. + # The bank account and storage accounts got closed. Let's delete bank and storage accounts certificates. await client.delete_certificate(name=bank_cert_name) await client.delete_certificate(name=storage_cert_name) - # To ensure certificate is deleted on the server side. - print("Deleting certificates...") - time.sleep(30) - # You can list all the deleted and non-purged certificates, assuming Key Vault is soft-delete enabled. - print("\n3. List deleted certificates from the Key Vault") + print("\n.. List deleted certificates from the Key Vault") deleted_certificates = client.list_deleted_certificates() async for deleted_certificate in deleted_certificates: print( diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations.py b/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations.py index d713f5d44554..03cd2ee2f382 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations.py @@ -3,24 +3,19 @@ # Licensed under the MIT License. # ------------------------------------ import os +import time from azure.keyvault.certificates import CertificateClient from azure.identity import DefaultAzureCredential from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 recover and purge operations on a vault(certificate) resource for Azure Key Vault @@ -35,67 +30,63 @@ # ---------------------------------------------------------------------------------------------------------- -def run_sample(): - # Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) - try: - # Let's create certificates holding storage and bank accounts credentials. If the certificate - # already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificates") - - bank_cert_name = "BankRecoverCertificate" - storage_cert_name = "ServerRecoverCertificate" - - bank_certificate_poller = client.create_certificate(name=bank_cert_name) - storage_certificate_poller = client.create_certificate(name=storage_cert_name) - - bank_certificate_poller.wait() - storage_certificate_poller.wait() - print("Certificate with name '{0}' was created.".format(bank_cert_name)) - print("Certificate with name '{0}' was created.".format(storage_cert_name)) - - # The storage account was closed, need to delete its credentials from the Key Vault. - print("\n2. Delete a Certificate") - deleted_bank_certificate = client.delete_certificate(name=bank_cert_name) - - print("Certificate with name '{0}' was deleted on date {1}.".format( - deleted_bank_certificate.name, - deleted_bank_certificate.deleted_date) - ) - - # We accidentally deleted the bank account certificate. Let's recover it. - # A deleted certificate can only be recovered if the Key Vault is soft-delete enabled. - print("\n3. Recover Deleted Certificate") - recovered_bank_certificate = client.recover_deleted_certificate(deleted_bank_certificate.name) - print("Recovered Certificate with name '{0}'.".format(recovered_bank_certificate.name)) - - # Let's delete the storage certificate now. - # If the keyvault is soft-delete enabled, then for permanent deletion deleted certificate needs to be purged. - client.delete_certificate(name=storage_cert_name) - - # To ensure permanent deletion, we might need to purge the secret. - print("\n4. Purge Deleted Certificate") - client.purge_deleted_certificate(name=storage_cert_name) - print("Certificate has been permanently deleted.") - - except HttpResponseError as e: - if "(NotSupported)" in e.message: - print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message)) - else: - print("\nrun_sample has caught an error. {0}".format(e.message)) - - finally: - print("\nrun_sample done") - - -if __name__ == "__main__": - try: - run_sample() +# Instantiate a certificate 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 = CertificateClient(vault_url=VAULT_URL, credential=credential) +try: + # Let's create certificates holding storage and bank accounts credentials. If the certificate + # already exists in the Key Vault, then a new version of the certificate is created. + print("\n.. Create Certificates") + + bank_cert_name = "BankRecoverCertificate" + storage_cert_name = "ServerRecoverCertificate" + + bank_certificate_poller = client.create_certificate(name=bank_cert_name) + storage_certificate_poller = client.create_certificate(name=storage_cert_name) + + bank_certificate_poller.wait() + storage_certificate_poller.wait() + print("Certificate with name '{0}' was created.".format(bank_cert_name)) + print("Certificate with name '{0}' was created.".format(storage_cert_name)) + + # The storage account was closed, need to delete its credentials from the Key Vault. + print("\n.. Delete a Certificate") + deleted_bank_certificate = client.delete_certificate(name=bank_cert_name) + # To ensure certificate is deleted on the server side. + time.sleep(30) + + print("Certificate with name '{0}' was deleted on date {1}.".format( + deleted_bank_certificate.name, + deleted_bank_certificate.deleted_date) + ) + + # We accidentally deleted the bank account certificate. Let's recover it. + # A deleted certificate can only be recovered if the Key Vault is soft-delete enabled. + print("\n.. Recover Deleted Certificate") + recovered_bank_certificate = client.recover_deleted_certificate(deleted_bank_certificate.name) + print("Recovered Certificate with name '{0}'.".format(recovered_bank_certificate.name)) + + # Let's delete the storage certificate now. + # If the keyvault is soft-delete enabled, then for permanent deletion deleted certificate needs to be purged. + client.delete_certificate(name=storage_cert_name) + # To ensure certificate is deleted on the server side. + time.sleep(30) + + # To ensure permanent deletion, we might need to purge the secret. + print("\n.. Purge Deleted Certificate") + client.purge_deleted_certificate(name=storage_cert_name) + print("Certificate has been permanently deleted.") + +except HttpResponseError as e: + if "(NotSupported)" in e.message: + print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message)) + else: + print("\nrun_sample has caught an error. {0}".format(e.message)) + +finally: + print("\nrun_sample done") - except Exception as e: - print("Top level Error: {0}".format(str(e))) diff --git a/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations_async.py b/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations_async.py index 75888e2b2d33..88e376419d5b 100644 --- a/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations_async.py +++ b/sdk/keyvault/azure-keyvault-certificates/samples/recover_purge_operations_async.py @@ -9,19 +9,13 @@ from azure.core.exceptions import HttpResponseError # ---------------------------------------------------------------------------------------------------------- -# Prerequistes - +# Prerequisites: +# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) # -# 1. An Azure Key Vault- -# https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli +# 2. azure-keyvault-certificates and azure-identity packages (pip install these) # -# 2. Microsoft Azure Key Vault PyPI package - -# https://pypi.python.org/pypi/azure-keyvault-certificates/ -# -# 3. Microsoft Azure Identity package - -# https://pypi.python.org/pypi/azure-identity/ -# -# 4. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL. -# How to do this - https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates#createget-credentials) +# 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 recover and purge operations on a vault(certificate) resource for Azure Key Vault @@ -47,9 +41,9 @@ async def run_sample(): try: # Let's create certificates holding storage and bank accounts credentials. If the certificate # already exists in the Key Vault, then a new version of the certificate is created. - print("\n1. Create Certificates") - bank_cert_name = "BankRecoverCertificate" - storage_cert_name = "ServerRecoverCertificate" + print("\n.. Create Certificates") + bank_cert_name = "BankRecoverCertificatezxv2" + storage_cert_name = "ServerRecoverCertificatezxcv2" bank_certificate_poller = await client.create_certificate(name=bank_cert_name) storage_certificate_poller = await client.create_certificate(name=storage_cert_name) @@ -60,8 +54,11 @@ async def run_sample(): print("Certificate with name '{0}' was created.".format(storage_cert_name)) # The storage account was closed, need to delete its credentials from the Key Vault. - print("\n2. Delete a Certificate") + print("\n.. Delete a Certificate") deleted_bank_certificate = await client.delete_certificate(name=bank_cert_name) + # To ensure certificate is deleted on the server side. + await asyncio.sleep(30) + print("Certificate with name '{0}' was deleted on date {1}.".format( deleted_bank_certificate.name, deleted_bank_certificate.deleted_date) @@ -69,16 +66,18 @@ async def run_sample(): # We accidentally deleted the bank account certificate. Let's recover it. # A deleted certificate can only be recovered if the Key Vault is soft-delete enabled. - print("\n3. Recover Deleted Certificate") + print("\n.. Recover Deleted Certificate") recovered_bank_certificate = await client.recover_deleted_certificate(deleted_bank_certificate.name) print("Recovered Certificate with name '{0}'.".format(recovered_bank_certificate.name)) # Let's delete storage account now. # If the keyvault is soft-delete enabled, then for permanent deletion deleted certificate needs to be purged. await client.delete_certificate(name=storage_cert_name) + # To ensure certificate is deleted on the server side. + await asyncio.sleep(30) # To ensure permanent deletion, we might need to purge the secret. - print("\n4. Purge Deleted Certificate") + print("\n.. Purge Deleted Certificate") await client.purge_deleted_certificate(name=storage_cert_name) print("Certificate has been permanently deleted.")