Infrastructure Lifecycle and Operations · Topic 3 of 5

Import and Resource Lifecycle

Terraform Professional 002: import with for_each and generated config, use lifecycle arguments, and safely rename, retire or destroy managed resources.

  • 5 min
In a nutshell
  • An import block's id must be known at plan, and the import happens at apply.
  • -generate-config-out needs a new file, and its output must be reviewed.
  • ignore_changes covers updates only.

What it is

Import adopts a real object into state so Terraform can manage it. Lifecycle management controls what happens to that object from then on: how it is replaced, what protects it and how it leaves Terraform's control.

Most exam questions here give a requirement and ask which block or argument meets it. The hard part is knowing what each one does not do.

Existing objectimport blockManagedin statelifecycle rulesReplaced or protectedRetiredremoved or destroyed

How it works

Importing with a review

import {
  for_each = var.buckets
  to       = aws_s3_bucket.this[each.key]
  id       = each.value
}

resource "aws_s3_bucket" "this" {
  for_each = var.buckets
  bucket   = each.value
}

If var.buckets is { logs = "acme-logs" }, the object named acme-logs lands at aws_s3_bucket.this["logs"]. The plan shows the import and any change needed to match the configuration, and nothing happens until apply.

The id can be any expression that evaluates to a string and is known at plan time. identity is an alternative for providers that support it, and the two cannot be combined. The to address can also point inside a module, and provider selects an aliased configuration.

Generating configuration

terraform plan -generate-config-out=generated.tf

This writes resource blocks for import blocks that have none. It is experimental, and it fails if the file already exists.

Generated code is a draft. A plan can fail with Conflicting configuration arguments, but the file is still written, so you remove one argument and plan again.

The terraform import ADDRESS ID command is the older route. It writes to state at once with no plan to review, so prefer import blocks.

Lifecycle arguments

ArgumentEffectLimit
create_before_destroyNew object first, then the old one is destroyedUnique names can collide while both exist; dependencies inherit it
prevent_destroyRejects a plan that would destroy the objectNo protection once the block is removed from configuration
ignore_changesIgnores listed attributes when planning updatesValues still apply on create; all ignores every attribute
replace_triggered_byReplaces when a referenced resource or attribute changesManaged resources only; use terraform_data for plain values
preconditionChecks before the resource's arguments are evaluatedNeeds condition and error_message
postconditionChecks afterward and blocks dependents on failureNeeds condition and error_message

Lifecycle settings are processed early, so most must be literal values rather than arbitrary expressions. Apart from create_before_destroy, they are not recorded in state.

Tracing lifecycle behavior

resource "aws_instance" "app" {
  ami           = var.ami
  instance_type = "t3.small"
  tags          = { Owner = "platform" }
  lifecycle {
    create_before_destroy = true
    ignore_changes        = [tags]
  }
}
  1. Someone adds a Cost tag in the console. The next plan proposes no update, because tags is ignored.
  2. var.ami changes, which forces replacement. The plan shows +/-, so the new instance comes first.
  3. The new instance is created from configuration, so it has only the Owner tag. The console tag is gone, because ignore_changes covers updates, not create.

Retiring a resource

GoalToolReal object
Rename or move into a modulemoved blockUntouched
Stop managing, with a reviewed planremoved block with destroy = falseStays
Stop managing, immediatelyterraform state rmStays
Destroy this one resourceDelete its block, then applyDestroyed
Destroy everything hereterraform destroyDestroyed; configuration unchanged
removed {
  from = aws_instance.legacy
  lifecycle {
    destroy = false
  }
}

The removed block replaces the resource block, and its from cannot include an instance key. The docs prefer it over state rm because you can preview the result.

A moved block's from and to can map instances, such as aws_instance.c[0] to aws_instance.c["small"], and blocks can be chained across renames. Keep them in shared modules: removing one makes configurations still on the old address plan a destroy.

How the exam asks about this

  • "A resource must leave Terraform but stay running, and the team wants to preview the change." Use a removed block with destroy = false.
  • "prevent_destroy is set, and someone deleted the resource block; what happens?" Terraform plans the destroy, because the rule left with the block.
  • "An autoscaler changes the desired count, and Terraform keeps reverting it." Add that attribute to ignore_changes.

What to remember for the exam

  • An import block's id must be known at plan, and the import happens at apply.
  • -generate-config-out needs a new file, and its output must be reviewed.
  • ignore_changes covers updates only.
  • prevent_destroy guards only while the configuration exists.
  • replace_triggered_by references managed resources only.
  • Use moved to change an address, and removed to leave management.
Watch out

Run a plan straight after import. If the configuration differs from the real object, the apply that completes the import also changes the object to match.

Common mistakes

Fixing a rename with destroy and create. Renaming a resource block alone plans a replacement. Add a moved block so state follows the new address.

Trusting prevent_destroy as a full safeguard. Removing or commenting out the block removes the rule too. Protect critical objects with review and provider level protection as well.

Using an import or moved block to stop managing. Neither keeps a deleted resource out of the destroy plan. Only removed with destroy = false or terraform state rm does that.

Check yourself

  • Does ignore_changes stop a value being set when a resource is replaced?

    No. It applies to updates only, so the replacement is created with the values in the configuration.

  • Which two options stop managing an object without destroying it?

    A removed block with destroy = false, or terraform state rm. The block is preferred because you can preview the result in a plan.

  • What happens if -generate-config-out points at an existing file?

    Terraform throws an error. The path must be a new file, which you then review and edit before applying.

Topic 3 of 5 in Infrastructure Lifecycle and Operations

Test yourself on Infrastructure Lifecycle and Operations

The full HashiCorp Terraform Infrastructure Engineer Professional question bank has 600 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by HashiCorp. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.