Azure Key Vault is used to store sensitive information like Keys, Secrets, Certificates. For Eg: Azure Storage Account Keys can be stored as Secrets. It is not a good practice to hardcode this information in our application or in configuration files. So that is why we store our passwords, keys in Azure Key Vault.

But for accessing the Secrets stored in Key Vault we need information like TenantId, ClientId, ClientSecret. Click on this link to know more. ClientSecret is in itself a private information. So again we have to put this somewhere it’s safe. This is a lot of hassle.

So that is why we use a built in feature in Azure called Managed Service Identity which helps to communicate with other Azure services as itself using a managed Azure Active Directory identity. By going this way there is no need for any TenantId, ClientId, ClientSecret.

STEPS:
  • Create an Azure Function
  • Enable Managed Service Identity
  • Create Key Vault
  • Test the Function
CREATE AN AZURE FUNCTION
  • Click on Create a Resource
  • Click on Compute and then choose Function App
  • Fill in the required values and click on Create
  • After the Function is provisioned go to that function and click on + icon.
  • Click on Create your custom function.
  • Enable the Experimental Language Support and choose HTTP Triggered Function.
  • Choose Python as the language and click create.
  • Paste the below code in the workspace. Also replace key_vault _uri and Name of your Secret with your own respective values.

from msrestazure.azure_active_directory import MSIAuthentication
from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient
from azure.keyvault.key_vault_client import KeyVaultClient
# Create MSI Authentication
credentials = MSIAuthentication(resource='https://vault.azure.net')
key_vault_client = KeyVaultClient(credentials)
key_vault_uri='https://.vault.azure.net/'
secret = key_vault_client.get_secret(
key_vault_uri, # Your KeyVault URL
"", # Name of your secret. If you followed the README 'secret' should exists
"" # The version of the secret. Empty string for latest
)
secret=secret.value
print(secret) 

Be sure to install the required packages from Kudu Console, you can access Kudu by going to Platform Features -> Development Tools -> Advanced Tools (Kudu).

Run these commands in Kudu Console:

  • pip install azure-mgmt-resource
  • pip install azure-keyvault
  • pip install msrestazur

 

  • Click on Save. We will not run it yet.
  • Your Function is ready.
ENABLE MANAGED SERVICE IDENTITY
  • Go to Platform Features
  • Choose Managed Service Identity
  • Click On and then Save
CREATE KEY VAULT
  • Go to Key Vaults and Click on Add.
  • Fill in the required fields and Choose Access Policy.
  • Click on Add New. Then Select Service Principal and choose the Function App that we just created. And Click on Select.
  • Choose Get Action for Key, Secret, Certificates and then Click on OK. Then Again Click on OK and Create. Your Key Vault is provisioned.
  • Now we will create a Secret. Secrets can be any data that you don’t want to make public ranging from Storage account Keys, Sendgrid keys etc.. Go to Secrets and Click on Generate and Import.
  • Choose Manual in Upload Options. Set Activation and Expiration Dates and Click on Create.
TEST THE FUNCTION
  • Now again go to your Function and this time Run it
  • In the Logs section, you will see the value of the Secret which you have stored in Key Vault
  • Use it however you want.
  • In my case, the secret is Azure Storage Account Key and I use it to generate SAS Tokens that can be used by the application to access Blobs, Tables, Queues.

Let me know if you face any difficulties in implementing this solution.

One thought to “Retrieve Azure Key Vault Secrets using Azure Functions (Python)”

  • Qudir Ahmad Ansari

    I am getting below error in get the secret key, please help:

    File “D:/home/python354x64/Lib/site-packages\azure\keyvault\key_vault_id.py”, line 92, in parse_object_id
    raise ValueError(“invalid id: {}. Bad number of segments: {}”.format(id, num_segments))
    ValueError: invalid id: https://xxxxxxxxxxxxxxx.vault.azure.net. Bad number of segments: 0
    (xxxxxxxxxxxxxxx: I have replaced function name with my xxxxxxxxxxxxxxx)

    Code:
    import sys, os.path
    import glob
    import urllib2
    import datetime
    import platform

    sys.path.append(‘D:/home/python354x64/Lib/site-packages’)
    print(os.environ[‘keyvaulturi’])

    print(‘startinggggggggggg……’)
    from azure.mgmt.resource import ResourceManagementClient
    from azure.mgmt.subscriptions import SubscriptionClient
    print(‘Debug-1’)
    from msrestazure.azure_active_directory import MSIAuthentication
    print(‘Debug-2′)
    from azure.keyvault.key_vault_client import KeyVaultClient
    # Create MSI Authentication
    credentials = MSIAuthentication(resource=’https://vault.azure.net’)
    print(‘Debug-3’)
    key_vault_client = KeyVaultClient(credentials)
    print(‘Debug-4’)
    key_vault_uri=os.environ[‘keyvaulturi’]
    print(‘Debug-5’)
    secret = key_vault_client.get_secret(key_vault_uri,”TableStorageConfigurationSecret”,””)
    print(‘Debug-6’)
    secret=secret.value
    print(secret)

    Reply

Leave a comment

Your email address will not be published. Required fields are marked *