Skip to content

Why terraform is creating the resource before destroying it, when a replace is expected? #36896

Closed as not planned
@ksaffarian

Description

@ksaffarian

Terraform Version

1.3.9

Terraform Configuration Files

terraform {
  required_version = ">=1.3.9"

  required_providers {
    azurerm = {
      version = "=3.107.0"
      source  = "hashicorp/azurerm"
    }
  }
}

data "azurerm_client_config" "current" {}

resource "azurerm_key_vault" "main" {
  name                = local.keyvault_name
  location            = var.location
  resource_group_name = local.resource_group_name
}

resource "azurerm_role_assignment" "main" {
  scope                = azurerm_key_vault.main.id
  role_definition_name = "Key Vault Administrator"
  principal_id         = data.azurerm_client_config.current.object_id

  depends_on = [
    azurerm_key_vault.main
  ]
}

Debug Output

...debug output, or link to a gist...

Expected Behavior

For known reasons regarding data sources and module dependencies, the azurem_role_assignment is being replaced (with same values). This is expected behavior from Terraform as far as I know.

Here is what I see in the plan:

Image

I expect the engine to delete the resource first and recreate it. This is based on default Terraform behavior and it is essential to prevent resource name conflict in the cloud.

Actual Behavior

The plan shows that the replaced resource will be created first and then destroyed.
I don't have any lifecycle block to change the default sequence of actions for a resource. however, this is what is happening for that specific resource type azurerm_role_assignment.

Image

Azure API does not allow for duplicate role assignments and the sequence of create then destroy will lead to an error that "Role already exists".

Steps to Reproduce

  1. create a dependency between keyvault module and resource group module
  2. change something in resource group module (like a tag) to trigger re-evaluation of dependent module (KV)
  3. the role assignment block would be replaced (with same attribute) and during the process it should show an error that role already exists.

Additional Context

No response

References

No response

Generative AI / LLM assisted development?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions