Using Python and Managed Identity to Authenticate and Run Code in Azure Container Apps Session Pools

This guide walks you through using Python and Azure Managed Identity to authenticate and execute code within Azure Container Apps Session Pools via the management API. This avoids storing secrets and securely leverages Microsoft Entra ID.
The following documentation is based on a source document linked below but modified to use managed identity. If anything is inaccurate, please check that guide.
Tutorial: Run JavaScript code in a code interpreter session in Azure Container Apps (preview)
🔐 Prerequisites and Permissions
- Azure Resources Required:
- Azure Subscription
- Azure Container Apps Session Pool (already deployed)
- A system-assigned or user-assigned managed identity
- Assign Roles to the Managed Identity:
Grant the following roles to the Managed Identity on the session pool resource:Azure Container Apps Session Executor
Azure Container Apps Contributor
- Audience Claim:
The identity token used must include anaud
claim for:https://dynamicsessions.io
⚙️ Environment Setup
Set the following environment variables in your Azure Function App (or local .env
file during development):
AZURE_SUBSCRIPTION_ID=<your-subscription-id>
CONTAINER_APP_RESOURCE_GROUP=<your-resource-group-name>
CONTAINER_APP_SESSION_POOL_NAME=<your-session-pool-name>
AZURE_REGION=<your-region> # e.g., eastus
🧠 Python Function Code Example
import azure.functions as func
import logging
import os
import json
import requests
from azure.identity import DefaultAzureCredential
app = func.FunctionApp(http_auth_level=func.AuthLevel.FUNCTION)
@app.route(route="RunCodeOnContainer")
def RunCodeOnContainer(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Processing request to run code in a container session.')
try:
# Load config
subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID')
resource_group = os.environ.get('CONTAINER_APP_RESOURCE_GROUP')
session_pool_name = os.environ.get('CONTAINER_APP_SESSION_POOL_NAME')
region = os.environ.get('AZURE_REGION', 'eastus')
if not all([subscription_id, resource_group, session_pool_name]):
return func.HttpResponse("Missing environment configuration.", status_code=500)
# Get token for dynamic sessions
credential = DefaultAzureCredential()
token = credential.get_token("https://dynamicsessions.io")
session_id = "test-session"
# Request URL
url = (
f"https://{region}.dynamicsessions.io/subscriptions/{subscription_id}/"
f"resourceGroups/{resource_group}/sessionPools/{session_pool_name}/"
f"code/execute?api-version=2024-02-02-preview&identifier={session_id}"
)
# Headers
headers = {
"Authorization": f"Bearer {token.token}",
"Content-Type": "application/json"
}
# Body
body = {
"properties": {
"codeInputType": "inline",
"executionType": "synchronous",
"code": "print('Hello World from Container App Session!')"
}
}
# POST request
response = requests.post(url, headers=headers, json=body)
if response.ok:
return func.HttpResponse(response.text, status_code=200, mimetype="application/json")
else:
return func.HttpResponse(f"Execution failed: {response.status_code} - {response.text}", status_code=response.status_code)
except Exception as e:
logging.error(f"Exception occurred: {str(e)}")
return func.HttpResponse(f"Internal error: {str(e)}", status_code=500)
✅ Step-by-Step Summary
1. Provision a Session Pool
Use Azure Portal or CLI to create a session pool:
az containerapp session-pool create --name <SESSION_POOL_NAME> \
--resource-group <RESOURCE_GROUP> --location <REGION> \
--concurrency 5 --idle-timeout 60
2. Assign Role to Managed Identity
az role assignment create \
--assignee <MANAGED_IDENTITY_CLIENT_ID> \
--role "Azure Container Apps Session Executor" \
--scope "/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RESOURCE_GROUP>/providers/Microsoft.App/sessionPools/<SESSION_POOL_NAME>"
(Repeat for the Azure Container Apps Contributor
role)
3. Deploy Python Function
- Set up a Python Azure Function App
- Configure environment variables
- Deploy code (see example above)
4. Test Endpoint
Trigger the endpoint (e.g., via Postman or a web client). The session will automatically be created and code will execute.