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

📚 Interview question

Write a GitHub Actions workflow for a .NET 10 API that builds, tests, publishes a container image and deploys it to Azure. How do you authenticate to Azure with OIDC instead of a stored secret, and how do you gate production?

A GitHub Actions workflow for a .NET 10 API: restore, build, test, container publish to ACR, OIDC login to Azure, environment approvals and deployment to Container Apps or App Service.

Intermediate Coding Intermediate azure ci-cd containers devops github-actions oidc

🎯 Key points

  • permissions: id-token: write lets the job request a GitHub OIDC token
  • azure/login with client-id, tenant-id and subscription-id, no client secret
  • Federated credential subject (e.g. repo:org/repo:environment:production) decides which jobs can get tokens
  • Tests run before any push; TRX results uploaded as an artefact with if: always() so failures stay inspectable
  • One immutable image tagged with the commit SHA is the only artefact promoted to every environment
  • dotnet publish -t:PublishContainer builds an image without a Dockerfile
  • GitHub environments with required reviewers gate the production job; concurrency stops overlapping deploys
  • Least-privilege GITHUB_TOKEN permissions and actions pinned to a version or SHA

⏱ 30-second answer

The workflow has a build job (restore, build, test, dotnet publish /t:PublishContainer to push an image tagged with the commit SHA to Azure Container Registry) and deploy jobs per environment that reuse that same image.

For Azure access I use OpenID Connect: the job declares permissions: id-token: write, GitHub issues a short-lived token, and azure/login exchanges it for an Entra token through a federated credential on an app registration or user-assigned managed identity. No client secret is stored anywhere.

Production is gated with a GitHub environment that has required reviewers, and the federated credential's subject is scoped to environment:production, so only an approved job can get production access.

The trade-off: OIDC needs one-off Entra setup per repo and environment, but removes secret rotation and leaked-secret risk entirely.

🗣 Full answer (senior)

How I would answer this in an interview

"I split the workflow into a build job and one deploy job per environment. The build job checks out the code, sets up the .NET 10 SDK from global.json, restores with a NuGet cache, builds in Release, runs the tests and uploads the results, then uses the SDK's container support (dotnet publish /t:PublishContainer) to push an image to Azure Container Registry, tagged with the commit SHA. That image is the artefact: I build it once and promote the same bytes to test and production.

For Azure I don't store a service principal secret. The job asks for id-token: write, GitHub's OIDC provider issues a signed token with claims like repo:contoso/orders-api:environment:production, and azure/login swaps it for an Entra access token through a federated credential configured on a user-assigned managed identity. That identity only has AcrPush on the registry and Contributor on the one Container App, nothing at subscription level. The production deploy job targets a GitHub environment called production with required reviewers, and because the federated credential's subject names that environment, a job that skipped the approval simply can't log in.

The mistake I see is pasting AZURE_CREDENTIALS JSON with a client secret into repo secrets, which then lives for two years, gets copied to five repos and has Owner on the subscription. The second is rebuilding the app in each stage, so what you deploy to production isn't what you tested. Build once, deploy many, and let the identity, not a secret, carry the trust."


Workflow shape

Job Trigger Does Identity
build PR and push to main restore, build, test, publish image (push only on main) OIDC → AcrPush
deploy-test after build on main update Container App revision with sha-<commit> OIDC, subject environment:test
deploy-prod after deploy-test same image, after approval OIDC, subject environment:production

OIDC setup (one-off)

  1. Create a user-assigned managed identity (or Entra app registration).
  2. Add a federated credential: issuer https://token.actions.githubusercontent.com, audience api://AzureADTokenExchange, subject repo:<org>/<repo>:environment:production.
  3. Assign narrow roles: AcrPush on the registry, Contributor (or a custom role) on the target resource only.
  4. Store AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_SUBSCRIPTION_ID as variables; they are identifiers, not secrets.

Gating production

  • Environment protection rules: required reviewers, wait timer, and deployment branches limited to main.
  • concurrency: production so two deployments never overlap.
  • Smoke test against /health/ready after deploy, failing the job (and triggering rollback to the previous revision) if it doesn't return 200.

Production example

Moving a team of six repos from a shared client secret to OIDC removed the yearly secret rotation that had caused two failed releases when the secret expired. The pipeline runs in about 7 minutes (restore from cache 20 s, tests 3 min, image push 1 min), and production deploys need one approval from the on-call lead.

🔍 What the interviewer is checking

Checks whether the candidate can write a realistic pipeline and, more importantly, secures it: no stored secrets, least privilege, approval gates and a single promoted artefact.

Green flags

  • Uses id-token: write and azure/login with OIDC, explains the federated subject
  • Builds one image tagged with the commit SHA and promotes it
  • Uses environments with required reviewers and concurrency
  • Mentions least-privilege permissions and action pinning
  • Adds a smoke test after deploy

Red flags

  • Stores a client secret or publish profile in repo secrets without question
  • Rebuilds per environment or deploys latest
  • No tests gate before the image is pushed

📚 Learn in depth

1. How GitHub OIDC federation works

GitHub runner                      GitHub OIDC provider              Microsoft Entra ID
     │  request token (aud=api://AzureADTokenExchange)  │                    │
     │ ───────────────────────────────────────────────► │                    │
     │ ◄─────────── signed JWT (iss, sub, aud, repo, ref, environment) ─────│
     │                                                                       │
     │  client assertion = GitHub JWT, client_id = managed identity           │
     │ ─────────────────────────────────────────────────────────────────────►│
     │                 Entra validates iss + sub + aud against the federated  │
     │                 credential, then issues an access token (~1 hour)      │
     │ ◄─────────────────────────────────────────────────────────────────────│

2. Scoping the subject (what "scoped to the environment" means)

The sub claim GitHub puts in the token depends on what triggered the job. Entra only issues a token if sub exactly matches a federated credential (or matches a flexible-expression rule if you use one).

Trigger sub claim
Job that declares environment: production repo:contoso/orders-api:environment:production
Push to a branch (no environment) repo:contoso/orders-api:ref:refs/heads/main
Pull request repo:contoso/orders-api:pull_request
Tag push repo:contoso/orders-api:ref:refs/tags/v1.4.0

In practice:

  1. Create one identity per environment (id-orders-gh-test, id-orders-gh-prod) with roles only on that environment's resource group.
  2. On the prod identity, add exactly one federated credential: subject repo:contoso/orders-api:environment:production.
  3. In GitHub, protect the production environment with required reviewers and "deployment branches: main only".

Now a PR job (sub = ...:pull_request) or a feature-branch job can't get a prod token, and a job that names environment: production can't start until a reviewer approves. If you instead trusted ref:refs/heads/main, any workflow file on main (including one added later for an unrelated purpose) could deploy to prod without an approval. Org admins can also customise the subject template (for example to include job_workflow_ref) to pin the trust to one reusable workflow.

3. Build once, promote many: managing artefacts

PR / push ─► restore (locked) ─► build ─► test ──► upload TRX + coverage (always)
                                           │
                                    tests pass AND ref == main?
                                           │ yes
                                           ▼
                         dotnet publish -t:PublishContainer ─► ACR: orders-api:sha-3f2c1ab
                                           │   (digest recorded as a job output)
                         deploy-test ──► deploy-prod (same digest)
  • Test results are uploaded with actions/upload-artifact and if: always(); a reporter action or the job summary shows failures in the PR. Artefacts are kept for the repo's retention period (90 days by default, configurable).
  • The deployable artefact is the image in ACR, not a workflow artefact. Record its digest (sha256:...) as a job output and deploy by digest if you want to rule out tag overwrites; enable ACR tag locking or immutability for release tags.
  • For non-container apps, upload the dotnet publish output once with upload-artifact and download it in each deploy job.

4. Container images without a Dockerfile

Since .NET 8 the SDK can build OCI images: dotnet publish -t:PublishContainer reads properties such as ContainerRepository, ContainerImageTags and ContainerFamily (for example noble-chiseled for a small, non-root Ubuntu image). It needs no Docker daemon to push to a registry. Use a Dockerfile when you need OS packages or custom layers.

5. Speed

Technique Effect
actions/setup-dotnet with cache: true + packages.lock.json Restore from cache in seconds
--no-restore / --no-build on later steps Avoid repeated work
Split tests across a matrix Shorter wall clock for big suites
paths filters Skip CI for docs-only changes

6. Security hardening

  • Set top-level permissions: contents: read and grant id-token: write only to jobs that log in.
  • Pin third-party actions to a full commit SHA (supply chain risk); Dependabot can update the pins.
  • Never run deploy jobs for pull_request_target or forks.
  • Use environment secrets/variables so production values are only visible to approved jobs.

7. Deploying

For Container Apps, deploy a new revision with az containerapp update --image; with multiple-revision mode you can shift traffic gradually. For App Service, deploy to a staging slot and swap. In both, the app pulls from ACR using its own managed identity with AcrPull, not admin credentials.

Try it yourself

  1. Create a user-assigned managed identity and a federated credential for environment:test in a test subscription; run azure/login and az account show.
  2. Run the same login from a job without environment: test and read the AADSTS700213 (no matching federated identity) error.
  3. Add <ContainerRepository>orders-api</ContainerRepository> to a project and run dotnet publish -t:PublishContainer locally; inspect the image with docker image inspect.
  4. Add an environment with a required reviewer and watch the deploy job pause.
  5. Break a test on purpose and confirm the TRX artefact is uploaded and no image is pushed.

💻 Code

The workflow (.github/workflows/orders-api.yml):

name: orders-api

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read            # least privilege by default

env:
  IMAGE: orders-api
  REGISTRY: contosoacr.azurecr.io

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write       # needed for OIDC login (push to ACR)
      checks: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          global-json-file: global.json
          cache: true
          cache-dependency-path: '**/packages.lock.json'
      - run: dotnet restore --locked-mode
      - run: dotnet build -c Release --no-restore
      - run: dotnet test -c Release --no-build --logger trx --results-directory TestResults
      - uses: actions/upload-artifact@v4
        if: always()
        with: { name: test-results, path: TestResults }

      - name: Azure login (OIDC, no secret)
        if: github.ref == 'refs/heads/main'
        uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Publish image to ACR
        if: github.ref == 'refs/heads/main'
        run: |
          az acr login --name contosoacr
          dotnet publish src/Orders.Api -c Release -t:PublishContainer \
            -p:ContainerRegistry=$REGISTRY \
            -p:ContainerRepository=$IMAGE \
            -p:ContainerImageTags=sha-${{ github.sha }}

  deploy-prod:
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment: production   # required reviewers + subject scoped to this environment
    concurrency: production   # never two prod deploys at once
    permissions:
      id-token: write
    steps:
      - uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      - name: Deploy new revision (same image that was tested)
        run: |
          az containerapp update -g rg-orders-prod-aue -n orders-api \
            --image $REGISTRY/$IMAGE:sha-${{ github.sha }}
      - name: Smoke test
        run: curl --fail --retry 10 --retry-delay 6 https://orders.contoso.com.au/health/ready

The readiness endpoint the smoke test calls (Program.cs):

using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHealthChecks()
    // Tagged "ready": only checked by the readiness endpoint, not liveness.
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["ready"]);

var app = builder.Build();

app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = r => r.Tags.Contains("ready") });
app.MapGet("/orders/{id:int}", (int id) => Results.Ok(new OrderDto(id, "Shipped")));

app.Run();

public sealed record OrderDto(int Id, string Status);

⚠ Common mistakes

  • Mistake: Storing a service principal client secret (AZURE_CREDENTIALS) in repo secrets. Why it is wrong: It is long-lived and copyable: anyone who can edit a workflow can exfiltrate it, it gets reused across repos, and if it leaks (logs, a forked workflow, a compromised action) an attacker has that identity's Azure access until someone notices and rotates it. Instead: Use OIDC with a federated credential; tokens last about an hour and are only issued to jobs matching the subject.
  • Mistake: Giving the pipeline identity Owner or Contributor on the whole subscription. Why it is wrong: A compromised workflow can delete or read everything. Instead: Grant AcrPush and a role on the specific resource group or app only.
  • Mistake: Scoping the federated credential to pull_request, or using a wildcard-style trust for any branch, for production. Why it is wrong: Unreviewed code (even a PR branch) could get production tokens. Instead: Scope the subject to environment:production with required reviewers and deployment branches limited to main.
  • Mistake: Rebuilding the app in each deploy job. Why it is wrong: Production runs bytes nobody tested. Instead: Build one image tagged with the SHA and promote it.
  • Mistake: Tagging images only as latest. Why it is wrong: You can't tell what's running or roll back to a known version. Instead: Tag with the commit SHA (and a version tag on release).
  • Mistake: Uploading test results only on success. Why it is wrong: The results you need most (failures) disappear with the runner. Instead: Upload TRX with if: always() and publish a test report.
  • Mistake: Leaving the default broad GITHUB_TOKEN permissions. Why it is wrong: Any compromised step can write to the repo. Instead: Set permissions: contents: read at the top and widen per job.
  • Mistake: Using third-party actions by floating tag only. Why it is wrong: A moved tag can inject code into your build. Instead: Pin to a commit SHA and update via Dependabot.
  • Mistake: No post-deploy check. Why it is wrong: A broken release looks "green" in the pipeline. Instead: Run a smoke test and fail (and roll back) if it fails.

🏛 Senior insight: trade-offs

The two ideas that matter most are identity instead of secrets and build once, deploy many. OIDC moves trust from a string you must protect to a policy you can read: this repo, this environment, this audience. It also maps cleanly onto ACSC Essential Eight thinking about restricting administrative privileges, because the pipeline identity has only what it needs, only when an approved job runs.

I keep workflows boring: reusable workflows (workflow_call) for the shared build, a thin per-repo file, and deployment logic that is the same command a human would run. Measure the pipeline like a product: duration, failure rate, flaky test count and lead time from merge to production.

Option When it fits Cost When not to
OIDC + federated credential Any GitHub → Azure deployment One-off Entra setup per repo/environment Never worse than a secret
Client secret in repo secrets Legacy, tools without OIDC support Rotation, leak risk New pipelines
Self-hosted runner with managed identity Private network targets Runner patching and isolation When a hosted runner + private endpoint or OIDC is enough
Reusable workflow Many similar services Versioning the shared workflow One-off repo

🔗 Follow-ups the interviewer may ask

  1. When: Candidate writes the build and test steps quickly. Why: Checks whether the candidate can critique the build and test stages, not just write them.
    How to answer

    The pipeline restores three times, builds in Debug, runs dotnet format in a way that silently fixes files instead of failing, and publishes from a different build than the one it tested. I'd use global.json for the SDK, restore once with --locked-mode, build once in Release with --no-restore, then test and publish with --no-build. I'd run dotnet format --verify-no-changes so formatting drift fails the build, collect test results and coverage, and cache the NuGet folder.

  2. When: Candidate deploys an API that uses EF Core. Why: Checks how the candidate fits database migrations into the same pipeline safely.
    How to answer

    I generate migrations locally with dotnet ef migrations add, then make deployment a separate, reviewed step. The pipeline produces an artefact: either an idempotent SQL script (dotnet ef migrations script --idempotent) for a DBA to review, or a migration bundle (dotnet ef migrations bundle), a self-contained executable that applies pending migrations. That artefact runs once, before the new app version starts, with a dedicated deployment identity. I avoid Database.Migrate() at startup because several instances can race, the app needs DDL permissions it shouldn't have, and a failed migration turns into a crash loop.

  3. When: Candidate uses dotnet publish -t:PublishContainer. Why: Checks understanding of the publish options behind the container step.
    How to answer

    By default dotnet publish gives a framework-dependent folder that needs the .NET runtime on the server. Self-contained (--self-contained -r linux-x64) bundles the runtime, so nothing needs installing, but the output is bigger and you patch the runtime by redeploying. On top of that: single-file packs everything into one executable, trimming removes unused code, ReadyToRun precompiles to speed up start-up, and Native AOT compiles to a native binary with very fast start-up and low memory but no dynamic code generation. The SDK can also build a container image directly. I choose based on where it runs, start-up and memory needs, and whether the libraries are trim- and AOT-safe, and I measure the result.

↩ Usually asked after

More in CI/CD

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me