Covers a Bicep template for Container Apps, Key Vault, Azure SQL with Entra-only authentication, a user-assigned managed identity, role assignments with deterministic guid names, .bicepparam files, what-if, and the database user step Bicep cannot perform.
I create a user-assigned managed identity first, then a Key Vault with enableRbacAuthorization: true, an Azure SQL server with Entra-only authentication (no SQL admin password), and a Container App that runs as that identity. Access is granted with Microsoft.Authorization/roleAssignments resources whose names are guid(scope, principalId, roleId), so redeployments are idempotent. The app receives AZURE_CLIENT_ID and a password-less connection string, and DefaultAzureCredential does the rest.
.bicepparam files.az deployment group what-if.The trade-off: Bicep handles the Azure control plane well, but it cannot create the SQL database user (a data-plane action), so a pipeline step runs CREATE USER ... FROM EXTERNAL PROVIDER.
"I start with a user-assigned managed identity rather than a system-assigned one. The identity exists before the Container App, so I can grant it roles on Key Vault and set it as something the app pulls secrets with, without a chicken-and-egg problem, and it survives if the app is recreated. Then Key Vault with RBAC authorisation turned on, soft delete and purge protection, and a role assignment giving the identity Key Vault Secrets User. Role assignments in Bicep are resources; their name must be a GUID, and I use
guid(kv.id, identity.id, roleId)so the name is deterministic. If you use a random GUID the second deployment fails with 'role assignment already exists'.For SQL I set the server's administrator to an Entra group with
azureADOnlyAuthentication: true, so there is no SQL login password anywhere. The app's connection string usesAuthentication=Active Directory Managed Identitywith the identity's client ID. The one thing Bicep cannot do is create the user inside the database:CREATE USER [id-orders-prod] FROM EXTERNAL PROVIDERand the role memberships are T-SQL, so a pipeline step runs that withsqlcmdas a member of the admin group. The Container App getsAZURE_CLIENT_ID, the Key Vault URI and the connection string as plain environment variables, because none of them is a secret.Structure-wise it is one
main.bicep, modules once it grows, and one.bicepparamper environment, and the pipeline runswhat-ifbeforecreate. The mistake I see is people granting roles by hand after the deployment, or giving the pipeline Owner so it can create role assignments. The pipeline identity needs Role Based Access Control Administrator, ideally with a condition limiting which roles it may assign, on just that resource group."
| Resource | Key settings | Why |
|---|---|---|
userAssignedIdentities |
none | The app's identity; lifecycle independent of the app |
Microsoft.KeyVault/vaults |
enableRbacAuthorization, enablePurgeProtection |
RBAC instead of access policies; secrets cannot be destroyed instantly |
roleAssignments |
name: guid(...), principalType: 'ServicePrincipal' |
Idempotent; avoids replication-delay errors on new identities |
Microsoft.Sql/servers |
administrators.azureADOnlyAuthentication: true |
No SQL passwords to leak or rotate |
Microsoft.App/containerApps |
identity: UserAssigned, env vars |
Runs as the identity; config without secrets |
| Task | Why not | Where it goes |
|---|---|---|
| Create the SQL contained user and roles | Data plane (T-SQL) | Pipeline step with sqlcmd or a migration bundle |
| Put secret values in Key Vault from Git | Secrets must not be in source | Set once by an operator or generated by the service |
| Build and push the container image | Not infrastructure | CI job before the deployment |
Moving a service from connection strings in app settings to this template removes every long-lived credential: zero secrets to rotate, and the quarterly password rotation ticket disappears. A full environment deploys in roughly 6–8 minutes, and what-if on an unchanged environment reports no changes, which is the drift check the pipeline runs nightly.
Checks that the candidate can write real, idempotent Bicep for a typical .NET workload and knows where managed identity and RBAC fit, including the parts Bicep cannot do.
Green flags
guid() for role assignment names and explains why.bicepparam per environment, what-if before deployRed flags
Bicep infers dependencies from symbolic references, so you rarely write dependsOn.
identity ─────────────┬──► kv role assignment ──┐
│ ▼
log analytics ─► container apps env ─────► container app (uses identity, kv URI, sql FQDN)
│
sql server (Entra admin) ─► database
The Container App references kvRole explicitly with dependsOn because nothing in its properties points at the role assignment, yet it needs the role to exist before it pulls a Key Vault secret.
| System-assigned | User-assigned | |
|---|---|---|
| Lifecycle | Dies with the app | Independent resource |
| Known before app exists | No | Yes |
| Shared across apps | No | Yes (use with care) |
| Extra config in code | None | Set AZURE_CLIENT_ID so DefaultAzureCredential picks it |
A role assignment is Microsoft.Authorization/roleAssignments at a scope (the Key Vault, a storage account, the resource group). Three details matter:
guid(scope.id, principalId, roleDefinitionId).principalType: 'ServicePrincipal' tells ARM not to look the principal up in Entra ID first, which avoids a 'principal does not exist' error when the identity was created seconds ago and has not replicated.4633458b-17de-408a-b874-0445c86b69e6). Keep them in variables with a comment.The deploying identity needs Microsoft.Authorization/roleAssignments/write. Role Based Access Control Administrator with a condition restricting the assignable roles is the least-privilege way.
Container App ─► ManagedIdentityCredential ─► token for https://database.windows.net/
─► SqlClient sends token on TDS login ─► SQL checks the contained user
azureADOnlyAuthentication: true disables SQL logins completely. The server admin is an Entra group (so people can join and leave). Inside the database, CREATE USER [identity-name] FROM EXTERNAL PROVIDER maps the managed identity, and ALTER ROLE db_datareader ADD MEMBER ... grants rights. This is data plane, so ARM cannot do it.
A Container App secret can reference a Key Vault secret by URL plus the identity to use. The platform fetches it, and it shows up as an env var through secretRef. Use this only for genuine third-party secrets (an API key from a payment provider). For Azure services, use managed identity directly and avoid the secret entirely.
.bicepparam files are type-checked against the template (using './main.bicep'). Keep only true differences in them: SKUs, replica counts, the admin group ID. Secure values use @secure() and come from the pipeline or az.getSecret() in a param file, never from Git.
This template keeps public endpoints for brevity. Production adds a VNet-integrated Container Apps environment, private endpoints for Key Vault and SQL, publicNetworkAccess: 'Disabled', and private DNS zones.
guid(...) with newGuid() as a default parameter and watch the second deployment fail with RoleAssignmentExists.sqlcmd step, then call an endpoint that reads the database and check the SQL audit log shows the managed identity as the principal.bicep lint and fix every warning it reports.The template: identity, Key Vault with RBAC, Azure SQL with Entra-only auth, and a Container App that uses all three without secrets.
// main.bicep
@allowed([ 'dev', 'test', 'prod' ])
param environmentName string
param location string = resourceGroup().location // australiaeast
param containerImage string // e.g. myacr.azurecr.io/orders-api:1.4.2
param sqlAdminGroupName string // Entra group that administers SQL
param sqlAdminGroupObjectId string
param minReplicas int = 1
var suffix = take(uniqueString(resourceGroup().id), 6)
var keyVaultSecretsUser = '4633458b-17de-408a-b874-0445c86b69e6' // built-in role id
resource identity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = {
name: 'id-orders-${environmentName}'
location: location
}
resource logs 'Microsoft.OperationalInsights/workspaces@2023-09-01' = {
name: 'log-orders-${environmentName}'
location: location
properties: { sku: { name: 'PerGB2018' }, retentionInDays: 30 }
}
resource kv 'Microsoft.KeyVault/vaults@2023-07-01' = {
name: 'kv-orders-${environmentName}-${suffix}'
location: location
properties: {
tenantId: tenant().tenantId
sku: { family: 'A', name: 'standard' }
enableRbacAuthorization: true // RBAC, not access policies
enableSoftDelete: true
softDeleteRetentionInDays: 90
enablePurgeProtection: true // a deleted vault cannot be purged before retention ends
}
}
// Deterministic name: redeploying finds the same assignment instead of failing
resource kvRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
name: guid(kv.id, identity.id, keyVaultSecretsUser)
scope: kv
properties: {
roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', keyVaultSecretsUser)
principalId: identity.properties.principalId
principalType: 'ServicePrincipal' // skip the Entra lookup; avoids replication-delay errors
}
}
resource sql 'Microsoft.Sql/servers@2021-11-01' = {
name: 'sql-orders-${environmentName}-${suffix}'
location: location
properties: {
minimalTlsVersion: '1.2'
administrators: {
administratorType: 'ActiveDirectory'
azureADOnlyAuthentication: true // no SQL logins, no password to leak
login: sqlAdminGroupName
sid: sqlAdminGroupObjectId
principalType: 'Group'
tenantId: tenant().tenantId
}
}
}
resource db 'Microsoft.Sql/servers/databases@2021-11-01' = {
parent: sql
name: 'orders'
location: location
sku: { name: 'GP_S_Gen5', tier: 'GeneralPurpose', family: 'Gen5', capacity: 2 }
}
resource env 'Microsoft.App/managedEnvironments@2024-03-01' = {
name: 'cae-orders-${environmentName}'
location: location
properties: {
appLogsConfiguration: {
destination: 'log-analytics'
logAnalyticsConfiguration: {
customerId: logs.properties.customerId
sharedKey: logs.listKeys().primarySharedKey
}
}
}
}
resource app 'Microsoft.App/containerApps@2024-03-01' = {
name: 'ca-orders-${environmentName}'
location: location
identity: {
type: 'UserAssigned'
userAssignedIdentities: { '${identity.id}': {} }
}
properties: {
managedEnvironmentId: env.id
configuration: {
ingress: { external: true, targetPort: 8080 } // .NET 8+ images listen on 8080
}
template: {
containers: [
{
name: 'api'
image: containerImage
resources: { cpu: json('0.5'), memory: '1Gi' }
env: [
{ name: 'AZURE_CLIENT_ID', value: identity.properties.clientId }
{ name: 'KeyVault__Uri', value: kv.properties.vaultUri }
{
name: 'ConnectionStrings__Orders'
// Not a secret: no password, the token comes from the managed identity
value: 'Server=tcp:${sql.properties.fullyQualifiedDomainName},1433;Database=${db.name};Authentication=Active Directory Managed Identity;User Id=${identity.properties.clientId};Encrypt=True;'
}
]
}
]
scale: { minReplicas: minReplicas, maxReplicas: 5 }
}
}
dependsOn: [ kvRole ] // the app reads Key Vault at startup
}
output identityName string = identity.name
output sqlServerFqdn string = sql.properties.fullyQualifiedDomainName
// env/prod.bicepparam
using '../main.bicep'
param environmentName = 'prod'
param containerImage = 'myacr.azurecr.io/orders-api:1.4.2'
param sqlAdminGroupName = 'sg-sql-admins-prod'
param sqlAdminGroupObjectId = '00000000-0000-0000-0000-000000000000'
param minReplicas = 2
# Preview, deploy, then the data-plane step Bicep cannot do
az deployment group what-if -g rg-orders-prod -f main.bicep -p env/prod.bicepparam
az deployment group create -g rg-orders-prod -f main.bicep -p env/prod.bicepparam
# Run as a member of the SQL admin group (sqlcmd go version supports Entra auth)
sqlcmd -S sql-orders-prod-abc123.database.windows.net -d orders \
--authentication-method ActiveDirectoryDefault -Q "
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'id-orders-prod')
CREATE USER [id-orders-prod] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [id-orders-prod];
ALTER ROLE db_datawriter ADD MEMBER [id-orders-prod];"
// Program.cs: the app side. No secrets in configuration.
using Azure.Identity;
var builder = WebApplication.CreateBuilder(args);
// Picks up AZURE_CLIENT_ID in Azure; uses your az / Visual Studio login locally
var credential = new DefaultAzureCredential();
if (builder.Configuration["KeyVault:Uri"] is { Length: > 0 } vaultUri)
{
// Package: Azure.Extensions.AspNetCore.Configuration.Secrets
builder.Configuration.AddAzureKeyVault(new Uri(vaultUri), credential);
}
builder.Services.AddDbContext<OrdersDb>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
var app = builder.Build();
app.MapGet("/health", () => Results.Ok());
app.Run();
newGuid() or a random value. Why it is wrong: The second deployment tries to create a duplicate and fails with RoleAssignmentExists. Instead: guid(scope.id, principalId, roleDefinitionId).principalType: 'ServicePrincipal' for a new identity. Why it is wrong: ARM looks the principal up in Entra ID, and replication lag can make it fail with PrincipalNotFound. Instead: Set principalType explicitly.enableRbacAuthorization: true and built-in roles such as Key Vault Secrets User.Authentication=Active Directory Managed Identity.Login failed for user '<token-identified principal>'. Instead: A pipeline step running CREATE USER ... FROM EXTERNAL PROVIDER.AZURE_CLIENT_ID with a user-assigned identity. Why it is wrong: DefaultAzureCredential cannot tell which identity to use and fails or picks the wrong one. Instead: Pass the client ID as an env var.The design choice that matters most here is removing secrets rather than storing them better. Managed identity plus Entra-only SQL means there is nothing to rotate and nothing to leak, which also simplifies Privacy Act and Essential Eight conversations about credential management. Key Vault is then only for genuine third-party secrets.
The second senior point is knowing the control-plane / data-plane boundary. Bicep (and Terraform) manage Azure resources; database users, Key Vault secret values and blob contents are data plane and need a separate, idempotent step. Teams that miss this end up with a template that 'works' and an app that cannot log in.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| User-assigned identity | Most apps; identity known before the app | One more resource, AZURE_CLIENT_ID |
Rarely a reason not to |
| System-assigned identity | Simple single-resource cases | Role assignments wait on the app | Identity reused across apps or slots |
| Key Vault secret reference | Third-party API keys | Rotation process still needed | Azure services that support Entra auth |
Measure it: what-if on an unchanged environment should report zero changes; anything else is drift or a non-idempotent template.
Managed identity gives the app an Entra ID identity that Azure manages, so there is no secret to store or rotate. In code, Azure.Identity gets tokens: DefaultAzureCredential tries managed identity in Azure and the developer's az login or Visual Studio sign-in locally. Then:
AddAzureKeyVault.BlobServiceClient with the credential.CREATE USER [app-name] FROM EXTERNAL PROVIDER, add it to database roles, and use Authentication=Active Directory Default in the connection string.Use a user-assigned identity when several apps share access or it must survive redeploys. The trade-off is setup effort in RBAC and SQL users in exchange for no secrets at all.
On a laptop, DefaultAzureCredential uses my az login identity, which has broad dev rights. In Azure it uses the app's managed identity, which may not exist, may be the wrong one, or may lack roles. I diagnose in layers:
AZURE_CLIENT_ID set?ForbiddenByRbac means missing Key Vault Secrets User (or the vault uses access policies). SQL's <token-identified principal> means the token worked but there is no contained database user.ForbiddenByFirewall or ForbiddenByConnection means firewall or private endpoint and DNS problems.The trade-off: granting broad roles makes the error go away fast but breaks least privilege; the right fix is the exact data role at the exact scope.
I build it in layers:
The trade-off is cost and complexity (private DNS, more resources) versus a much smaller attack surface and a tested recovery path.
Last updated 23 Nov 2026.