Module 7: Maintaining Infrastructure with Terraform

Lesson 7.1: Importing Existing Infrastructure

Plain language

Importing tells Terraform: "this object already exists, so record it in state under this address." Import doesn't create anything. It only binds an existing object to a resource address. After an import, your configuration must describe the object accurately, or the next plan proposes changes to it.

Two ways to import

terraform import (CLI) import block (1.5+)
Syntax terraform import ADDRESS ID import { to = ADDRESS id = "ID" } in configuration
Preview ✗. Writes state immediately. ✓. The import appears in plan ("1 to import") and happens on apply.
Resource block Must already exist in configuration Can be generated with plan -generate-config-out
Many objects at once One per command Many blocks, or one block with for_each (1.7+)
Code review and VCS-driven runs ✗ ✓. Works in HCP Terraform VCS workflows where nobody runs the CLI against state.
id value Literal on the command line Literal or expression, known at plan time
Aliased provider -provider= flag (legacy) provider = aws.west argument
HCL
import {
  to = docker_network.app
  id = "4f9c0d2e..." # provider-specific import ID — check the provider docs' "Import" section
}

resource "docker_network" "app" {
  name = "app-net"
}

Generating configuration

Shell
terraform plan -generate-config-out=generated.tf
  • This writes HCL for every import block whose target resource block doesn't exist yet.
  • The output file must not already exist.
  • Review and edit the generated HCL. It can include computed attributes, conflicting arguments, or literal values you'll want to replace with references. HashiCorp warns that it can contain errors to fix before applying.

Under the hood

  • The import ID format is defined by the provider. It might be an AWS instance ID, a container ID, or a compound value such as project/region/name. Check the "Import" section of the resource's documentation.
  • Not every resource type supports import.
  • After the import is applied, the import block is a no-op. You can remove it, or keep it as a record. Removing it is the common convention.
  • New in 1.12 (flagged): for providers that implement resource identity, an import block can use an identity object instead of a string id. Provider support is still limited, so exam questions and these labs focus on id.