This sample demonstrates a Python Flask single-page web application called Vacation Planner hosted on an Azure Web App. The app runs on an Azure App Service Plan and stores activity data in the activities table of the PlannerDB database on an Azure Database for PostgreSQL flexible server, reached through a Private Endpoint. What sets this permutation apart from the PostgreSQL sample it derives from is where the app reads its connection settings from: the host, port and database name live in an Azure App Configuration store, the application role name and password live in Azure Key Vault and reach the app through App Configuration Key Vault references, and the app authenticates to both stores with a user-assigned managed identity authorized through Azure RBAC. No connection string, access key or database credential is stored in the Web App's app settings.
The web app enables users to plan and manage vacation activities; all data is persisted in PostgreSQL. The solution is composed of the following Azure resources:
- Azure Resource Group: A logical container scoping all resources in this sample.
- Azure Virtual Network: Hosts two subnets:
- app-subnet: Delegated to
Microsoft.Web/serverFarmsfor regional VNet integration of the Web App. - pe-subnet: Hosts the three Private Endpoints to the PostgreSQL flexible server, the App Configuration store and the Key Vault.
- app-subnet: Delegated to
- Azure Private DNS Zones
privatelink.postgres.database.azure.com,privatelink.azconfig.ioandprivatelink.vaultcore.azure.net, each linked to the VNet with alink-to-vnetvirtual network link. The DNS zone group (default) of each Private Endpoint registers theArecord of its target, so the Web App resolves the three services to private IP addresses. - Azure Private Endpoints:
<prefix>-postgres-pe-<suffix>(grouppostgresqlServer),<prefix>-appconfig-pe-<suffix>(groupconfigurationStores) and<prefix>-keyvault-pe-<suffix>(groupvault). - Azure NAT Gateway: Deterministic outbound connectivity for the Web App subnet.
- Azure Network Security Group: One NSG per subnet.
- Azure Log Analytics Workspace: Centralizes the diagnostic logs and metrics of every resource, the store and the vault included, the telemetry of Application Insights, and the audit records of the queries run on it.
- Azure Application Insights
<prefix>-insights-<suffix>: A workspace-based resource that collects the requests, the calls to App Configuration, Key Vault and PostgreSQL, the log records, the exceptions, the custom events and the custom metric of the web app, which the Microsoft OpenTelemetry Distro sends to the connection string of theAPPLICATIONINSIGHTS_CONNECTION_STRINGapp setting. See Application Insights. - Azure Database for PostgreSQL flexible server: Public-access server hosting the
PlannerDBdatabase. BurstableStandard_B1ms, version 16, 32 GiB storage, 7-day backup retention, HA disabled. A permissive firewall rule (0.0.0.0to255.255.255.255) lets the deploy machine run the post-create psql bootstrap; the Web App itself reaches the server through the Private Endpoint. - PostgreSQL database
PlannerDB: Created at provisioning time; the post-deploy psql step creates theactivitiestable and seeds the demo rows. - Azure App Configuration store
<prefix>-appconfig-<suffix>(Standard tier): Holds the five connection settings as key-values, see Configuration design. Access keys stay enabled (the default) because the deployment scripts and templates write the key-values with them; the Web App never uses them. - Azure Key Vault
<prefix>-keyvault-<suffix>with the Azure RBAC permission model: Holds the secretspg-userandpg-passwordwith the credentials of the PostgreSQL application role. - User-assigned managed identity
<prefix>-identity-<suffix>, assigned to the Web App, with two role assignments: App Configuration Data Reader on the store and Key Vault Secrets User on the vault. - Azure App Service Plan: The underlying compute tier that hosts the web application.
- Azure Web App: Runs the Python Flask Vacation Planner app with regional VNet integration into app-subnet and the user-assigned managed identity. Its app settings hold the store endpoint (
Endpoints__AppConfiguration), the identity client id (AZURE_CLIENT_ID),LOGIN_NAME,WEBSITES_PORT, the connection string of the Application Insights resource (APPLICATIONINSIGHTS_CONNECTION_STRING) and the Oryx build flags. NoPG_*app setting exists: the app connects to PostgreSQL with the dedicated application role (testuser) it reads from the store, and the server-admin login is never used at runtime. - App Service Source Control: (Optional) Configures continuous deployment from a public GitHub repository.
The deploy scripts and templates follow the same pattern as the sibling web-app-postgresql-flexible-server sample: after provisioning, they (i) connect as the server admin via the public endpoint and the firewall rule, (ii) create the application role testuser with its own password, (iii) grant minimum schema privileges on PlannerDB, (iv) create the activities table and (v) seed the sample rows. The difference is step (vi): the role name and password are not written onto the Web App's app settings; they are stored in Key Vault and referenced from the App Configuration store at provisioning time, and the app loads them from there.
The application needs five PostgreSQL connection settings. They are stored by sensitivity: the three connection details are key-values in the App Configuration store, and the two credentials are secrets in the Key Vault, exposed to the application through Key Vault references in the same store.
| Setting | Stored in | Key or secret name | Content type |
|---|---|---|---|
PG_HOST |
App Configuration key-value | PG_HOST |
none |
PG_PORT |
App Configuration key-value | PG_PORT |
none |
PG_DATABASE |
App Configuration key-value | PG_DATABASE |
none |
PG_USER |
Key Vault secret, referenced from the store | PG_USER referencing pg-user |
application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8 |
PG_PASSWORD |
Key Vault secret, referenced from the store | PG_PASSWORD referencing pg-password |
application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8 |
How the settings are stored. The key-values are named like the environment variables the application reads, carry no label, and hold plain values: PG_HOST and PG_PORT come from the fully qualified domain name of the PostgreSQL flexible server, PG_DATABASE is PlannerDB. PG_USER and PG_PASSWORD are Key Vault references: key-values whose content type is application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8 and whose value is the identifier of a secret, {"uri":"https://<vault>.vault.azure.net/secrets/pg-user"}. The identifier is versionless, so a reference always follows the latest version of its secret. The store never holds the secret values; they live only in the vault, as the secrets pg-user and pg-password (Key Vault secret names allow only alphanumerics and hyphens). Whoever reads the store sees where every setting comes from, and only an identity with read access to the vault can turn the two references into values.
How the application reads them. The Web App receives two app settings: Endpoints__AppConfiguration, the store endpoint, and AZURE_CLIENT_ID, the client id of its user-assigned managed identity. At startup the application loads the PG_* keys with the Azure App Configuration Python provider and one DefaultAzureCredential: on App Service the credential is the user-assigned managed identity selected by AZURE_CLIENT_ID, on a developer machine it is the signed-in Azure CLI user. The provider reads the key-values from the store (the identity holds App Configuration Data Reader on it), recognizes the two Key Vault references by their content type and fetches the secrets from the vault with the same credential (the identity holds Key Vault Secrets User on it), so the application ends up with five plain settings. Both calls travel through the Private Endpoints of the store and the vault, resolved by the Private DNS Zones linked to the VNet. See src/settings.py:
credential = DefaultAzureCredential()
settings = load(
endpoint=os.environ["Endpoints__AppConfiguration"],
credential=credential,
keyvault_credential=credential,
selects=[SettingSelector(key_filter="PG_*")],
startup_timeout=60,
)The load is retried for a few minutes, so a role assignment that has not propagated yet produces log lines rather than a crash loop, and the application logs which keys it loaded and how many Key Vault references it resolved, never the values. The settings are read once at startup; a changed key-value or secret takes effect when the app restarts. The app setting is called Endpoints__AppConfiguration in both language variants because it is the app-setting spelling of the Endpoints:AppConfiguration key the .NET configuration system reads.
On Azure the store endpoint is https://<store>.azconfig.io and the vault URI is https://<vault>.vault.azure.net/; on the emulator they are https://<store>.azure.localhost.localstack.cloud:4566 and https://<vault>.vault.azure.localhost.localstack.cloud:4566. The scripts and templates read both values back from the service and never assemble them from a name, so the same code runs on both targets.
- lstk CLI
- Azure Subscription
- Azure CLI
- Python 3.11+
- Flask
- psycopg2 (
psycopg2-binaryfor development) - Azure App Configuration Python provider and Azure Identity (installed from
src/requirements.txt) - PostgreSQL client tools (
psql), required by the deploy scripts to create the application role and seed data - Bicep extension, if you plan to install the sample via Bicep
- Terraform, if you plan to install the sample via Terraform
Important
Macs with Apple silicon: this sample deploys a web app from code. The emulator builds it with Microsoft's Oryx build image and runs it on an Oryx runtime image, and Microsoft publishes both for amd64 only (microsoft/Oryx#2133 asks for arm64). On a Mac with Apple silicon they run only under Docker Desktop's amd64 emulation: in Docker Desktop's settings, under General, select the Apple Virtualization framework as the Virtual Machine Manager and turn on Use Rosetta for x86_64/amd64 emulation on Apple Silicon. Under QEMU, which Docker Desktop uses otherwise (Rosetta off, or Docker VMM, which has no Rosetta), the sample is not expected to work: Oryx is a .NET app, and .NET does not support QEMU. The sample does not run on an arm64 Linux host without amd64 emulation.
Set up the Azure emulator using the LocalStack for Azure Docker image. Before starting, ensure you have a valid LOCALSTACK_AUTH_TOKEN. Refer to the Auth Token guide to obtain yours. Pull and start the emulator:
docker pull localstack/localstack-azure
export LOCALSTACK_AUTH_TOKEN=<your_auth_token>
lstk start --type azure
# Route all Azure CLI calls to the LocalStack Azure emulator
lstk az start-interceptionDeploy the application using one of these methods:
All three variants provision the same topology: a VNet whose pe-subnet hosts three Private Endpoints, to a public-access PostgreSQL flexible server, to the App Configuration store and to the Key Vault, each with its Private DNS Zone linked to the VNet; the store seeded with the three plain key-values and the two Key Vault references; the vault seeded with the two secrets; the user-assigned managed identity with its two role assignments; and the Web App configured with the store endpoint and the identity client id only.
The store and the vault have globally unique names: on Azure, export your own SUFFIX (or PREFIX) before running a variant. When you are done, delete the resource group and purge the soft-deleted store and vault (az appconfig purge, az keyvault purge) so that their names are released.
Note
When you deploy the application to LocalStack for Azure for the first time, the initialization process pulls and builds Docker images (LocalStack itself plus the postgres:18 backing container for the flexible-server emulator). This is a one-time operation; subsequent deployments are much faster.
- Retrieve the host port Docker maps to the port the Web App listens on in its container, for example with
docker port <container-name>(the container's name starts withls-<web-app-name>). Do not assume port 80: the app listens on the port itsWEBSITES_PORTapp setting names, when it has one. - Open a web browser and navigate to
http://localhost:<published-port>. - If the deployment was successful, you will see the Vacation Planner UI with the seeded activities and can add, edit, and remove activities.
You can use the scripts/call-web-app.sh Bash script to call the web app from outside the emulator. The script demonstrates four call paths:
- Through the LocalStack for Azure emulator via the default hostname.
- Via localhost and host port mapped to the container's port
80. - Via container IP address on port
80. - Via the default hostname
<web-app-name>.azurewebsites.azure.localhost.localstack.cloud:4566.
To inspect the configuration the app runs with, list the key-values of the store with their content types (the two Key Vault references stand out), the secret names in the vault (never the values), and the app settings of the Web App, which must contain no PG_* entry:
az appconfig kv list --name local-appconfig-test \
--query "[].{Key:key,ContentType:contentType,Label:label}" --output table
az keyvault secret list --vault-name local-keyvault-test --query "[].name" --output tsv
az webapp config appsettings list --name local-webapp-test --resource-group local-rg \
--query "[?starts_with(name, 'PG_')].name" --output tsvThe projection uses --query rather than --fields: --fields makes the CLI request only those fields from the service, and the CLI then fails to build a Key Vault reference whose value was not returned. scripts/validate.sh runs these checks, and fails if a PG_* app setting exists. The app itself reports its configuration source at startup; on the emulator read it with docker logs on the container whose name starts with ls-local-webapp-test:
Loaded 5 settings from App Configuration https://local-appconfig-test.azure.localhost.localstack.cloud:4566 (PG_DATABASE, PG_HOST, PG_PASSWORD, PG_PORT, PG_USER); 2 Key Vault references resolved (PG_PASSWORD, PG_USER)
PostgreSQL schema initialized
The web app sends its telemetry to <prefix>-insights-<suffix>, a workspace-based Application Insights resource that stores it in the <prefix>-log-analytics-<suffix> workspace. The three deployment methods set the APPLICATIONINSIGHTS_CONNECTION_STRING app setting to the connection string of the resource, and the application turns on the Microsoft OpenTelemetry Distro when the setting is present. The application also sends a custom event for each activity it adds, updates or deletes, counts these operations in the activities custom metric, and logs the exceptions it catches:
from microsoft.opentelemetry import use_microsoft_opentelemetry
# The logger of the application
LOGGER_NAME = "webapp"
if os.environ.get("APPLICATIONINSIGHTS_CONNECTION_STRING"):
use_microsoft_opentelemetry(enable_azure_monitor=True, logger_name=LOGGER_NAME)
from flask import Flask
from opentelemetry import metrics
activity_counter = metrics.get_meter(LOGGER_NAME).create_counter(
"activities", unit="{activity}", description="The number of activities added, updated and deleted."
)
def track_activity_event(event_name: str, operation: str, activity_id: str) -> None:
logger.info(
f"{event_name}: {activity_id}",
extra={"microsoft.custom_event.name": event_name, "activity.id": activity_id},
)
activity_counter.add(1, {"operation": operation})The distro starts before the application imports Flask and psycopg2, so that its instrumentations wrap them, and it collects the records of the webapp logger and of its children (webapp.database, webapp.settings).
The workspace keeps the telemetry in these tables:
| Table | What the web app sends |
|---|---|
AppRequests |
The requests it serves, such as GET / |
AppDependencies |
Its calls to App Configuration, Key Vault and PostgreSQL |
AppTraces |
The records of its loggers, such as the line it writes once it has loaded its settings |
AppEvents |
The ActivityAdded, ActivityUpdated and ActivityDeleted custom events, with the id of the activity in activity.id |
AppMetrics |
The activities custom metric, with the operation (add, update or delete) in operation |
AppExceptions |
The exceptions it logs, with their stack trace, when a call to PostgreSQL fails |
scripts/query-telemetry.sh calls the web app, adds an activity, and reads the tables back, retrying until their records arrive. It shows the exceptions without waiting for them: a healthy run has none.
The web app, its App Service plan, the App Configuration store, the key vault, the PostgreSQL server, the VNet, the two NSGs, the NAT Gateway and its public IP each have a diagnostic setting that sends their resource logs, their platform metrics (AllMetrics) or both to the <prefix>-log-analytics-<suffix> Log Analytics workspace, and the workspace has one that sends the audit records of the queries run on it (Audit, table LAQueryLogs) to itself. The Application Insights resource has none: its telemetry is already in the workspace it's based on, and a diagnostic setting of a workspace-based Application Insights resource can't send to that workspace. The private endpoints and the private DNS zones offer no diagnostic settings, and neither does the managed identity. The four resources the application uses record what it does:
| Resource | Log categories | Tables in the workspace | What the application leaves there |
|---|---|---|---|
| Web App | AppServiceHTTPLogs, AppServiceConsoleLogs, AppServicePlatformLogs, AppServiceAppLogs, AppServiceAuditLogs, AppServiceIPSecAuditLogs, AppServiceAuthenticationLogs |
One table per category, named after it | The requests it serves, its console output (the gunicorn access log and the application's log lines) and the start of its container |
| App Configuration store | HttpRequest, Audit |
AACHttpRequest, AACAudit |
The GET /kv?key=PG_* with which the application loads its settings, made by its managed identity |
| Key Vault | AuditEvent, AzurePolicyEvaluationDetails |
AZKVAuditLogs, AZKVPolicyEvaluationDetailsLogs |
The SecretGet of pg-user and pg-password that resolves the two Key Vault references |
| PostgreSQL flexible server | PostgreSQLLogs |
PGSQLServerLogs |
The connections of the testuser role |
Their platform metrics land in the AzureMetrics table. The settings of the key vault and of the PostgreSQL server write to the resource-specific tables, which Microsoft recommends over the shared AzureDiagnostics table: the Azure CLI script passes --export-to-resource-specific true, the Bicep modules set logAnalyticsDestinationType: 'Dedicated' and the Terraform modules log_analytics_destination_type = "Dedicated". App Service and App Configuration write to resource-specific tables only. The App Service plan sends its metrics too, and the VNet and the two NSGs their network logs; on the emulator the network categories stay empty, because no traffic crosses an emulated network security group.
The query command comes from the log-analytics extension of the Azure CLI:
az extension add --name log-analyticsThe query API identifies a workspace by its workspace id (customerId):
WORKSPACE_ID=$(az monitor log-analytics workspace show \
--resource-group local-rg \
--workspace-name local-log-analytics-test \
--query customerId \
--output tsv)
az monitor log-analytics query \
--workspace "$WORKSPACE_ID" \
--analytics-query "AppServiceHTTPLogs | project TimeGenerated, CsMethod, CsUriStem, ScStatus, TimeTaken | order by TimeGenerated desc | take 5" \
--output tableCsMethod CsUriStem ScStatus TableName TimeGenerated TimeTaken
---------- ----------- ---------- ------------- --------------------------- -----------
GET / 200 PrimaryResult 2026-11-06T16:05:45.368091Z 51
GET / 200 PrimaryResult 2026-11-06T16:05:45.283727Z 51
GET / 200 PrimaryResult 2026-11-06T16:05:45.188826Z 55
...
On Azure the table also records the requests of the zip deployment to the app's Kudu site, such as POST /api/publish and GET /api/deployments/latest. The other tables answer the same way. A few queries to try:
// The line the application writes once it has loaded its settings
AppServiceConsoleLogs
| where ResultDescription has "App Configuration"
| project TimeGenerated, ResultDescription
// The requests that loaded the settings, with the principal id of the web app's managed identity (ClientObjectId)
AACHttpRequest
| project TimeGenerated, Method, StatusCode, HitCount, ClientObjectId, RequestURI
// The reads of the two secrets behind the Key Vault references
AZKVAuditLogs
| where OperationName == "SecretGet"
| project TimeGenerated, OperationName, ResultSignature, RequestUri
// The connections of the application role (on Azure the server also logs those of its maintenance role, azuresu)
PGSQLServerLogs
| where Message has "connection authorized" and Message has "testuser"
| project TimeGenerated, Message
// The requests per minute, which the Logs page of the portal draws as a chart
AppServiceHTTPLogs
| summarize Requests = count() by bin(TimeGenerated, 1m)
| render columnchartThe platform metrics need no diagnostic setting: the Azure Monitor metrics API serves them directly.
WEB_APP_ID=$(az webapp show \
--name local-webapp-test \
--resource-group local-rg \
--query id \
--output tsv)
az monitor metrics list \
--resource "$WEB_APP_ID" \
--metrics Requests Http2xx BytesSent \
--interval PT1M \
--aggregation Total \
--query "value[].{Metric:name.value,Total:sum(timeseries[].data[].total)}" \
--output tableMetric Total
--------- --------
Requests 8.0
Http2xx 8.0
BytesSent 171720.0
scripts/query-logs-and-metrics.sh does all of this in one go: it calls the web app, lists the diagnostic settings of the four resources, runs queries like these (plus the platform events of the web app and the exported AzureMetrics) until their records arrive, and prints the metrics of the web app, the store, the vault and the server. It exits with a non-zero code when the web app does not answer, or when a query still lacks its records after RETRY_COUNT attempts (30 by default) made SLEEP seconds apart (10 by default), except for the exported platform metrics on Azure (see below).
The emulator serves an emulated Azure portal at http://localhost:4566/_localstack/portal/ (see Azure Portal Emulator):
- Open the portal and select Sign in: the sign-in is a mock and asks for no credentials.
- Select Resource groups, then
local-rg, thelocal-log-analytics-testworkspace and Logs. Type a query, for example therender columnchartquery above, and select Run: the Results tab lists the records and the Chart tab draws them. - Open the
local-webapp-testweb app. Under Monitoring, Metrics charts its platform metrics: select the Requests metric, which the chart shows with its default Sum aggregation. Logs runs queries over the records of the web app only, and Diagnostic settings lists its diagnostic setting. - The App Configuration store, the key vault and the PostgreSQL server have the same Metrics, Logs and Diagnostic settings pages.
On the emulator the records are queryable within seconds, and the aggregated ones (AACHttpRequest and AzureMetrics) once their one-minute window is over. On Azure the records take minutes, and the first records of a new diagnostic setting can take up to 90 minutes: run the queries again later, or raise RETRY_COUNT for the script. The exported platform metrics (AzureMetrics) are the exception: Azure exports them late and irregularly, so on Azure query-logs-and-metrics.sh reads them once, shows those that arrived and notes how many are still missing, without failing. A new setting can also take a while before it delivers anything, and on Azure the records of what the application did while it started, such as its start-up console lines or its secret reads in the key vault, can then be missing for good: once the workspace receives records, az webapp restart --name local-webapp-test --resource-group local-rg starts the application again, and the records of the new start arrive.
- The app logs
App Configuration load failed ... 403orForbiddenand restarts. The identity's role assignments have not propagated yet (up to 10 minutes on Azure), or one of them is missing. Checkaz role assignment list --assignee <principalId> --allfor App Configuration Data Reader on the store and Key Vault Secrets User on the vault; the app keeps retrying and App Service restarts it until the load succeeds. az keyvault createoraz appconfig createfails because the name exists in a deleted state. A previous run soft-deleted the resource. The scripts recover it automatically; to start from scratch, purge it:az keyvault purge --name <vault> --location <location>andaz appconfig purge --name <store> --location <location> --yes.KeyVaultReferenceExceptionorNo key vault credential or secret resolver callback configured. The provider found a Key Vault reference but has no credential for Key Vault. The sample passes the same credential withkeyvault_credential=credential(Python) orConfigureKeyVault(kv => kv.SetCredential(credential))(.NET); keep that call.The setting Endpoints__AppConfiguration was not found.The Web App has no store endpoint app setting. Set it to the value ofaz appconfig show --name <store> --query endpoint --output tsv.- The app stops with a message about a literal
@Microsoft.AppConfiguration(...)value. The Web App holds an App Service configuration reference as an app setting and the platform did not resolve it (LocalStack for Azure hands app settings to the container verbatim). This sample expects the plain store endpoint inEndpoints__AppConfigurationand loads the settings itself. az keyvault secret setkeeps failing withForbiddenon Azure. The deploying principal has no Key Vault Secrets Officer assignment on the vault (the script could not resolve its object id) or the assignment is still propagating. Assign the role and re-run; the scripts are idempotent.
You can use pgAdmin to explore and manage the deployed database. Connect using:
| Field | Value |
|---|---|
| Host | localhost |
| Port | (see docker ps for the host-mapped port of the backing postgres:18 container) |
| Database | PlannerDB |
| Username | testuser (or pgadmin for admin operations) |
| Password | TestP@ssw0rd123 (or P@ssw0rd1234! for the admin) |
The application role credentials are the values of the pg-user and pg-password secrets; read them with az keyvault secret show --vault-name local-keyvault-test --name pg-password --query value --output tsv when you override the defaults. Or use psql:
PGPASSWORD='TestP@ssw0rd123' psql -h localhost -p <port> -U testuser -d PlannerDB
PlannerDB=> SELECT id, username, activity, created_at FROM activities;- Azure Web Apps Documentation
- Azure Database for PostgreSQL flexible server
- Quickstart: Python Flask on Azure
- psycopg2 documentation
- Quickstart: Create a Python app with Azure App Configuration
- Azure App Configuration Python provider
- Tutorial: Use Key Vault references in a Python app
- Access Azure App Configuration using Microsoft Entra ID
- Use managed identities to access App Configuration
- Use App Configuration references for App Service and Azure Functions
- Use Key Vault references as app settings in Azure App Service
- Use private endpoints for Azure App Configuration
- Integrate Key Vault with Azure Private Link
- Provide access to Key Vault keys, certificates, and secrets with Azure RBAC
- Azure App Configuration best practices
- Naming rules and restrictions for Azure resources
- LocalStack for Azure
- lstk CLI
- lstk GitHub repository

