Skip to content

Commit

Permalink
Key Vault: reworked certificates samples, all passing (#7225)
Browse files Browse the repository at this point in the history
* reworked certificates samples, all passing

* automatically run sync samples instead of within a try catch block
  • Loading branch information
iscai-msft authored Sep 12, 2019
1 parent 58e3bf1 commit 1caeded
Show file tree
Hide file tree
Showing 12 changed files with 433 additions and 542 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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.
Expand All @@ -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))

Expand Down
87 changes: 36 additions & 51 deletions sdk/keyvault/azure-keyvault-certificates/samples/contacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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='[email protected]',
name='John Doe',
phone='1111111111'),
Contact(email='[email protected]',
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='[email protected]',
name='John Doe',
phone='1111111111'),
Contact(email='[email protected]',
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)))
finally:
print("\nrun_sample done")
16 changes: 5 additions & 11 deletions sdk/keyvault/azure-keyvault-certificates/samples/contacts_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading

0 comments on commit 1caeded

Please sign in to comment.