Connect a Python App to Azure Key Vault and CosmosDB

Coding + Azure + Python maurotommasi todayJanuary 15, 2024

Background
share close

Let’s create a Python application that requires access to Azure Key Vault to fetch information from a Cosmos DB using a specific query, we can use the Azure SDK for Python. Below is a basic example using the azure-cosmos library for Cosmos DB and the azure-identity library for Azure Key Vault integration.

Install the required packages

pip install azure-cosmos azure-identity

Create the Python Code

# Import necessary libraries
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from azure.cosmos import CosmosClient

# Function to retrieve a secret from Azure Key Vault
def get_secret_from_keyvault(vault_url, secret_name):
    # Authenticate to Azure Key Vault using default credentials
    credential = DefaultAzureCredential()
    secret_client = SecretClient(vault_url=vault_url, credential=credential)

    # Retrieve the secret value from Key Vault
    secret_value = secret_client.get_secret(secret_name).value
    return secret_value

# Function to query data from Cosmos DB
def query_cosmos_db(cosmos_connection_string, database_id, container_id, query):
    # Connect to Cosmos DB using the provided connection string
    cosmos_client = CosmosClient(cosmos_connection_string)
    database_client = cosmos_client.get_database_client(database_id)
    container_client = database_client.get_container_client(container_id)
    
    # Execute the specified query and retrieve results
    query_results = container_client.query_items(query, enable_cross_partition_query=True)
    return list(query_results)

# Main function
if __name__ == "__main__":
    # Azure Key Vault configuration
    keyvault_url = "https://YourKeyVaultName.vault.azure.net/"
    secret_name = "CosmosDBConnectionStringSecret"

    # Cosmos DB configuration
    cosmos_db_connection_string_secret = get_secret_from_keyvault(keyvault_url, secret_name)
    cosmos_db_connection_string = cosmos_db_connection_string_secret.strip()

    # Cosmos DB query
    cosmos_db_database_id = "YourCosmosDBDatabaseId"
    cosmos_db_container_id = "YourCosmosDBContainerId"
    cosmos_db_query = "SELECT * FROM c WHERE c.YourProperty = 'YourValue'"

    # Fetch data from Cosmos DB
    results = query_cosmos_db(cosmos_db_connection_string, cosmos_db_database_id, cosmos_db_container_id, cosmos_db_query)

    # Process and print the results
    for result in results:
        print(result)

DefaultAzureCredential()

The DefaultAzureCredential is a part of the Azure Identity library in Python, which provides a default way to authenticate your application to Azure services. It simplifies the process of obtaining Azure Active Directory (AAD) tokens, which are required for authentication when interacting with Azure services, including Azure Key Vault.

Here’s how the DefaultAzureCredential works:

  1. Environment Variables:
    • The DefaultAzureCredential first checks for the presence of environment variables that might contain authentication information.
    • Common environment variables include AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_USERNAME.
  2. Managed Identity:
    • If no environment variables are found, the DefaultAzureCredential attempts to use Managed Identity credentials if your code is running in an Azure environment that supports Managed Identity.
    • Managed Identity allows your application to use Azure AD identities without embedding credentials in your code.
  3. Visual Studio Code (VS Code) Authentication Extension:
    • If running in Visual Studio Code with the Azure Account extension installed, the DefaultAzureCredential leverages the extension for authentication.
  4. Azure CLI:
    • If the Azure CLI is installed and you have signed in, the DefaultAzureCredential can use the Azure CLI’s credentials for authentication.
  5. Interactive Browser Login:
    • If none of the above methods provide credentials, the DefaultAzureCredential opens a browser window to interactively authenticate the user.
  6. Azure Managed Service Identity (MSI):
    • If running on an Azure resource that supports Managed Service Identity (MSI), the DefaultAzureCredential attempts to use MSI.
  7. Azure SDK Log:
    • If authentication fails, the Azure SDK logs detailed information about the attempted authentication, helping in debugging.

By attempting various methods in sequence, the DefaultAzureCredential ensures that it can acquire credentials in various environments and scenarios without requiring you to explicitly specify the authentication method.

For example, if your application is running in an Azure environment with Managed Identity, the DefaultAzureCredential will automatically use that identity. If you’re developing locally and have signed in using the Azure CLI, it will use those credentials. The flexibility provided by DefaultAzureCredential makes it suitable for a wide range of scenarios and environments.

The environment file .env can be used installing the package as follow: pip install python-env.

We can set up our .env file as follow:

AZURE_TENANT_ID=your_tenant_id
AZURE_CLIENT_ID=your_client_id
AZURE_CLIENT_SECRET=your_client_secret

and use the .env configuration in the python code:

import os
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential

# Load environment variables from the .env file
load_dotenv()

# Use DefaultAzureCredential to authenticate
credential = DefaultAzureCredential()

This is an example code. It’s a good practice to standardize the code creating a class called, for example, azure-framework where inside we can split all functionalities based on their area (Azure Key Vult, Azure Cosmo DB and so on) and creating function to retrieve data as needed.

Written by: maurotommasi

Rate it
Previous post

Similar posts

Post comments (0)

Leave a reply

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


LOGO

  • help@firwl.com
  • info@firwl.com


Products


Company


Contacts

Support

en_USEnglish