Inventory Existing ARM, Bicep and Terraform Ownership
An ownership register is the first artefact, not the HCL. Every resource group, vault and role assignment already has a declarer: a Bicep template, an ARM deployment, another Terraform root, a portal habit, or nobody. Import is a transfer between declarers, so name the current one before writing a resource block.
ARM records deployments, not ownership. A Bicep file compiles to an ARM template and converges the resources it names; the deployment history shows inputs, outputs and timings but does not claim the objects afterwards. Deleting that history changes nothing, and a successful template run is not evidence that Terraform may not also own the same object.
Complete mode is a competing declarer with delete rights. An ARM deployment in complete mode removes resources in its scope that the template does not declare. That is correct for a template that owns the entire resource group and destructive for one that shares it with Terraform, so read the mode before treating a template as documentation.
Deployment stacks are the exception that does record ownership. A stack tracks the resources it manages, can deny writes made outside the stack, and can delete managed resources when the stack itself is deleted. Where a stack exists, treat it as the current owner and do not import underneath it.
Terraform proves ownership through state. The address, backend key and workspace identify one declarer for one object; a matching tag proves nothing, because anyone with write access can set it. Two roots that both declare the same identifier produce two clean plans and a race in which the last apply wins.
Some objects should never be imported. Management-group policy assignments, shared hub networks and platform-owned DNS zones are usually better read through data sources and asserted with preconditions. Referencing them keeps the owning team's pipeline in charge and avoids a transfer you cannot complete.
Reads disagree, so collect more than one. Azure Resource Graph is fast but sees only control-plane resources; deployment history sees only template runs; Terraform state sees only what one root recorded. The register is trustworthy when those reads agree on the identifier and the declarer.
Table 1 sorts the readable signals by what they can actually prove.
| Signal | What it proves | Blind spot |
|---|---|---|
| ARM deployment history | A template ran at a scope with these parameters | Says nothing about objects the template later dropped |
| Deployment stack resource list | The stack currently manages these IDs | Only covers stacks, not plain deployments |
| Terraform state address | This root records this ID | One root per read; other roots stay invisible |
| Resource Graph query | The object exists in this tenant and scope | No declarer, and no proof of who maintains it |
| Resource tags | Someone chose these values | Any writer can change or copy them |
Figure 1 shows the decision that follows from that evidence.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Resource exists in the subscription"] --> B{"What record proves the declarer?"}
B -->|"template or deployment"| C["Bicep or ARM template"]
B -->|"state address"| D["A Terraform root"]
B -->|"stack resource list"| E["Deployment stack"]
B -->|"nothing"| F["Portal, script or orphan"]
C --> G{"Does the template own the whole scope?"}
G -->|"yes, complete mode"| H["Keep ARM as owner, reference only"]
G -->|"no, shares the scope"| I["Remove it from the template first"]
D --> J{"Same root and workspace?"}
J -->|"yes"| K["Change it here"]
J -->|"no"| L["Transfer through zero declarers"]
E --> M["Do not import underneath the stack"]
F --> N["Name an owner, then adopt or delete"]
I --> O["Register ARM ID, declarer and id shape"]
K --> O
L --> O
N --> O
H --> O
M --> O
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,B,G,J primary;
class C,D,E secondary;
class K,L,N,O ok;
class H,M warn;
class I secondary;
class F danger;
Figure 2 places the recorded declarers on one boundary and shows why the register, not the plan, decides ownership.
Import a Bounded Resource and Inspect Its Canonical ID
Bound the set before you bound the risk. One resource group, ten to twenty objects, and nothing whose replacement would lose data. A bounded import is reviewable in one sitting; a subscription-wide sweep produces a plan nobody reads and a rollback nobody can execute.
The canonical ID is the ARM path. It starts with the subscription, then the resource group, then the provider namespace, type and name; child resources append further type and name pairs. Portal URLs, template functions and CLI output should all reduce to that same path before you paste anything into a resource block.
Casing is compared loosely and stored literally. ARM resolves identifiers case-insensitively, but Terraform keeps the string the API returned. Importing with different case can therefore surface a one-time diff in arguments that are compared literally, even though the object in Azure never changed.
Name rules belong to the service. Storage account names are three to twenty-four lowercase letters and digits; resource group names keep the casing they were created with. A syntactically plausible ID is not a valid one, so check the name shape before the import rather than debugging it after.
Import support is per resource and per provider version. Each resource page has an Import section naming the identifier shape: some take a full ARM ID, some a name, some a composite. Read the section for 5.13.0, not the one you remember from an older release.
Terraform 1.17 gives you a reviewable entry point. An import block names the destination address and the identifier in configuration, so the change is reviewed like any other. The older CLI import still works for one object, but it mutates state and leaves nothing behind for a reviewer.
Configuration generation is a draft, not a resource. The generated HCL matches the live API rather than your naming or module conventions, and it can contain literal secrets. Read it line by line, move sensitive values to a reference, and treat every generated argument as unconfirmed.
Import to the final address. A temporary address followed by a moved block doubles the review and leaves an intermediate state other tooling can observe. Decide the module path and resource name first, then confirm the address appears exactly once in the plan.
Inspect the stored ID before you trust the plan. The state view prints the identifier exactly as recorded, and a read of the same path in Azure prints the canonical casing. If the two differ by one segment, you imported the wrong object; if they differ only by case, fix the configuration before the next apply.
Import the companions in the same set. An account without its container, diagnostic setting, lock and role assignment is half-owned: the next plan proposes to create those companions, and a create against an existing object fails. Import them together or record them as external in the register.
A successful import is not a clean plan. Import records the object; the next plan compares configuration with the live API. Missing arguments, provider defaults and server-side normalisation all appear as a diff, and the baseline you want is no change except ones you named in advance.
Table 2 gives the ID shapes an importer actually has to recognise.
| Scope | Canonical shape | Segment discipline |
|---|---|---|
| Tenant | /providers/Microsoft.Management/managementGroups/{name} | Management group name, not display name |
| Subscription | /subscriptions/{subscriptionId} | GUID, no resource group segment |
| Resource group | /subscriptions/{subscriptionId}/resourceGroups/{name} | Name keeps creation casing |
| Resource | .../providers/{namespace}/{type}/{name} | Namespace is case-insensitive, type is not free text |
| Child resource | .../{type}/{name}/{childType}/{childName} | Every parent segment stays in the path |
| Extension | Parent ID + /providers/Microsoft.Authorization/... | Scope is whatever parent the ID starts with |
Figure 3 traces the import loop and the three ways a plan can answer back.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Pick 10 to 20 objects in one resource group"] --> B["Read the canonical ARM ID"]
B --> C{"Import documented for 5.13.0?"}
C -->|"no"| C1["Keep it external or recreate deliberately"]
C -->|"yes"| D["Write the block at its final address"]
D --> E["Import block with the ARM ID"]
E --> F["terraform plan"]
F --> G{"Result for the imported address"}
G -->|"not found"| G1["Wrong tenant, subscription or casing"]
G -->|"already managed"| G2["Another address or another root owns it"]
G -->|"replacement"| G3["Configuration does not match the object"]
G -->|"in-place diff"| G4["Encode the real value, then plan again"]
G -->|"no changes"| H["Apply, then remove the import block"]
G1 --> B
G2 --> C1
G3 --> D
G4 --> D
H --> I["Refactor with moved and removed blocks"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,E,F primary;
class B,C,D secondary;
class G,H,I ok;
class C1,G1,G3 danger;
class G2,G4 warn;
Table 3 maps the answers to the action that keeps the import reversible.
| Result after import | What it means | Next action |
|---|---|---|
not found | Wrong tenant, subscription or casing, or the object was deleted | Re-read the ID from the API, do not guess |
already managed | Another address or another state owns it | Find that owner; never import over it |
| Replacement proposed | Configuration disagrees with an immutable argument | Fix the block, or import to a different address |
| In-place diff | A default or server-side normalisation differs | Encode the real value and re-plan |
| No changes | Configuration matches the object | Apply once, then delete the import block |
A failed import is cheaper than a duplicate create. The import writes state only; it never changes Azure. If the plan after import proposes a replacement, the object was not what you thought it was, and stopping there costs nothing but a review cycle.
Review Provider Features, Defaults and Deprecations
Pin the pair, not just the provider. Terraform 1.17.1 and azurerm 5.13.0 are the tested pair for this article, and the lock file records hashes for every platform the pipeline uses. A runner on a different architecture that initialises without those hashes silently swaps the binary.
A major upgrade is a three-part review. The binary changes, the schema changes, and the plan changes. Read the upgrade guide for provider-level behaviour, then the release notes between your pin and the target, then run the new provider on a branch against a non-production state and diff the plans.
Registration is the change most likely to break an apply. In 5.x the provider registers nothing by default, where 4.x registered a legacy set. A subscription that relied on that implicit registration now fails at apply with an unregistered-namespace error unless the set or the exact namespaces are declared.
Validation moved later, not away. The enhanced-validation controls now sit inside the features block and default to disabled, so an unsupported location or namespace is rejected by Azure at apply instead of by the provider at plan. Enabling preflight can pull some policy and quota failures back to plan time, but only for the resources it supports.
Removals fail fast; default changes do not. A removed argument is a validation error before any API call. A changed default, or a block that stops being computed, appears as an in-place update that can quietly disable a feature you believed was on.
The features block is operational policy. Resource-group deletion protection defaults on, Key Vault purge-on-destroy defaults on, and storage data-plane checks default on. Each default decides what a destroy is allowed to do, so review it with the resource rather than once at bootstrap.
Two flags decide the shape of a failure. Persisting the ID before polling records a failed create as tainted instead of absent; skipping the import check lets a create overwrite an existing object. The first changes your recovery path, the second can destroy data, and neither belongs in a change made to silence an error.
Sort the plan into four buckets. Refresh noise re-reads computed values, normalisation rewrites a representation, address changes belong in moved blocks, and replacement is the only bucket that can cause an outage. A replacement needs a named reason in the change record, not just a count.
Table 4 lists the 5.0 changes most likely to appear in a first plan after the upgrade.
| Change in 5.x | What you see | Review action |
|---|---|---|
Registration defaults to none | Apply fails on an unregistered namespace | Declare the provider namespaces or choose a set |
skip_provider_registration removed | Validation error in the provider block | Replace it with the registration arguments |
| Enhanced validation moves into features | Invalid location passes plan, fails apply | Enable location checks or accept later failure |
Key Vault rbac_authorization_enabled required | Validation error where the old argument was used | Set the new argument explicitly |
| AKS node provisioning profile required | Validation error on an existing cluster block | Add the block and confirm no replacement |
| ACR encryption no longer computed | Plan proposes removing encryption entirely | Declare the block explicitly, or accept and verify |
| Application Insights booleans inverted | Validation error on the old inverted name | Rename the argument and invert the value |
| App Service legacy resources removed | Unknown resource type at plan | Migrate to the current web app resources |
API versions move with the provider, not with your configuration. A release upgrades the API version behind a resource, which can change a server-side default, a validation rule or a computed field. That is why the plan, not the changelog, is the final authority on what an upgrade does.
Run Scoped Federated Pipelines with Protected Plans
Federation replaces the stored secret. A GitHub or Azure DevOps workload presents a short-lived OIDC token, and the app registration's federated credential restricts the repository, branch or environment allowed to present it. Nothing long-lived is stored, and deleting the credential is the off switch.
Plan and apply should not share an identity. The plan identity reads the target scope and the state container; the apply identity writes both. Splitting them means a pull-request plan cannot change infrastructure even if someone edits the workflow file. An apply that creates role assignments also needs a role-administration permission, which Contributor does not include.
The state container is part of the trust boundary. State holds resource IDs, outputs and often sensitive values, so the blob container gets its own role assignment and one key per root. The blob lease is the lock, so a second apply waits or fails instead of interleaving.
The saved plan is the approval unit. Write the plan to a file, render its JSON, hash both, and store them with short retention. Approvers approve that hash and the apply job downloads exactly that artefact; a workflow that re-plans after approval has approved a different change.
Immutable inputs close the gap between review and apply. Apply from a commit SHA with the committed lock file, not a moving branch head. Record the Terraform version, the provider version, the plan hash, the identity that applied, and the digest of any application artefact the plan references.
Serialise per state key and never cancel an apply. A concurrency group keyed on the backend key lets one run finish before the next starts; cancel-in-progress turns a slow apply into a partial one. A held lock is a queue signal, not a reason to force-unlock.
A scheduled read-only plan is the drift alarm. Run it with the plan identity, treat exit code two as "changes exist", and route the result to the owner instead of auto-applying. The same run proves the pipeline still authenticates after a credential rotation.
Table 5 assigns each stage the smallest identity that can do its job.
| Stage | Identity | Scope and role | Output |
|---|---|---|---|
| Plan | Plan app registration | Reader on the target, state blob reader | Plan file, JSON, hash |
| Approve | Human reviewer | No Azure role | Approval naming the hash |
| Apply | Apply app registration | Contributor on the target, role admin when needed, state blob contributor | Applied plan and exit code |
| Verify | Plan app registration | Same as plan | No-change plan and evidence |
Figure 4 shows the gates in order, and Figure 5 contrasts the same pipeline with and without them.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Reviewed commit SHA and lock file"] --> B["Plan job with the read identity"]
B --> C["Save plan, JSON and SHA-256"]
C --> D{"Approval for that hash?"}
D -->|"no"| D1["Stop before apply credentials"]
D -->|"yes"| E["Apply job behind the environment gate"]
E --> F["Queue per state key"]
F --> G{"Blob lease acquired?"}
G -->|"no"| G1["Wait or fail, never force-unlock"]
G -->|"yes"| H["Apply the downloaded plan"]
H --> I{"Apply completed?"}
I -->|"no"| I1["Partial state, reconcile with a fresh plan"]
I -->|"yes"| J["Verify with a no-change plan"]
J --> K["Publish hash, versions and identity"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A,C,H primary;
class B,E,F secondary;
class G,J,K ok;
class D1,G1,I1 danger;
class D,I warn;
Recover a Partial Apply Without Blindly Repeating It
A partial apply is a normal failure, not a corrupted state. Terraform stops at the first error; resources completed before it are recorded, and the failing one is either absent or present and tainted. The exit code is non-zero and the saved plan can no longer be resumed.
Never re-apply the old plan file. It describes a graph that no longer matches reality. Run a fresh plan, read what it proposes for the addresses that did land, and treat any create against an object that already exists as an import candidate rather than a retry.
Diagnose the layer before touching state. A control-plane rejection, a data-plane authorisation failure, a policy denial, a quota limit and a management lock all stop the same graph but need different responses. The error code names the layer; the plan summary does not.
RBAC propagation explains the confusing 403. A role assignment can be written while the data-plane token still lacks it, and a newly created service principal can take time to replicate. Retry with backoff, set the principal type when the caller is ABAC-constrained, and do not recreate the assignment.
Private networking fails after the control plane succeeds. A private endpoint, its DNS zone group and the account's public-access setting form one unit; changing them in separate applies can leave a resource that exists but cannot be reached. Keep the endpoint and the DNS link in the same change as the consumer.
Retention changes what destroy means. Key Vault soft delete and purge protection keep a deleted vault for the retention period, so recreating the same name fails until it is recovered or purged; resource-group deletion protection refuses to remove a group that still holds resources. Both are correct behaviour and both look like a stuck apply.
Reconcile in three passes. List state to see which addresses are recorded, refresh to learn what the APIs hold, then decide per address: keep and import, forget with a removed block that disables destroy, or replace deliberately. A tainted object is a replace decision, not an import.
Close with evidence, not relief. Confirm the final plan is empty, the identifiers you meant to keep are unchanged, retained data still exists, and temporary roles, locks and artefacts are gone. Attach the plan hash and the verification output to the change record.
Table 6 sorts the common Azure failures by the layer that has to answer them.
| Symptom | Layer | First read | Safe next action |
|---|---|---|---|
403 after a role assignment was created | Data plane, RBAC propagation | Activity log plus a direct token test | Wait and retry with backoff; keep the assignment |
RequestDisallowedByPolicy at apply | Azure Policy | Policy assignment and the denied field | Change the configuration or request an exemption |
409 ScopeLocked on delete | Management lock | Locks on the group and the resource | Remove the lock through its own change |
| Name already exists after a destroy | Soft delete or retention | Deleted-vault and deleted-blob listings | Recover or wait, never rename to dodge it |
| Endpoint exists, name resolution fails | Private DNS | Zone link and the record set | Recreate the link, then re-plan the consumer |
Figure 6 is the lab that produces all three failure shapes on purpose, in a disposable subscription.
Recover a Partial Apply Without Blindly Repeating It
Status: design-only. No Azure subscription was touched for this article, and none of the commands below was run here. Use a disposable subscription and treat every identifier as a placeholder.
Prerequisites. Terraform CLI 1.17.1, hashicorp/azurerm 5.13.0, Azure CLI, one resource group you can delete, and a CI principal whose role assignments you may edit. No stored secret is needed because the lab assumes federated credentials.
Minimal setup. One root containing a resource group, a storage account, one container, a role assignment granting the runner blob data access, and a management lock on the resource group. Keep resource-group deletion protection at its default of true.
- Apply the baseline and confirm the next plan is empty.
- Record each address and its canonical ID, then compare the casing with the API.
- Downgrade the runner's blob role to read-only and apply, then confirm the plan is empty.
- Add a second container and apply, so the only change is the data-plane write.
- Record the exit code, then list state and run a fresh plan.
- Restore the writer role, plan again, apply the new plan, and confirm it is empty.
- Remove the private DNS zone link, then disable public network access in a separate change and plan again.
- Destroy with the group lock in place, then remove the lock and destroy again.
| Address after step 4 | State | API reality | Correct action |
|---|---|---|---|
| Resource group and account | Recorded | Exist and unchanged | Leave them alone |
| First container | Recorded | Exists | Leave it alone |
| Second container | Absent | Does not exist | Re-apply once the writer role is restored |
| Role assignment | Recorded, changed outside Terraform | Read-only instead of read-write | Restore it as its own reviewed change |
Expected observation. Step 4 exits non-zero after the refresh succeeds and the data-plane write fails, which is the signature of an authorisation or propagation problem rather than a bad plan. Step 7 fails on name resolution while the endpoint still exists, because the zone link is gone. Step 8 removes the children and stops at the locked group, leaving an empty group rather than lost data.
Failure check. If the fresh plan in step 5 wants to create the account, state was never written for an object that exists; import it instead of applying a duplicate. If the account appears as tainted, the create was recorded before polling finished; replace it deliberately. If step 4 succeeds on the first attempt, the role change had not propagated yet; retry before concluding the configuration is correct.
Cost and cleanup. A small storage account, one container and a lock cost cents for the session. Remove the lock, run destroy again to clean the empty group, confirm the account and container are gone, delete the private endpoint and DNS records, then remove the lab state and the temporary role assignment.