CI/CD on Azure · Part 7 of 7
Automating the release to production
Taking the human out of the mechanical steps, not out of the decision: an OIDC identity dedicated to prod, a custom Azure role, a one-click promotion workflow, and rollback without a rebuild.
- GitHub Actions
- OIDC
- Azure RBAC
Where we are
Article 6 put production online by hand: we identified the sha-<hash> image validated in staging, marked it v0.1.0 on the Git side and on the ACR side, extracted its static files, then published them to Static Web Apps with the SWA CLI. A good ten commands, two shells, and a deployment token handled by hand.
In this article, we are going to turn that sequence into a GitHub Actions workflow. The goal is not to take the human out of the release to production, but to take the mechanical steps away from them and leave them only the decision. In practice, a release to production will come down to two actions:
- set an annotated Git tag on the commit to promote
- run the workflow with that tag as a parameter
Everything else (checks, ACR tag, extraction, deployment, final check) will be handled automatically.
Step 1: an identity dedicated to production
We could reuse the staging service principal, adding a second federated credential and a few roles to it. I prefer a separate identity, for a simple reason: if the staging identity is ever compromised or misconfigured, production must not go down with it. Two pipelines, two identities, two scopes of rights that only overlap on the bare minimum.
Working variables
$rg = "rg-westbalidrivers"
$acr_name = "acrwestbalidrivers"
$swa_name = "swa-westbalidrivers-prod"
$app_name = "gh-actions-westbalidrivers-prod"App registration and service principal
$ghProdApp = New-AzADApplication -DisplayName $app_name
$ghProdSp = New-AzADServicePrincipal -ApplicationId $ghProdApp.AppId
# Client ID (will go into the GitHub secrets)
$ghProdApp.AppIdThe federated credential, restricted to main
Same mechanics as in article 5, with the immutable subject format enforced by GitHub since July 2026. We get the numeric identifiers of the repository and of its owner through the GitHub API, still with a PAT limited to the “Metadata: Read-only” permission on this repository only:
$headers = @{
Authorization = "Bearer $GITHUB_TOKEN"
Accept = "application/vnd.github+json"
}
$repo = Invoke-RestMethod -Uri "https://api.github.com/repos/lolecat/WestBaliDrivers" -Headers $headers
New-AzADAppFederatedCredential `
-ApplicationObjectId $ghProdApp.Id `
-Name "github-main-branch" `
-Issuer "https://token.actions.githubusercontent.com" `
-Subject "repo:lolecat@$($repo.owner.id)/WestBaliDrivers@$($repo.id):ref:refs/heads/main" `
-Audience "api://AzureADTokenExchange"For a workflow triggered by workflow_dispatch, the subject of the OIDC token reflects the branch the run was started from. Started from main, it matches. Started from staging or from a working branch, the token exchange fails with the AADSTS700213 error already met in article 5.
Step 2: RBAC
The production workflow needs to do exactly three things on the Azure side:
- read and push tags in ACR
- get the deployment token of the Static Web App
- read the properties of the Static Web App (its hostname, for the final check)
On the ACR side: “AcrPush”
The built-in AcrPush role is needed to set the “vx.x.x” tag, and it includes pull. No need for more: this service principal will neither be able to delete an image, nor change the registry configuration.
$acr_id = (Get-AzContainerRegistry -ResourceGroupName $rg -Name $acr_name).Id
New-AzRoleAssignment `
-ObjectId $ghProdSp.Id `
-RoleDefinitionName "AcrPush" `
-Scope $acr_idOn the Static Web App side: a custom role
This is where the principle of least privilege takes a bit more effort. The deployment token is obtained through the Microsoft.Web/staticSites/listSecrets/action action. The smallest built-in role that contains it is Website Contributor, which actually opens all of Microsoft.Web/* on its scope: changing the configuration, deleting the resource, and many other things our pipeline has no need for.
So we create a tailor-made role, limited to two actions. The method documented here is to start from an existing role, empty it, then fill it (actually no, the doc is out of date, we are starting to get used to it).
So we will do it a safe way, by going straight through a PUT on the ARM resource:
$subscription_id = (Get-AzContext).Subscription.Id
# Build the role GUID from the hash of its name + subscription
$md5 = [System.Security.Cryptography.MD5]::Create()
$role_id = [guid]::new($md5.ComputeHash(
[Text.Encoding]::UTF8.GetBytes("$subscription_id/swa-deployment-token-reader")))
$payload = @"
{
"properties": {
"roleName": "Static Web App Deployment Token Reader",
"description": "Reads a Static Web App and gets its deployment token",
"type": "CustomRole",
"permissions": [{
"actions": [
"Microsoft.Web/staticSites/read",
"Microsoft.Web/staticSites/listSecrets/action"
],
"notActions": [], "dataActions": [], "notDataActions": []
}],
"assignableScopes": [ "/subscriptions/$subscription_id/resourceGroups/$rg" ]
}
}
"@
$response = Invoke-AzRestMethod -Method PUT `
-Path "/subscriptions/$subscription_id/providers/Microsoft.Authorization/roleDefinitions/$($role_id)?api-version=2022-04-01" `
-Payload $payload
if ($response.StatusCode -notin @(200, 201)) {
throw "Failed ($($response.StatusCode)): $($response.Content)"
}
$response.StatusCodeA few details:
staticSites/readis not essential to get the token, but it lets the workflow read the hostname of the Static Web App for its final check, rather than hard-coding it.AssignableScopeslimits where this role can be (not “is”) assigned. Scoping it to the resource group keeps it from ever being used elsewhere in the subscription by accident.
We then assign it on the Static Web App:
$swa_id = (Get-AzStaticWebApp -ResourceGroupName $rg -Name $swa_name).Id
New-AzRoleAssignment `
-ObjectId $ghProdSp.Id `
-RoleDefinitionName "Static Web App Deployment Token Reader" `
-Scope $swa_idA freshly created custom role can take a few minutes to propagate. If
New-AzRoleAssignmentanswers that the role cannot be found right after it was created, just wait a little and run it again.
Summary of the project’s identities
| Identity | Used by | Rights |
|---|---|---|
id-westbalidrivers-staging (managed) | The Container App, at runtime | AcrPull on the ACR |
gh-actions-westbalidrivers | The staging workflow | AcrPush on the ACR, Container Apps Contributor on the Container App |
gh-actions-westbalidrivers-prod | The production workflow | AcrPush on the ACR, custom role on the Static Web App |
Step 3: the GitHub secret
A single new repository secret, in Settings → Secrets and variables → Actions:
| Name | Value |
|---|---|
| AZURE_PROD_CLIENT_ID | $ghProdApp.AppId |
AZURE_TENANT_ID and AZURE_SUBSCRIPTION_ID have existed since article 5 and are reused as is. As for staging, this “secret” is not really one: it is a public identifier. Its only point in the GitHub secrets is to avoid hard-coding it in the YAML.
And that’s it. No Mapbox token (we build nothing), no Static Web Apps token (we get it at runtime).
Step 4: the production workflow
# .github/workflows/production.yml
name: Promote to production
on:
workflow_dispatch:
inputs:
version:
description: "Git tag to promote (e.g.: v0.2.0)"
required: true
type: string
permissions:
id-token: write # OIDC exchange with Entra ID
contents: read # read only: the Git tag is set by a human
env:
VERSION: ${{ inputs.version }}
IMAGE: acrwestbalidrivers.azurecr.io/westbalidrivers
RESOURCE_GROUP: rg-westbalidrivers
SWA_NAME: swa-westbalidrivers-prod
SWA_CLI_VERSION: "2.0.10" # pinned version, never "latest"
jobs:
promote:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # required to fetch the tags
- name: Resolve tag to commit
run: |
commit=$(git rev-parse "refs/tags/${VERSION}^{commit}")
echo "SHORT_SHA=${commit::7}" >> "$GITHUB_ENV"
- name: Azure login (OIDC)
uses: azure/login@v2
with:
client-id: ${{ secrets.AZURE_PROD_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: Authenticate Docker against ACR
uses: azure/powershell@v2
with:
inlineScript: Connect-AzContainerRegistry -Name "acrwestbalidrivers"
azPSVersion: "latest"
- name: Tag image for production
run: |
if docker manifest inspect "${IMAGE}:${VERSION}" > /dev/null 2>&1; then
echo "${VERSION} already exists in ACR: redeploy or rollback, no retag."
else
# Fails if the sha-* image does not exist: the commit never went through staging
docker pull "${IMAGE}:sha-${SHORT_SHA}"
docker tag "${IMAGE}:sha-${SHORT_SHA}" "${IMAGE}:${VERSION}"
docker push "${IMAGE}:${VERSION}"
fi
- name: Extract static files
run: |
docker create --name swa-extract "${IMAGE}:${VERSION}"
docker cp swa-extract:/usr/share/nginx/html ./release
docker rm swa-extract
cp deploy/swa/staticwebapp.config.json ./release/
- name: Deploy to Static Web Apps
uses: azure/powershell@v2
with:
inlineScript: |
$secret = Get-AzStaticWebAppSecret -ResourceGroupName $env:RESOURCE_GROUP -Name $env:SWA_NAME
$env:SWA_CLI_DEPLOYMENT_TOKEN = ($secret.Property | ConvertFrom-Json).apiKey
Write-Output "::add-mask::$($env:SWA_CLI_DEPLOYMENT_TOKEN)"
npx -y "@azure/static-web-apps-cli@$($env:SWA_CLI_VERSION)" deploy "$env:GITHUB_WORKSPACE/release" --env production
if ($LASTEXITCODE -ne 0) { throw "Deployment to Static Web Apps failed." }
$hostname = (Get-AzStaticWebApp -ResourceGroupName $env:RESOURCE_GROUP -Name $env:SWA_NAME).DefaultHostname
"SWA_HOSTNAME=$hostname" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8
azPSVersion: "latest"
- name: Smoke test
run: curl -sf --retry 5 --retry-delay 5 --retry-all-errors "https://${SWA_HOSTNAME}/" > /dev/nullThe workflow follows, in order, the manual sequence of article 6. Several choices deserve a few words.
“workflow_dispatch” and the version parameter
The workflow never triggers on its own: it has to be started from the Actions tab of the repository (Run workflow button), choosing the main branch and typing in the version. This is the human approval gate described above.
Why not trigger the workflow on the push of a v* tag instead, which would save a click? Because the OIDC subject would then become ref:refs/tags/v0.2.0, different for every version. And a federated credential compares its subject strictly literally, with no wildcard: we would have to create a new one for every release to production. Triggering manually from main keeps a stable subject.
“${commit::7}” rather than “git rev-parse –short”
The staging workflow tags its images with ${GITHUB_SHA::7}, that is always exactly 7 characters. git rev-parse --short, for its part, can return more if 7 characters are not enough to identify a commit unambiguously in the repository. The day that happens, the safeguard would look for sha-95ab7cf3 instead of sha-95ab7cf, and would wrongly reject a perfectly valid image. Both workflows must compute this short hash exactly the same way.
The deployment token never leaves its step
The Static Web Apps token is fetched, used and forgotten within a single PowerShell step. It is placed in an environment variable of the current process, which the SWA CLI reads directly, and is never written to $GITHUB_ENV, which would have exposed it to all the following steps. The ::add-mask:: asks GitHub to replace it with *** in the logs, in case some tool takes it into its head to print it.
The SWA CLI is called through npx with a pinned version. An npx -y @azure/static-web-apps-cli with no version would download the latest one published on npm at the time of the run, that is unverified third-party code, running with a production deployment token in memory. It is the same logic as the --frozen-lockfile of article 2: we only run what we chose to run.
Step 5: first automated promotion
Putting the workflow in place
A workflow_dispatch only shows up in the GitHub interface if the workflow file exists on the default branch of the repository, here main.
The production.yml file then follows the same path as any other change: committed to staging, validated by the staging pipeline, then merged into main.
git checkout staging
git add -A
git commit -m "Add production workflow"
git push origin stagingOnce the staging workflow has turned green and the staging site has been checked:
git checkout main
git merge --ff-only staging
git push origin mainSetting the version tag
The commit to promote is the last commit of staging, the one whose image has just been built and validated:
git fetch origin staging
git tag -a v0.2.0 origin/staging -m "test prod workflow"
git push origin v0.2.0Pushing a tag triggers nothing: no workflow listens to tags. The tag is set, but nothing is deployed yet.
Running the workflow
From the Actions tab: Promote to production → Run workflow → main branch → version v0.2.0.
Testing the rollback
From the Actions tab: Promote to production → Run workflow → main branch → version v0.1.0.
No tag is created, the artifact is extracted, then redeployed. The production site goes back to the article 6 version, with the current hosting configuration.
We then run the workflow again with v0.2.0 to get back to the latest version. A rollback, then a “roll-forward”, without any build: that is exactly the promise of build once, deploy many made in article 6.
What this chapter changed
A release to production, in article 6, meant about ten commands, two shells and a secret handled by hand. It is now:
git tag -a v0.3.0 origin/staging -m "..."
git push origin v0.3.0
gh workflow run production.yml --ref main -f version=v0.3.0And behind these three lines, the workflow checks that the commit did go through staging, refuses to rewrite a version tag, deploys the artifact, stores no secret and checks the result. Rollback is the same command with a previous version number.
The full pipeline now looks like this:
Local workstation (dev)
│
▼
staging branch ──push──→ staging.yml
│ ├── docker build (runner)
│ ├── push to ACR: staging + sha-<hash>
│ └── new Container App revision
│
▼
main branch ──── annotated Git tag vX.Y.Z (by hand)
│
▼
production.yml (workflow_dispatch, by hand)
├── ACR tag vX.Y.Z (same digest, never moved)
├── file extraction
├── adding the staticwebapp.config.json file (from main)
├── Static Web Apps deployment
└── smoke testChecklist before moving on
- The
gh-actions-westbalidrivers-prodapp registration exists, with its service principal - Its federated credential is scoped to
refs/heads/main, in the immutable subject format - The custom role
Static Web App Deployment Token Readerexists, scoped to the resource group, and contains only two actions - The production service principal has
AcrPushon the ACR and the custom role on the Static Web App, and nothing else - The
AZURE_PROD_CLIENT_IDsecret is set in GitHub -
production.ymlis present onmain, with a pinned version of the SWA CLI - Promoting
v0.2.0turns fully green, and the run summary shows the right digest -
v0.2.0and the matchingsha-<hash>share the same digest in ACR - Rolling back to
v0.1.0then returning tov0.2.0works without any build - The Mapbox map works in production after the automated promotion
Next
The chain is complete: from the local workstation to production, every step is either automated or an explicit, traced human decision. One last piece of work remains before the final touches: the custom domain, which will finally let us remove the temporary X-Robots-Tag: noindex and open the site to search engines. That will be the subject of the next chapter.