Andrew Mercer
on this page

Most arguments in a resource block are passed to the provider. Meta-arguments are interpreted by Terraform core and work on any resource type (and most work on module blocks).

Meta-argument Resources Modules Data sources Covered
count ✓ ✓ ✓ Loops
for_each ✓ ✓ ✓ Loops
depends_on ✓ ✓ ✓ Dependencies
provider ✓ ✓ Below
providers ✓ Below
lifecycle ✓ partial Below
provisioner / connection ✓ Below

provider and providers

Use provider to choose a non-default (aliased) provider configuration for a resource:

provider "azurerm" {
  features {}
  subscription_id = var.workload_subscription_id
}

provider "azurerm" {
  alias           = "connectivity"
  features {}
  subscription_id = var.connectivity_subscription_id
}

# Spoke-side peering in the workload subscription (default provider)
resource "azurerm_virtual_network_peering" "spoke_to_hub" {
  name                      = "peer-spoke-to-hub"
  resource_group_name       = azurerm_resource_group.spoke.name
  virtual_network_name      = azurerm_virtual_network.spoke.name
  remote_virtual_network_id = data.azurerm_virtual_network.hub.id
}

# Hub-side peering in the connectivity subscription
resource "azurerm_virtual_network_peering" "hub_to_spoke" {
  provider                  = azurerm.connectivity
  name                      = "peer-hub-to-${var.workload}"
  resource_group_name       = "rg-connectivity-hub"
  virtual_network_name      = "vnet-hub-cc"
  remote_virtual_network_id = azurerm_virtual_network.spoke.id
}

Modules receive providers through providers. The child declares which aliases it expects with configuration_aliases:

# modules/spoke-peering/versions.tf
terraform {
  required_providers {
    azurerm = {
      source                = "hashicorp/azurerm"
      version               = ">= 4.0"
      configuration_aliases = [azurerm.hub]
    }
  }
}

# root
module "peering" {
  source = "../modules/spoke-peering"
  providers = {
    azurerm     = azurerm               # default
    azurerm.hub = azurerm.connectivity  # alias the child calls "hub"
  }
}

Multi-region and multi-account patterns are covered in advanced.

The lifecycle block

resource "azurerm_key_vault" "this" {
  # ...
  lifecycle {
    prevent_destroy       = true
    create_before_destroy = false
    ignore_changes        = [tags["last_rotated"]]
    replace_triggered_by  = [terraform_data.rebuild_marker]

    precondition {
      condition     = var.sku_name == "premium" || !var.hsm_required
      error_message = "HSM-backed keys need the premium SKU."
    }

    postcondition {
      condition     = self.purge_protection_enabled
      error_message = "Purge protection must be on."
    }
  }
}

Most lifecycle arguments must be literal values. They're read before expressions are evaluated. The exceptions are the condition blocks, and OpenTofu 1.12+ which lets prevent_destroy reference values in the same module (Terraform doesn't).

create_before_destroy

When a change forces replacement, Terraform normally destroys the old object first. With create_before_destroy = true, it creates the new one, repoints dependents, then destroys the old.

Use it for things where a gap means an outage: certificates, launch templates, NSG rules referenced by live NICs, App Service plans with apps on them.

Constraints:

  • Names must be able to coexist. If the name is fixed, the create fails because the old object still holds it. Add a random or hashed suffix, or use a name_prefix argument where the provider has one.
  • It propagates to dependencies: Terraform forces it on anything this resource depends on, to keep the ordering valid. You'll see it in the plan for resources you didn't mark.

prevent_destroy

Any plan that would destroy the resource fails. Put it on things that are expensive or impossible to rebuild: state storage accounts, Key Vaults with purge protection, databases with data, DNS zones.

What it doesn't do:

  • Stop someone deleting the resource block from configuration. The block is gone, so the lifecycle setting goes with it, and Terraform destroys the object. Pair it with cloud-side protection: Azure resource locks (CanNotDelete), AWS deletion protection, Key Vault purge protection, SQL prevent_destroy and backups.
  • Stop deletion outside Terraform.
  • Accept variables in Terraform. A module can't make it configurable; OpenTofu 1.12+ can.

destroy = false (Terraform 1.16+)

Terraform 1.16 adds a destroy lifecycle argument. Setting destroy = false tells Terraform not to destroy the real object. OpenTofu 1.12 has a similarly named setting. Read your version's docs for the exact behaviour (whether a destroy plan errors, or the object is forgotten from state and left running) before relying on it as a guard:

lifecycle {
  destroy = false
}

For removing a resource from management without destroying it, the long-standing tool is a removed block with destroy = false.

ignore_changes

Tells Terraform to ignore drift in specific attributes after creation:

lifecycle {
  ignore_changes = [
    tags["CreatedOnDate"],                 # one map key set by Azure Policy
    site_config[0].application_stack,      # managed by the app team's pipeline
    app_settings["WEBSITE_RUN_FROM_PACKAGE"],
  ]
}

Legitimate uses:

  • Attributes another system owns: tags added by Azure Policy, autoscaler-managed node_count, image tags deployed by CD.
  • Provider bugs that produce perpetual diffs, as a temporary measure with a comment and an issue link.

Abuses:

  • ignore_changes = all turns Terraform into a create-only tool. Real drift becomes invisible.
  • Ignoring an attribute to silence a diff you don't understand. A provider-injected default (like Azure's default virtual_application block on App Service) is often better handled by declaring the default explicitly, so legitimate future changes still show up in the plan.

replace_triggered_by

Replace this resource when something else changes:

resource "terraform_data" "image_version" {
  input = var.image_version
}

resource "azurerm_linux_virtual_machine_scale_set" "this" {
  # ...
  lifecycle {
    replace_triggered_by = [terraform_data.image_version]
  }
}

References must be to resources (or their attributes), not variables directly. Wrap a variable in terraform_data (Terraform 1.4+) as above. Terraform 1.15+ errors if you reference an attribute that doesn't exist, instead of silently never triggering.

Preconditions and postconditions

data "azurerm_subnet" "aks" {
  name                 = var.aks_subnet_name
  virtual_network_name = var.vnet_name
  resource_group_name  = var.network_rg

  lifecycle {
    postcondition {
      condition     = tonumber(split("/", self.address_prefixes[0])[1]) <= 22
      error_message = "AKS subnet must be /22 or larger for Azure CNI."
    }
  }
}

resource "azurerm_kubernetes_cluster" "this" {
  # ...
  lifecycle {
    precondition {
      condition     = !var.private_cluster || var.private_dns_zone_id != null
      error_message = "A private cluster needs private_dns_zone_id."
    }
  }
}
Evaluated Can reference Failure
precondition Before the resource is planned Anything except self Blocks plan/apply
postcondition After plan (if known) and after apply self plus anything Blocks; dependents don't proceed
Variable validation When the variable is set The variable, plus other vars/locals/data (1.9+) Blocks plan
check block End of plan and apply Anything, including scoped data sources Warning only

Use preconditions to assert assumptions about inputs that came from elsewhere (data sources, other modules). Use postconditions to assert guarantees about what you built, so downstream resources don't run against a broken assumption. More in policy.

action_trigger (Terraform 1.14+)

Terraform 1.14 added actions: provider-defined imperative operations (invoke a Lambda, run an Ansible job, restart a service) declared with a top-level action block. A resource's lifecycle can trigger them on events. Terraform 1.16 added before_destroy/after_destroy events and on_failure modes (halt, taint, continue). Syntax and examples are in advanced: actions.

Provisioners: last resort

resource "azurerm_linux_virtual_machine" "this" {
  # ...
  provisioner "remote-exec" {
    inline = ["sudo systemctl enable --now myagent"]
    connection {
      type        = "ssh"
      host        = self.private_ip_address
      user        = "azureuser"
      private_key = file(pathexpand("~/.ssh/id_ed25519"))
    }
  }
}

HashiCorp's own docs call provisioners a last resort. They aren't in the plan, failures leave resources tainted, and they don't re-run when you change them. In order of preference:

  1. cloud-init / custom_data for VM bootstrapping
  2. Image baking with Packer
  3. Configuration management (Ansible) run by your pipeline after apply
  4. Actions (Terraform 1.14+) for imperative operations the provider supports
  5. terraform_data with local-exec and triggers_replace for one-off glue
  6. remote-exec / file provisioners