Cloud / IaC · Enterprise

Azure Container Registry Onboarding Automation with Terraform and GitHub Actions

A workflow that creates a registry per customer or team, grants least-privilege pull and push roles to the right identities, and supports dedicated registry builds for specific product lines.

  • Azure Container Registry
  • Terraform
  • GitHub Actions
  • Azure RBAC
  • AKS
  • OIDC
  • Private endpoints
  • Vault

// Why this matters

Azure container registry terraform automation is one of those platform chores that looks trivial until you do it for the fortieth time. A registry needs a name that is globally unique, the right SKU, network rules, diagnostic settings, identities that can pull, identities that can push and a way for CI to authenticate. Done by hand, every registry differs slightly, and the differences are where access incidents come from.

Teams and customers have different needs: a shared registry is cheaper but blurs ownership; a dedicated registry gives clean isolation, separate retention and separate network rules, at the cost of more of them to manage. Automation removes that cost, which means the decision can follow the requirement instead of the effort.

The security win is mostly negative space: no admin user, no shared pull secrets copied between namespaces, no personal access scoped to the whole registry. Every grant is a role assignment on a specific identity, visible in code.

// The problem

The default way to use a registry is to enable the admin account and share the username and password. It works immediately, which is why it is everywhere, and it means nobody can tell who pushed an image, nothing expires and revoking access breaks every consumer at once.

Naming is another constraint: registry names are global, alphanumeric only, 5 to 50 characters. Without validation, a workflow that fails halfway through leaves a half-configured resource group and a confusing error.

Finally, runtime access has to be wired per cluster. A cluster that cannot pull gives you ImagePullBackOff at 2am; a cluster that can pull from every registry gives you a lateral-movement path. Both are configuration problems that belong in code.

// The solution

The solution is a Terraform module and a thin workflow. The module takes a name, SKU, a list of pull principals, a list of push principals, an optional private endpoint subnet and a retention setting, and returns the login server and the registry id. It always sets admin_enabled = false, always enables diagnostic logs to a central workspace and always assigns roles at the registry scope.

The workflow is triggered by workflow_dispatch with inputs (registry name, tier, owner group, whether it needs a private endpoint). A validation step enforces the name rules and checks uniqueness with az acr check-name. A plan job produces the plan, the apply job is bound to a protected environment so required reviewers act as the approval gate, and the final job runs a smoke test that pushes and pulls a tiny image using the new federated identity. This is the same pattern used in One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling and Subscription Factory: Customer Onboarding That Starts by Minting Subscriptions.

Authentication is identity-first. Clusters pull using the kubelet managed identity with AcrPull assigned at the registry scope, which avoids image pull secrets entirely. CI pushes using OIDC: an app registration (or user-assigned managed identity) has a federated credential bound to a specific repository and branch or environment, and holds AcrPush. No secret is stored; see The App Registration Factory That Cannot Hold a Secret for generating those identities.

Dedicated registries for particular product lines use the same module with different inputs, which was the deciding factor against writing a second, special-case workflow. We rejected a single shared registry with repository-scoped tokens (token sprawl and expiry management) and per-team ad hoc scripts (inconsistent, untested).

How it flows flow1. Request → 2. Validate → 3. Plan → 4. Gate: approval → 5. Create → 6. Assign roles → 7. Federate → 8. Publish outputs → 9. Smoke test01Request02Validate03Plan04 · GATEGate: approval05Create06Assign roles07Federate08Publish outputs09Smoke test
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Requestworkflow dispatch with registry name, tier, owner group
  2. Validatenaming rules and uniqueness
  3. PlanTerraform plan for the registry module
  4. Gate: approval gateprotected environment for apply
  5. Createregistry, private endpoint, diagnostics
  6. Assign rolesAcrPull to cluster identity, AcrPush to build identity
  7. FederateOIDC credential for the repository pipeline
  8. Publish outputslogin server and role map to the config store
  9. Smoke testpush and pull a test image
RequesterWorkflowTerraformAzureSmoke testdispatch name, tier, owner groupcheck-name uniquenessplan registry moduleapprove apply (protected environment)registry, endpoint, diagnostics, role assignmentspush and pull test image with federated identity
Onboarding run. From dispatch to a working, tested registry.
ConsumersAKS kubelet identityCI federated identityOperator groupRolesAcrPullAcrPushReaderRegistryPremium or Standard SKUPrivate endpointRetention policyObservabilityDiagnostic logsCentral workspace
Registry access model. Every consumer is an identity with exactly one role.

// Before you start

  • An Azure subscription where you can create resource groups, registries and role assignments (Owner or User Access Administrator on the target scope).
  • Terraform 1.5+ with the azurerm provider 3.x or 4.x and a remote state backend.
  • A GitHub repository with environments configured and OIDC federation to Azure set up for the pipeline.
  • An AKS cluster (or several) whose kubelet identity object id you can look up.
  • Optionally a spoke subnet and private DNS zone privatelink.azurecr.io for private endpoints.
  • A Log Analytics workspace for diagnostics.

// Step-by-step implementation

  1. 01 Write the registry module

    The module is the whole standard in one file. Admin disabled, public access controlled by an input, retention policy where the SKU supports it, and a diagnostics setting on every registry.

    Use a random_string only if you need to avoid collisions; a deterministic name from the request is better because the same request must map to the same resource.

  2. 02 Add an optional private endpoint

    For registries that must not be reachable from the internet, add a private endpoint in a spoke subnet and register it in the privatelink.azurecr.io zone. This requires the Premium SKU. Make it a conditional resource so the same module serves both modes.

    Remember that CI runners then need network reach to the endpoint, which is why many platforms run self-hosted runners in the same network.

  3. 03 Create the federated CI identity

    A user-assigned managed identity with a federated credential is the simplest secret-free CI identity. The subject claim ties it to one repository and environment, so a fork or another branch cannot use it.

    Pass its principal id into the module as a push principal. The pipeline then logs in with OIDC and runs az acr login.

  4. 04 Validate the request before Terraform runs

    Fail early with a message a human can act on. Registry names are lowercase alphanumeric, 5 to 50 characters and globally unique; checking this takes seconds and saves a failed apply with a half-built resource group.

    Treat workflow inputs as untrusted: they flow into commands, so pass them through environment variables instead of interpolating them into shell.

  5. 05 Wire the workflow: plan, approve, apply, smoke test

    Use workflow_dispatch with typed inputs. The apply job references a protected environment so required reviewers approve it; the smoke job proves the happy path rather than trusting that Terraform exit code zero means pulls work.

    Use OIDC login (azure/login with client, tenant and subscription ids as variables) instead of stored credentials.

  6. 06 Smoke test pull and push, and attach the cluster

    The final job pushes a tiny image with the CI identity and pulls it from a pod running as the cluster identity. A pull that fails here fails the onboarding, not a production deployment later.

    If the cluster was created before the registry, attach it with az aks update --attach-acr, or rely on the Terraform role assignment shown earlier; do not do both.

// How to verify it works

  • az acr show -n <registry> --query adminUserEnabled returns false.
  • az role assignment list --scope <registry-id> -o table lists exactly the pull and push principals from the request.
  • The smoke pod reaches Succeeded without any imagePullSecret configured.
  • A push from a branch other than the one in the federated subject is rejected at login.
  • Diagnostic events for the push appear in the central workspace within a few minutes.

// Design decisions and trade-offs

  • One workflow input record produces the registry, role assignments and pull identity; no portal clicks.
  • Roles are assigned to groups or workload identities, with AcrPull for runtime and AcrPush only for the build identity.
  • Admin user is disabled; CI authenticates with OIDC federation, and clusters pull with their kubelet identity.
  • Dedicated registries for product lines are the same module with different inputs, not a fork.
  • Idempotent by name: re-running the workflow for an existing registry is a no-op plan.

// Pitfalls and lessons learned

  • Role assignments can take a minute or more to propagate; a smoke test that runs immediately may fail once. Retry with backoff before declaring failure.
  • Private endpoints require the Premium SKU; Terraform will accept the plan for Standard and fail at apply.
  • Registry names are global and case-insensitive; a name taken in another tenant looks identical to a typo.
  • Using both attach-acr and Terraform role assignments produces duplicate-assignment errors.
  • A federated credential subject must match exactly (environment versus branch format differ); mismatches show up as generic AADSTS errors.
  • Retention policies and quarantine need Premium; do not promise image cleanup on Standard.
  • Granting AcrPush to a human group for convenience reintroduces the shared-credential problem under a new name.

// Frequently asked questions

How do I give AKS access to Azure Container Registry with Terraform?

Assign the AcrPull role to the cluster kubelet identity at the registry scope using azurerm_role_assignment.

Should I use the ACR admin user?

No. It is a shared credential with no per-user audit and no scoping; use role assignments and OIDC federation instead.

How do I push to ACR from GitHub Actions without secrets?

Create a managed identity or app registration with a federated credential for your repository and grant it AcrPush, then use azure/login with OIDC.

One registry per team or one shared registry?

Per team or product line gives clean isolation and permissions; with automation, the extra registries cost little.

Can I automate registry deletion too?

Yes, but gate it and confirm no clusters still reference it; see the ordered approach in the offboarding post.

// The outcome

Registries appear with consistent naming, networking and permissions from a single reviewed run, and access follows identity rather than shared credentials. Onboarding a new team or product line stops being a bespoke task.

// Where to take it next

// Keep reading