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.
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.
"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 likerepo:contoso/orders-api:environment:production, andazure/loginswaps it for an Entra access token through a federated credential configured on a user-assigned managed identity. That identity only hasAcrPushon the registry and Contributor on the one Container App, nothing at subscription level. The production deploy job targets a GitHub environment calledproductionwith 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_CREDENTIALSJSON 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."
| 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 |
https://token.actions.githubusercontent.com, audience api://AzureADTokenExchange, subject repo:<org>/<repo>:environment:production.AcrPush on the registry, Contributor (or a custom role) on the target resource only.AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_SUBSCRIPTION_ID as variables; they are identifiers, not secrets.main.concurrency: production so two deployments never overlap./health/ready after deploy, failing the job (and triggering rollback to the previous revision) if it doesn't return 200.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.
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
id-token: write and azure/login with OIDC, explains the federated subjectconcurrencypermissions and action pinningRed flags
latestGitHub 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) │
│ ◄─────────────────────────────────────────────────────────────────────│
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:
id-orders-gh-test, id-orders-gh-prod) with roles only on that environment's resource group.repo:contoso/orders-api:environment:production.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.
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)
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).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.dotnet publish output once with upload-artifact and download it in each deploy job.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.
| 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 |
permissions: contents: read and grant id-token: write only to jobs that log in.pull_request_target or forks.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.
environment:test in a test subscription; run azure/login and az account show.environment: test and read the AADSTS700213 (no matching federated identity) error.<ContainerRepository>orders-api</ContainerRepository> to a project and run dotnet publish -t:PublishContainer locally; inspect the image with docker image inspect.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);
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.AcrPush and a role on the specific resource group or app only.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.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).if: always() and publish a test report.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.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 |
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.
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.
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.
Last updated 23 Nov 2026.