Skip to content
Visual explainer 8h to learn 5 steps

Capstone: deploy the API and worker with Bicep

Provision and release the API and worker with Bicep and a scoped deploy identity.

By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 13 minutes to read.

Topic 32 of 33

In short

Now you turn the design into code. Bicep modules create the monitoring workspace, registry, storage, identities, role assignments and the two container apps. A GitHub Actions workflow signs in to Azure with workload identity federation, so no secret is stored, previews the change with what-if, deploys, builds the image and rolls out a new revision.

Explained simply

In this milestone the design becomes running software. You write Bicep files that describe every resource. You create a deploy identity that GitHub Actions can use without any password. Then you push code and watch the pipeline build the image and roll it out.

Bicep is Azure's language for describing infrastructure. You split it into modules, one file per part: monitoring, storage, identities, registry and apps. The main file calls each module and passes values between them, such as the storage account's address. Running the same files again gives the same result, which is what makes the system repeatable.

The deploy identity is a managed identity with a federated credential. The credential says: trust tokens from GitHub, but only from this repository and this environment. GitHub Actions asks GitHub for a short-lived token, swaps it for an Azure token, and deploys. No secret is ever stored in GitHub.

Apps need settings, such as the storage address and which identity to use. These are plain environment variables, not secrets, because the managed identity proves who the app is. The only sensitive value is the Application Insights connection string, which you can store as a Container Apps secret.

You will also do one operation twice: once in the Azure Portal and once with the Azure CLI. That shows you understand what the tools do underneath. Prerequisites: an Azure subscription where you can create role assignments, a GitHub repository, the Azure CLI with the Bicep tooling, and Docker if you build locally.

Press Play on a diagram to walk through it one step at a time.

FlowFrom git push to a running revision
  1. 1
    Push to main

    Workflow starts in the production environment

  2. 2
    OIDC sign-in

    azure/login exchanges a GitHub token for an Entra token

  3. 3
    What-if

    az deployment group what-if shows planned changes

  4. 4
    Deploy Bicep

    Identities, storage, roles, environment, apps

  5. 5
    Build and push image

    Tagged with the commit SHA in the registry

  6. 6
    Update apps

    New revision; smoke test /healthz

MapBicep module layout
main.bicep
  • monitoring.bicep
    • Log Analytics workspace
    • Application Insights
  • storage.bicep
    • Storage account
    • uploads and results containers
    • jobs queue
  • identity.bicep
    • id-api
    • id-worker
    • Role assignments
  • registry.bicep
    • Container registry, admin user off
    • AcrPull for both identities
  • apps.bicep
    • Container Apps environment
    • ca-api with ingress
    • ca-worker without ingress
CompareThree ways to make the same change
Portal
  • Good for exploring and learning
  • Visual check of what exists
  • Hard to repeat exactly
  • Leaves drift if code also manages it
Azure CLI
  • Scriptable and quick for one-offs
  • Output can be saved as evidence
  • Still imperative: order matters
  • Ideal for checks and diagnostics
Bicep in a pipeline
  • Declarative desired state
  • Reviewed in pull requests
  • What-if before apply
  • The source of truth for the capstone

In depth

Write the Bicep modules

Start with main.bicep. It takes a few parameters, such as location, environment name and image tag, and calls each module in order. Bicep works out the order from references: when apps.bicep needs storage.outputs.blobEndpoint, Bicep deploys storage first. You rarely need dependsOn.

Keep names predictable with a short prefix and uniqueString(resourceGroup().id) for globally unique names like the storage account. Set secure defaults in the modules: allowSharedKeyAccess false and minimumTlsVersion TLS1_2 on storage, adminUserEnabled false on the registry, and tags on everything. Run az bicep build to catch errors early, then az deployment group what-if to see the plan. Save the what-if output; it is evidence that you reviewed the change before applying it.

  • Parameters: location, envName, imageTag, budget owner alias
  • Outputs: blob endpoint, queue name, identity client IDs, API URL
  • Role assignments use guid() names so redeploys are idempotent
  • Container apps reference identities for registry pulls

Create the deploy identity

Create a user-assigned managed identity, id-gh-deploy, in a small separate resource group so deleting the lab does not delete the pipeline's identity mid-run. Add a federated credential with issuer https://token.actions.githubusercontent.com, audience api://AzureADTokenExchange, and a subject such as repo:contoso/thumbs:environment:dev. Only jobs that run in that GitHub environment can use it.

Assign it Contributor on rg-capstone-dev, and Role Based Access Control Administrator on the same group with a condition limiting which roles it can assign. In the workflow, set permissions id-token: write and use azure/login with the identity's client ID, the tenant ID and the subscription ID stored as GitHub variables, not secrets, because none of them is secret. Protect the GitHub environment with required reviewers if you add a production stage.

SequenceHow the workflow signs in without a secret
GitHub Actions job
GitHub OIDC provider
Microsoft Entra ID
Azure Resource Manager
  1. 1Request token for audience api://AzureADTokenExchange
    GitHub Actions job to GitHub OIDC provider: Request token for audience api://AzureADTokenExchange
  2. 2Signed JWT: repo, environment dev
    GitHub OIDC provider to GitHub Actions job: Signed JWT: repo, environment dev
  3. 3Exchange JWT; Entra checks issuer, subject, audience
    GitHub Actions job to Microsoft Entra ID: Exchange JWT; Entra checks issuer, subject, audience
  4. 4Short-lived access token for id-gh-deploy
    Microsoft Entra ID to GitHub Actions job: Short-lived access token for id-gh-deploy
  5. 5Deploy main.bicep to rg-capstone-dev
    GitHub Actions job to Azure Resource Manager: Deploy main.bicep to rg-capstone-dev
  6. 6Deployment succeeded, outputs returned
    Azure Resource Manager to GitHub Actions job: Deployment succeeded, outputs returned

Configure environment settings

Each container app gets environment variables in its Bicep template. AZURE_CLIENT_ID holds the app's own identity client ID, so DefaultAzureCredential in the Azure SDK picks the right user-assigned identity. STORAGE_ACCOUNT_URL and QUEUE_NAME come from the storage module's outputs. OTEL_SERVICE_NAME sets the role name you will filter on in KQL.

APPLICATIONINSIGHTS_CONNECTION_STRING goes in as a Container Apps secret and is referenced by secretRef. Scale settings are configuration too: the API has minReplicas 0 or 1 and an HTTP scale rule; the worker can scale on queue length with a KEDA azure-queue rule, using its managed identity where the platform supports it, or simply run one replica in the lab. Keep dev and prod differences in parameter files, not in copied templates.

Release from the pipeline

The workflow has two jobs. The infrastructure job signs in, runs what-if, then runs az deployment group create. The app job builds the image with the commit SHA as its tag, pushes it with az acr build or docker push after az acr login, then updates both container apps to that tag. Each update creates a new revision.

After the update, a smoke test calls /healthz on the API URL and fails the job if it does not return 200 within a minute. Use single revision mode in dev for simplicity, or multiple revision mode if you want to shift traffic gradually and keep the old revision ready. Record the run URL, the what-if summary and the revision name; together they are the deployment evidence.

Show Portal and CLI equivalents

Pick one core operation and do it both ways. Assigning a role is a good choice. In the Portal, open the storage account, select Access control (IAM), then Add role assignment, choose Storage Blob Data Reader, select Managed identity as the member type, pick id-worker, and Review + assign. With the CLI it is one az role assignment create command with the principal ID, role name and scope.

Compare the results with az role assignment list: both show the same principal, role and scope. Then remove the Portal-made assignment and let Bicep own it, because anything created by hand drifts from the code. The lesson is that the Portal, CLI and Bicep all call the same Azure Resource Manager API; they differ only in how repeatable and reviewable the change is.

Learn it in 5 short steps

About 1h 35m each. Track them with a timer in your plan.

  1. 1
    Write the Bicep modules~1h 35m
  2. 2
    Create the deploy identity~1h 35m
  3. 3
    Configure environment settings~1h 35m
  4. 4
    Release from the pipeline~1h 35m
  5. 5
    Show Portal and CLI equivalents~1h 35m

Key points

  • Pass outputs between modules (IDs, endpoints) instead of hard-coding names.
  • The deploy identity gets Contributor on one resource group plus a constrained right to assign roles.
  • Settings such as STORAGE_ACCOUNT_URL and AZURE_CLIENT_ID are configuration, not secrets.
  • Run what-if before every deploy and keep its output as evidence.
  • Do each core step once in the Portal and once with the CLI so you can operate either way.

Key terms

Tap a card to flip it. 0/5 known

Examples

bicep
resource blobRole 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(storage.id, apiIdentity.id, 'blob-contributor')
  scope: storage
  properties: {
    // Storage Blob Data Contributor
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')
    principalId: apiIdentity.properties.principalId
    principalType: 'ServicePrincipal'
  }
}

A role assignment scoped to the storage account, with a stable name so redeploys do not duplicate it.

Create the deploy identity and its federated credential

Run once, by someone with rights to create identities and role assignments. Prerequisites: Azure CLI signed in, the target resource group created, and the GitHub repository contoso/thumbs with an environment named dev. Evidence: the federated credential list shows the subject, and the workflow's azure/login step succeeds. Rollback: delete the identity, which removes its credential and role assignments stop applying. Add the conditioned RBAC Administrator role separately in the Portal or with a condition file.

bash
az group create -n rg-capstone-cicd -l westeurope --tags project=capstone
az identity create -g rg-capstone-cicd -n id-gh-deploy
az identity federated-credential create -g rg-capstone-cicd --identity-name id-gh-deploy \
  --name gh-dev --issuer https://token.actions.githubusercontent.com \
  --subject repo:contoso/thumbs:environment:dev --audiences api://AzureADTokenExchange

PRINCIPAL=$(az identity show -g rg-capstone-cicd -n id-gh-deploy --query principalId -o tsv)
RG_ID=$(az group show -n rg-capstone-dev --query id -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role Contributor --scope $RG_ID
az identity show -g rg-capstone-cicd -n id-gh-deploy --query clientId -o tsv  # AZURE_CLIENT_ID variable

The release workflow, trimmed to its core

The job runs in the dev environment so the federated credential's subject matches. It signs in, previews and deploys the Bicep, builds the image in the registry, updates the API, and smoke-tests it. The worker update is the same az containerapp update line with ca-worker. Evidence: a green run, a new revision name in the log, and a 200 from /healthz.

yaml
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: dev
    permissions: { id-token: write, contents: read }
    steps:
      - uses: actions/checkout@v4
      - uses: azure/login@v2
        with: { client-id: "${{ vars.AZURE_CLIENT_ID }}", tenant-id: "${{ vars.AZURE_TENANT_ID }}", subscription-id: "${{ vars.AZURE_SUBSCRIPTION_ID }}" }
      - run: az deployment group what-if -g rg-capstone-dev -f infra/main.bicep -p infra/dev.bicepparam
      - run: az deployment group create -g rg-capstone-dev -f infra/main.bicep -p infra/dev.bicepparam
      - run: az acr build -r $ACR -t api:${{ github.sha }} ./api
      - run: az containerapp update -g rg-capstone-dev -n ca-api --image $ACR.azurecr.io/api:${{ github.sha }}
      - run: curl -fsS --retry 5 --retry-delay 10 https://$API_FQDN/healthz

Quick reference

  • Preview: az deployment group what-if -g RG -f infra/main.bicep -p infra/dev.bicepparam
  • Federated subject for an environment: repo:ORG/REPO:environment:ENV
  • Workflow needs permissions id-token: write for OIDC sign-in.
  • Deploy identity: Contributor + conditioned Role Based Access Control Administrator on one resource group.
  • App identity selection: set AZURE_CLIENT_ID to the user-assigned identity's client ID.
  • Storage defaults: allowSharedKeyAccess false, minimumTlsVersion TLS1_2; registry adminUserEnabled false.
  • Tag images with the commit SHA, never only latest, so rollback has a target.
  • Role assignments can take a few minutes to apply; retry before you debug a 403.

Common mistakes

  • Giving the deploy identity Owner on the subscription because role assignments failed with Contributor.
  • Using the registry admin user or a storage key in app settings instead of the managed identities.
  • Starting the app before its role assignments have propagated and treating the first 403 as a bug.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1The azure/login step fails with an error saying no matching federated identity record was found. What is the most likely cause?

Question 2

2Why tag images with the commit SHA?

Question 3

3Which value belongs in a Container Apps secret rather than a plain variable?

Question 4

4How does Bicep know to create the storage account before the container app?

Question 5

5You added a role in the Portal that Bicep also defines. What should you do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Do one core operation in the Portal and then with the CLI: assign Storage Blob Data Reader on the uploads container to id-worker. Show that both produce the same assignment, then remove the manual one.

  2. Exercise 2medium

    Write storage.bicep with a StorageV2 LRS account, shared keys off, the uploads and results containers, the jobs queue, and outputs for the blob endpoint and account name.

  3. Exercise 3hard

    Deploy the full stack from the pipeline, then prove least privilege: list every role assignment in the resource group and show it matches your design table with nothing extra.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why a managed identity for GitHub instead of an app registration?
Both can hold federated credentials. A user-assigned managed identity is an Azure resource you can manage with Bicep and RBAC, and it needs no Entra app admin rights. An app registration also works.
Can I use Azure Pipelines instead of GitHub Actions?
Yes. Create an Azure Resource Manager service connection that uses workload identity federation, and keep the same Bicep and CLI steps.
Should I use Terraform instead of Bicep?
Either works. The capstone uses Bicep because it needs no state file and maps directly to Azure Resource Manager. Terraform suits teams that manage several clouds.
Why does my app get 403 right after deploying?
New role assignments can take a few minutes to take effect. Wait and retry; if it persists, check the role, scope and that AZURE_CLIENT_ID matches the identity that holds the role.

Go deeper

ShareXLinkedInWhatsApp