1# ------------------------------------ 2# Copyright (c) Microsoft Corporation. 3# Licensed under the MIT License. 4# ------------------------------------ 5import os 6from azure.identity import DefaultAzureCredential 7from azure.keyvault.certificates import CertificateClient, CertificateContact 8from azure.core.exceptions import HttpResponseError 9 10# ---------------------------------------------------------------------------------------------------------- 11# Prerequisites: 12# 1. An Azure Key Vault (https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli) 13# 14# 2. azure-keyvault-certificates and azure-identity packages (pip install these) 15# 16# 3. Set Environment variables AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET, VAULT_URL 17# (See https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-keys#authenticate-the-client) 18# 19# ---------------------------------------------------------------------------------------------------------- 20# Sample - demonstrates basic CRUD operations for the certificate contacts for a key vault. 21# 22# 1. Create contacts (set_contacts) 23# 24# 2. Get contacts (get_contacts) 25# 26# 3. Delete contacts (delete_contacts) 27# ---------------------------------------------------------------------------------------------------------- 28 29# Instantiate a certificate client that will be used to call the service. 30# Notice that the client is using default Azure credentials. 31# To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', 32# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials. 33VAULT_URL = os.environ["VAULT_URL"] 34credential = DefaultAzureCredential() 35client = CertificateClient(vault_url=VAULT_URL, credential=credential) 36try: 37 # First we create a list of Contacts that we would like to make the certificate contacts for this key vault. 38 contact_list = [ 39 CertificateContact(email="admin@contoso.com", name="John Doe", phone="1111111111"), 40 CertificateContact(email="admin2@contoso.com", name="John Doe2", phone="2222222222"), 41 ] 42 43 # Creates and sets the certificate contacts for this key vault. 44 client.set_contacts(contact_list) 45 46 # Gets the certificate contacts for this key vault. 47 contacts = client.get_contacts() 48 for contact in contacts: 49 print(contact.name) 50 print(contact.email) 51 print(contact.phone) 52 53 # Deletes all of the certificate contacts for this key vault. 54 client.delete_contacts() 55 56except HttpResponseError as e: 57 print("\nrun_sample has caught an error. {0}".format(e.message)) 58 59finally: 60 print("\nrun_sample done") 61