Skip to content

SAIFTRBL0002 ยท permalink

Terraform apply fails: resource already exists - to be imported into the State (application_permissions)

One-sentence summary: the app role, permission scope, pre-authorized app, API access, or delegated permission grant already exists in Entra ID; check the plan first, because a spurious replacement of a resource Terraform already tracks needs a module fix while a genuinely untracked object needs an import.


๐Ÿšจ Symptom

terraform apply fails with one of these errors:

Error: A resource with the ID "/applications/<app-object-id>/appRoles/<role-id>" already exists - to be imported into the State. Please see the resource documentation for "azuread_application_app_role" for more information.
Error: A resource with the ID "/applications/<app-object-id>/permissionScopes/<scope-id>" already exists - to be imported into the State. Please see the resource documentation for "azuread_application_permission_scope" for more information.

The same pattern appears for the pre-authorization, API access, and consent resource types, in any combination, whenever a workspace starts managing objects that already exist in Entra:

Error: A resource with the ID "<app-object-id>/preAuthorizedApplication/<authorized-app-id>" already exists - to be imported into the State. Please see the resource documentation for "azuread_application_pre_authorized" for more information.
Error: A resource with the ID "/applications/<app-object-id>/apiAccess/<resource-app-id>" already exists - to be imported into the State. Please see the resource documentation for "azuread_application_api_access" for more information.
Error: A resource with the ID "/oauth2PermissionGrants/<grant-id>" already exists - to be imported into the State. Please see the resource documentation for "azuread_service_principal_delegated_permission_grant" for more information.

App role assignments (azuread_app_role_assignment) report the same collision with different wording, and the attempt before it usually fails with a provider error instead:

Error: Could not create app role assignment
unexpected status 400 (400 Bad Request) with error: Request_BadRequest: Permission being assigned already exists on the object
Error: Provider produced inconsistent result after apply
provider "provider[\"registry.terraform.io/hashicorp/azuread\"]" produced an unexpected new value: Root object was present, but now absent.

Delegated permission grants (azuread_service_principal_delegated_permission_grant) follow the same two-step pattern. The first run fails with the inconsistent-result error above, and every later run fails with:

Error: Could not create delegated permission grant
unexpected status 400 (400 Bad Request) with error: Request_BadRequest: Permission entry already exists.

This appears in Terraform Cloud apply logs when application_permissions tries to create a role, scope, pre-authorization, API access grant, delegated permission grant, or app role assignment that already exists in Entra ID.


๐Ÿ“Œ Applies to

Aspect Value
Component saif-application-permissions Terraform module, and the permissions submodule inside the platform application module
Forge versions Any version managing generated app_roles or scopes
Related versions Generated auth.generated.tf older than the Forge 3.8.5 template still carries the depends_on that triggers cause 1. The platform half is fixed in iac-azure-modules 5.1.1

๐Ÿง  Cause

Two different problems produce this identical error, and their fixes are opposite. One needs the object left alone and a module change; the other needs an import. Run the Diagnose step before acting.

Cause 1: Terraform is replacing a resource it already tracks

The object is in state, the plan shows it being replaced, and the replacement traces back to a deferred data source read. Terraform recreates it, the "new" resource resolves to the same Entra object, and the create call collides with the object that is still there.

The replacement itself is spurious. It comes from a coarse module-level depends_on sitting above the data sources the module reads:

  1. Terraform cannot read a data source at plan time if a managed resource in its dependency closure has a pending change in the same plan. It defers the read to apply time and reports read_because_dependency_pending. A changed local or variable does not trigger this, and unknown values in the data source's own configuration produce a different reason, read_because_config_unknown.
  2. Every attribute derived from that deferred read becomes unknown at plan time. Which attribute that is depends on the module. In application_permissions it is the application object ID from data.azuread_application. In the platform application module the application ID arrives as a direct resource reference and is never unknown; the unknowns there are the pre-authorized client lookups, data.azuread_application.pre_authorized and data.azuread_service_principal.pre_authorized_sp.
  3. Those unknowns land on attributes that cannot change in place. The provider reports the change as impossible without replacement, which is what "action_reason": "replace_because_cannot_update" records, and Terraform plans a replacement.
  4. At apply time the data sources resolve to the same objects they always did, so the replacement recreates something identical to what already exists.

Two separate depends_on blocks caused this in practice:

Location Resources affected Observed action order Fix
module "application_permissions" in generated infra/api/auth.generated.tf azuread_application_app_role, azuread_application_permission_scope ["delete", "create"], destroy-then-create, destructive if the run fails Regenerate the file from the current template (Forge 3.8.5 and later)
module "permissions" inside the platform application module azuread_application_pre_authorized, azuread_application_api_access, azuread_service_principal_delegated_permission_grant ["create", "delete"], create-before-destroy, safe for the address that errors Move to a module version built on iac-azure-modules >= 5.1.1, which contains iac-azure-modules#76

The trigger is "something upstream has a pending change," so this is intermittent rather than constant. A workspace can apply cleanly for months and then fail the first time an unrelated upstream resource changes, such as a new random_string introduced by a platform module bump. That intermittency is the tell: nothing about the app registration itself changed.

Read the action order as a diagnostic signal, not just a caveat. It tells you which depends_on you are looking at and whether anything is at risk:

  • ["delete", "create"] on an app role or scope points at the generated auth.generated.tf. Terraform destroys first, so a run that errors before the create leaves the object deleted from the registration. In the run behind this article, App.Read, App.Write, and the User.Read scope were planned this way and all three disappeared from state between serial 4 and serial 5. The destroy ran, the run errored, the create never happened.
  • ["create", "delete"] on a pre-authorization, API access, or delegated grant resource points at the platform application module. The create runs first and collides with the object that is still there, so the run errors without touching the existing object. These are the addresses that report already exists, and they are safe.

action_reason was replace_because_cannot_update on all nine replacements in that run, which is the ordinary "the provider cannot change this in place" reason rather than anything exotic.

Do not treat the error list as the blast radius. That run planned six replacements in the platform module and surfaced only three errors, because the apply stopped early. Check the app registration after any failed apply, not just the plan, and check the app roles and scopes first since those are the destroy-then-create half.

Cause 2: state drift, the object is not tracked at all

Standard Terraform state drift: the role, scope, pre-authorization, or grant exists in Entra ID, but Terraform state has no record of the matching resource address. That can happen after a partial apply, manual creation, state loss, or an out-of-band delete and recreate. It can occur on its own, or immediately after resolving the deadlock in Terraform apply fails: Provider produced inconsistent final plan if you re-ran an apply while the object was mid-transition.

A create that succeeds in Entra but fails its read-back also produces this drift, and it affects azuread_app_role_assignment and azuread_service_principal_delegated_permission_grant. The provider creates the object, the follow-up read returns nothing, and Terraform rejects the result with Root object was present, but now absent. The object exists in Entra, and state has no entry for it. Every rerun then fails with a duplicate error (Permission being assigned already exists on the object for an assignment, Permission entry already exists. for a grant), so retrying does not help. The latest failing run is a victim; find the first failing run of the same stage to see where the object was orphaned.

In the run behind this addition, the first attempt created six of seven resources cleanly and failed on role_assignments["<group-object-id>-App.Write"] with the inconsistent-result error. Graph showed the assignment created about a second before the read-back. The second attempt refreshed the six tracked resources, planned one add, and failed with the 400. A matching, still open provider issue is hashicorp/terraform-provider-azuread#763, whose title matches the inconsistent-result error. The read-after-create timing explanation is an inference and is not confirmed from the provider source.

For the delegated grant, the provider source confirms the mechanism. In hashicorp/azuread v3.10.0, the latest release as of 2026-11, servicePrincipalDelegatedPermissionGrantResourceCreate posts the grant, sets the ID, and calls the read function immediately with no consistency wait. When that GET returns 404, the read function clears the ID and returns no error, which Terraform reports as Root object was present, but now absent. The case behind this addition was a first deploy to a new environment: the API's service principal was created two seconds before the grant, and the grant create ran about 86 seconds before failing, which fits the provider retrying while the new service principal replicated and the read-back then landing on a replica without the grant. The same stage in the previous environment recorded its grant normally, so the race is intermittent. The closest provider issue, hashicorp/terraform-provider-azuread#748, was closed in 2022 as not reproducible.

The recurring case is a workspace starting to manage an Entra object that already exists, and there is no single version boundary for it. The pre-authorization, API access, and consent resources arrived in application_permissions across four commits in late 2025, not in 3.0.12:

Resource Introduced
azuread_application_api_access.api_permissions, azuread_application_pre_authorized.pre_authorized b66ce20, 2025-10-22, with the module itself
azuread_application_api_access.pre_authorized_api_access f5786c1, 2025-11-03
azuread_service_principal_delegated_permission_grant.pre_authorized_consent e19e64d, 2025-11-03
azuread_service_principal_delegated_permission_grant.scope_permissions b13526a, 2025-11-07

3.0.12 (cc89c65, 2026-01-20) added no resource types at all. It added the configure_api_access and grant_admin_consent opt-out flags, both defaulting to true, plus documentation comments. An app that kept the defaults saw no change in what the module manages.

So the trigger is narrower than "upgrading past a release." Expect this error when a workspace manages one of these objects for the first time: an app onboarded to a module version that already declares the resource, a pre_authorized_applications entry added for a client someone had already pre-authorized by hand, or configure_api_access or grant_admin_consent flipped from false back to true. Only the addresses newly brought under management collide, so the blast radius is those addresses rather than the whole module.


๐Ÿ” Diagnose

Check whether Terraform already tracks the failing address:

terraform state list | Select-String "azuread_application_app_role|azuread_application_permission_scope|azuread_application_pre_authorized|azuread_application_api_access|azuread_service_principal_delegated_permission_grant|azuread_app_role_assignment"

Then route on what you find. Do not route on must be replaced alone. A tainted resource, an explicit terraform apply -replace=..., and a genuine change to an attribute that forces replacement all replace an address that is present in state, and none of them are fixed by this guide.

  1. Address is not in state. Cause 2. Go to Fix cause 2.
  2. Address is in state, the plan shows must be replaced, and the deferred-read signature below is present. Cause 1. Go to Fix cause 1.
  3. Address is in state and replaced, but the deferred-read signature is absent. Neither cause applies, and this guide is the wrong one. Find the real replacement trigger instead: look for is tainted, so must be replaced in the plan output, check the run's plan options for -replace, and diff your config for an actual change to a replacement-forcing attribute. Removing the depends_on will not help.

Confirm the cause 1 signature from the plan rather than the apply log. In a Terraform Cloud structured plan (GET /api/v2/plans/{plan-id}/json-output), look for all of:

  • "action_reason": "read_because_dependency_pending" on a nearby data.azuread_* resource.
  • A replacement on the failing address, meaning "actions": ["create", "delete"] or ["delete", "create"], normally with "action_reason": "replace_because_cannot_update".
  • No "action_reason" of replace_because_tainted or replace_by_request on that address, either of which points at step 3 instead.

List every multi-action change in the plan, not just the addresses that errored, since the action order per address tells you which depends_on is responsible and which objects a failed run can delete.

In human-readable plan output, look for will be read during apply on a data source whose configuration is entirely static. That strongly suggests an inherited depends_on, but it is not proof. A depends_on on the data block itself, an unknown count or for_each, a precondition that depends on a pending resource, or unknown values in the provider configuration all defer a read as well. Confirm a module-level depends_on is actually present before acting on it.


โœ… Fix

Fix cause 1: remove the coarse depends_on

Do not import. The object is already tracked correctly; the plan is wrong.

  1. Compare your generated infra/api/auth.generated.tf against the current template at src/templates/saif-feature-api/infra/api/auth.generated.tf. If your copy contains depends_on = [module.saif-appservices], it predates the fix. Regenerate the file, or apply the change by hand: drop the depends_on, raise the version constraint to >= 3.8.5, < 4.0.0, and pass the identity in directly.

    application = {
      id        = module.saif-appservices.application_id
      client_id = module.saif-appservices.application_client_id
    }
    service_principal = {
      object_id = module.saif-appservices.application_principal_object_id
      client_id = module.saif-appservices.application_principal_client_id
    }
    

    Passing these as inputs creates the same ordering edges the depends_on was there to provide, without deferring the module's data reads.

    The 3.8.5 release notes are written around a different symptom of the same depends_on, Error: Cycle on apply. For the app roles and scopes, spurious replacement and the cycle both come from the coarse module boundary, and this change clears both, so do not skip 3.8.5 because your error text does not mention a cycle. It does not cover the platform module half; see step 2.

  2. For the pre-authorization, API access, and delegated grant resources, the fix is iac-azure-modules#76, released in iac-azure-modules 5.1.1. That is a platform module you consume indirectly: saif-appservices (SAIFCorp/saif-apiservice/azure) sits several modules above where the change lands, so bumping saif-appservices alone does not pick it up. You get the fix when the Forge-published module you call is itself built on iac-azure-modules >= 5.1.1, so check the release notes for the Forge version carrying that bump and move to it.

    Until your workspace is on a version that carries the fix, the interim path for this half is to re-run the apply after the upstream change has settled. The deferred read is no longer pending on the second run, so the replacement disappears and the apply succeeds. That is a workaround, not a fix; it recurs the next time something upstream changes. Once you are on a version containing #76, this step should stop being necessary, and a recurrence means the deferred read is coming from somewhere else.

  3. Re-plan. The app role and scope replacements should disappear and data.azuread_application should resolve at plan time. Replacements inside the platform application module persist until the module you call is built on iac-azure-modules >= 5.1.1.

  4. If a previous failed apply already destroyed app roles or scopes, the clean apply after this fix recreates them. Verify against the registration rather than assuming.

Fix cause 2: import or remove the untracked object

  1. Import the exact ID from the error message:

    terraform import 'module.application_permissions.module.permissions.azuread_application_app_role.app_roles["<value>"]' "/applications/<app-object-id>/appRoles/<role-id>"
    terraform import 'module.application_permissions.module.permissions.azuread_application_permission_scope.scopes["<value>"]' "/applications/<app-object-id>/permissionScopes/<scope-id>"
    

    For the pre-authorization, API access, and consent resources there are five distinct addresses, not three. The module declares two azuread_application_api_access resources and two azuread_service_principal_delegated_permission_grant resources under different names, and each pair means a different thing:

    Resource What it represents Whose object ID the import ID carries
    azuread_application_api_access.api_permissions This API's own permissions on an upstream API such as Microsoft Graph This API
    azuread_service_principal_delegated_permission_grant.scope_permissions Admin consent for those upstream permissions Grant ID only
    azuread_application_pre_authorized.pre_authorized A client app pre-authorized against this API This API
    azuread_application_api_access.pre_authorized_api_access The client app's own API access entry pointing back at this API The pre-authorized client app
    azuread_service_principal_delegated_permission_grant.pre_authorized_consent Admin consent for the client app against this API Grant ID only

    Include the resource name in the address. azuread_application_api_access["Microsoft Graph"] without a name is not a valid Terraform address and fails immediately with Error: Invalid address. Use the ID exactly as it appears in the error, prefixed as shown:

    terraform import 'module.saif-appservices.module.identity.module.application.module.permissions.azuread_application_api_access.api_permissions["Microsoft Graph"]' "/applications/<this-api-app-object-id>/apiAccess/<upstream-api-client-id>"
    terraform import 'module.saif-appservices.module.identity.module.application.module.permissions.azuread_service_principal_delegated_permission_grant.scope_permissions["Microsoft Graph"]' "/oauth2PermissionGrants/<grant-id>"
    terraform import 'module.saif-appservices.module.identity.module.application.module.permissions.azuread_application_pre_authorized.pre_authorized["_saif_cli"]' "<this-api-app-object-id>/preAuthorizedApplication/<client-app-client-id>"
    terraform import 'module.saif-appservices.module.identity.module.application.module.permissions.azuread_application_api_access.pre_authorized_api_access["_saif_cli"]' "/applications/<client-app-object-id>/apiAccess/<this-api-client-id>"
    terraform import 'module.saif-appservices.module.identity.module.application.module.permissions.azuread_service_principal_delegated_permission_grant.pre_authorized_consent["_saif_cli"]' "/oauth2PermissionGrants/<grant-id>"
    

    The two object-ID placeholders are not the same app. <this-api-app-object-id> is the registration this module manages. <client-app-object-id> is the pre-authorized client's object ID, which pre_authorized_api_access takes instead. They coincide only for the _self key, where the client is this API itself. _saif_cli is an example key; substitute your own pre_authorized_applications keys.

    The delegated permission grant import must be prefixed with /oauth2PermissionGrants/. The bare grant ID fails at terraform plan, harmlessly, since no state is touched. Resolve the grant IDs with:

    $apiSpId = az ad sp list --filter "appId eq '<this-api-client-id>'" --query "[0].id" -o tsv
    $msGraphSpId = az ad sp show --id 00000003-0000-0000-c000-000000000000 --query id -o tsv
    $clientSpId = az ad sp list --filter "appId eq '<pre-authorized-app-client-id>'" --query "[0].id" -o tsv
    
    # scope_permissions: this API consuming Microsoft Graph
    az rest --method GET --uri "https://graph.microsoft.com/v1.0/oauth2PermissionGrants?`$filter=clientId eq '$apiSpId' and resourceId eq '$msGraphSpId'" --query "[?consentType=='AllPrincipals'].id | [0]" -o tsv
    
    # pre_authorized_consent: the client app consuming this API, client and resource inverted
    az rest --method GET --uri "https://graph.microsoft.com/v1.0/oauth2PermissionGrants?`$filter=clientId eq '$clientSpId' and resourceId eq '$apiSpId'" --query "[?consentType=='AllPrincipals'].id | [0]" -o tsv
    

    The two queries are not interchangeable. pre_authorized_consent inverts the pair, so the first query returns nothing for it, and loosening the filter until it returns something imports the wrong grant.

    00000003-0000-0000-c000-000000000000 is the well-known Microsoft Graph application ID, resolved to the tenant's Microsoft Graph service principal object ID. A client/resource pair can have both a per-user (Principal) grant and a tenant-wide admin-consent (AllPrincipals) grant; application_permissions manages the AllPrincipals grant, so filter on consentType instead of taking value[0]. Confirm which grant type matches what Terraform actually declares before importing.

    These five are not the whole module. application_permissions declares ten resources; the other five are azuread_application_app_role.app_roles, azuread_application_permission_scope.scopes, and three azuread_app_role_assignment resources (permissions, role_assignments, pre_authorized_app_roles), which drift the same way. Import whichever addresses your errors actually name instead of working from a fixed count.

    For an azuread_app_role_assignment that fails with Permission being assigned already exists on the object, the import ID is /servicePrincipals/<resource-sp-object-id>/appRoleAssignedTo/<assignment-id>, where the resource service principal is the API that owns the role. Find the assignment ID by filtering on the principal and the role ID from the plan:

    az rest --method GET --uri "https://graph.microsoft.com/v1.0/servicePrincipals/<resource-sp-object-id>/appRoleAssignedTo" --query "value[?principalId=='<principal-object-id>' && appRoleId=='<app-role-id>'].id | [0]" -o tsv
    

    Take principal_object_id and app_role_id from the failed plan's will be created block, then import the address the error names, for example role_assignments["<group-object-id>-App.Write"]. Against a Terraform Cloud workspace, Test-WorkspaceMigration.ps1 -WorkspaceName <workspace> -Imports @{ '<address>' = '<id>' } writes the import through an auto-approved apply with no confirmation, so confirm the plan target first. The script stages the configuration from the workspace's most recent run when no applied run exists, so it works for a first deploy that never completed.

    Import the addresses one at a time. Each terraform import is independent and touches only the address you name, so run one command per address the error reports, in any order. There is no bulk path for these resources.

    If terraform import fails with Invalid for_each argument ... will be known only after apply, use an import block instead. The import command does not plan the rest of the configuration, so a for_each that reads another resource's attributes stays unknown, while a normal plan resolves it. Add a file such as import.tf:

    import {
      to = module.saif-appservices.module.identity.module.application.module.permissions.azuread_service_principal_delegated_permission_grant.scope_permissions["Microsoft Graph"]
      id = "/oauth2PermissionGrants/<grant-id>"
    }
    

    Then target only that address, check the plan, and apply the saved plan:

    terraform plan -lock=false -target='<address>' -out=import.tfplan
    terraform apply import.tfplan
    

    The plan must read Plan: 1 to import, 0 to add, 0 to change, 0 to destroy; do not apply anything else. Delete import.tf and import.tfplan afterwards.

    For a workspace whose state lives in Pulumi Cloud (cloud { hostname = "tf.pulumi.com" }), run these commands from a copy of the failing root at the build commit, with TF_WORKSPACE set to the workspace from the pipeline log. The module's provider "okta" {} block needs Okta credentials even for import and plan, and the data lookups need the environment's subscription, so wrap each command in the environment's Pulumi ESC environment, for example pulumi env run saif-corp/saif/qa -- terraform plan .... That environment supplies the ARM_* OIDC identity, ARM_SUBSCRIPTION_ID, and OKTA_* variables. Check that ARM_SUBSCRIPTION_ID matches the az account set --subscription line in the pipeline log; a mismatch fails with Resource group '<name>' could not be found.

  2. If the object is orphaned, remove it through the Entra admin center, az rest, or Microsoft Graph instead of importing it.

Do not force a recreate to clear this error

Terraform apply fails: Provider produced inconsistent final plan offers a targeted destroy of the tracked app roles and scopes. That step is gated there on confirming the deferred-read signature first and on targeting exact instance keys, and it is not a remedy for this error. If Diagnose confirms cause 1, the objects are fine and only the plan is wrong, and a targeted destroy deletes working app roles and scopes to work around it. The already exists error itself comes from a create-before-destroy replacement that leaves the object intact; a targeted destroy removes it for real, so callers lose the authorization that role or scope carries until the recreate lands, and a failed apply can leave it deleted. The IDs survive that: they are deterministic uuidv5 values seeded on the application ID and the role or scope value, so a recreate against an unchanged seed recomputes the identical GUID. GUIDs churn only when the seed changes, such as when the app registration itself is recreated. Fix the depends_on instead.


๐Ÿ”ฌ Verify

terraform apply completes without the "already exists - to be imported into the State" error.

For cause 1, the plan no longer shows must be replaced on the permission resources, and no data.azuread_* source reports will be read during apply. Confirm the app registration still has every expected app role and scope, since a prior failed apply may have destroyed some.

For cause 2, terraform state list now includes the imported address.