📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Write Bicep that deploys a .NET 10 API to Azure Container Apps with a Key Vault and an Azure SQL database, using a managed identity instead of any connection-string secrets. How do you assign RBAC roles in Bicep, structure parameters per environment, and what can Bicep not do for you?

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.

Intermediate Coding Intermediate azure-sql bicep container-apps devops infrastructure-as-code managed-identity

🎯 Key points

  • Order: user-assigned identity first, then Key Vault and SQL, role assignments, then the Container App (dependsOn the role)
  • Role assignment name = guid(scope, principal, role) so redeploys are idempotent
  • Key Vault with enableRbacAuthorization, soft delete and enablePurgeProtection, plus the Key Vault Secrets User role
  • Azure SQL with azureADOnlyAuthentication and an Entra group as admin; no SQL admin password anywhere
  • Connection string has no password: Authentication=Active Directory Managed Identity plus AZURE_CLIENT_ID
  • Control plane vs data plane: CREATE USER ... FROM EXTERNAL PROVIDER runs in a pipeline step, not Bicep
  • One main.bicep plus a .bicepparam per environment; az deployment group what-if before create
  • Pipeline identity gets RBAC Administrator scoped to the resource group, with a condition limiting assignable roles

⏱ 30-second answer

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.

  • Environments differ only through .bicepparam files.
  • Every change is previewed with 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 uses Authentication=Active Directory Managed Identity with 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 PROVIDER and the role memberships are T-SQL, so a pipeline step runs that with sqlcmd as a member of the admin group. The Container App gets AZURE_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 .bicepparam per environment, and the pipeline runs what-if before create. 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."


What each resource does

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

What Bicep cannot do

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

Production example

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.

🔍 What the interviewer is checking

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

  • Uses guid() for role assignment names and explains why
  • Entra-only SQL with a group admin and no password parameter
  • Knows the SQL contained user is a separate data-plane step
  • One template plus .bicepparam per environment, what-if before deploy

Red flags

  • Connection strings with passwords in app settings or parameters
  • Grants roles manually in the portal after deployment
  • Pipeline runs as Owner on the subscription

📚 Learn in depth

1. Order of creation and dependencies

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.

2. Why user-assigned identity

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

3. Role assignments as resources

A role assignment is Microsoft.Authorization/roleAssignments at a scope (the Key Vault, a storage account, the resource group). Three details matter:

  1. Name must be a GUID and stable: guid(scope.id, principalId, roleDefinitionId).
  2. 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.
  3. Built-in role IDs are fixed GUIDs (Key Vault Secrets User is 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.

4. Azure SQL without passwords

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.

5. Container Apps secrets from Key Vault

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.

6. Parameters per environment

.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.

7. Network hardening (next step)

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.

Try it yourself

  1. Deploy the template to a sandbox resource group in Australia East, then run it again and confirm what-if shows no changes.
  2. Replace guid(...) with newGuid() as a default parameter and watch the second deployment fail with RoleAssignmentExists.
  3. Run the sqlcmd step, then call an endpoint that reads the database and check the SQL audit log shows the managed identity as the principal.
  4. Remove the Key Vault role assignment and observe the Container App revision fail to provision because it cannot read the secret.
  5. Run bicep lint and fix every warning it reports.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Naming role assignments with 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).
  • Mistake: Leaving out 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.
  • Mistake: Using Key Vault access policies in new templates. Why it is wrong: Policies are vault-wide, cannot be scoped or conditioned, and are managed separately from Azure RBAC. Instead: enableRbacAuthorization: true and built-in roles such as Key Vault Secrets User.
  • Mistake: Passing a SQL admin password as a parameter, or putting a password in the app's connection string. Why it is wrong: It ends up in deployment history, pipeline variables, app settings and often Git, and it has to be rotated. Instead: Entra-only authentication with a group as administrator, and a connection string that uses Authentication=Active Directory Managed Identity.
  • Mistake: Expecting Bicep to create the database user. Why it is wrong: Users are a data-plane T-SQL concept; ARM has no resource for them, so the app gets Login failed for user '<token-identified principal>'. Instead: A pipeline step running CREATE USER ... FROM EXTERNAL PROVIDER.
  • Mistake: Forgetting 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.
  • Mistake: Giving the pipeline Owner, or an unconditioned Role Based Access Control Administrator at subscription scope, so it can write role assignments. Why it is wrong: Either lets a compromised pipeline grant any role, including Owner, to anyone. Instead: Contributor plus Role Based Access Control Administrator scoped to the target resource group with a condition that only allows assigning the specific roles the template uses (for example Key Vault Secrets User and Storage Blob Data Contributor).
  • Mistake: Turning off soft delete or purge protection to make test teardown easier, then copying that to prod. Why it is wrong: A bad deployment or attacker can permanently destroy secrets. Instead: Soft delete and purge protection on in every long-lived environment; use separate, short-lived test vaults with unique names.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DefaultAzureCredential or AZURE_CLIENT_ID. Why: Checks the candidate understands the runtime side of managed identity that the template sets up.
    How to answer

    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:

    • Key Vault: grant Key Vault Secrets User and use AddAzureKeyVault.
    • Blob Storage: grant Storage Blob Data Contributor and create BlobServiceClient with the credential.
    • Azure SQL: 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.

  2. When: Candidate mentions role assignments or the SQL contained user. Why: Checks what the candidate does when the deployed app gets 403 or login failures despite the template.
    How to answer

    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:

    1. Which identity? Is managed identity enabled, and for user-assigned, is AZURE_CLIENT_ID set?
    2. Authorisation: read the error code. Key Vault 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.
    3. Network: 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.

  3. When: Candidate notes the template still uses public endpoints. Why: Checks the candidate can extend the template to a hardened production network design.
    How to answer

    I build it in layers:

    • Compute: App Service Premium v3 (or a Container Apps workload-profile environment) in Australia East with zone redundancy, at least two instances, and a health check path.
    • Releases: a staging slot with warm-up and swap (or revisions with traffic splitting).
    • Network: traffic enters through Front Door Premium or Application Gateway with WAF, the app only accepts traffic from it; outbound uses VNet integration, and SQL, Key Vault and Storage are reached through private endpoints with public access off.
    • Identity and ops: managed identity everywhere, Application Insights and alerts on SLOs.
    • Resilience: a warm or cold standby in Australia Southeast with SQL failover groups and geo-redundant storage, all from IaC.

    The trade-off is cost and complexity (private DNS, more resources) versus a much smaller attack surface and a tested recovery path.

↩ Usually asked after

More in Infrastructure as Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me