Skip to content
Hands-on IT IT Drills

Day 11: Import, moved, removed

Goal: Bring resources created by hand under OpenTofu, rename resources without rebuilding them, and release resources from management without deleting them. · Duration: approx. 75 min · Prerequisite: Day 9

Briefing

  • Legacy resources are everywhere: resources someone created by hand before OpenTofu. An import block records them in the state. After that, OpenTofu manages them like ones it built itself.
  • tofu plan -generate-config-out=datei.tf writes a configuration suggestion for each import. It’s a rough draft – you have to clean it up yourself.
  • A moved block tells OpenTofu: “This resource has a different name now.” Without it, OpenTofu plans a delete and a recreate.
  • A removed block takes a resource out of the state. With destroy = false it stays in place in the real world.
 by hand         import          moved             removed
 ─────────►  [ State ]  ───►  [ new name ]    ───►  no longer managed
 docker volume create          same resource         resource stays

Drill 1: Creating Legacy Resources by Hand

This is what it looks like when someone was at work before you:

docker network create altnetz
docker volume create altdaten
docker run -d --name altweb --network altnetz -v altdaten:/usr/share/nginx/html \
  -p 127.0.0.1:8099:80 nginx:1.31.8-alpine
docker exec altweb sh -c 'echo "Altdaten von Hand" > /usr/share/nginx/html/index.html'
curl -s http://127.0.0.1:8099/

Expected (the IDs differ):

0657c4de822c...
altdaten
93aefacb57ba...
Altdaten von Hand

Save your progress? Sign up for free

Drill 2: Import with Generated Configuration

mkdir -p ~/tf-lab/tag11 && cd ~/tf-lab/tag11
sed 's|tag05/terraform.tfstate|tag11/terraform.tfstate|' ~/tf-lab/tag05/backend.tf \
  > backend.tf
cp ~/tf-lab/tag05/versions.tf .
NETZ_ID=$(docker network ls -q --no-trunc --filter name=^altnetz$)
cat > import.tf <<EOF
provider "docker" {}

import {
  to = docker_volume.altdaten
  id = "altdaten"
}

import {
  to = docker_network.altnetz
  id = "$NETZ_ID"
}
EOF
tofu init -no-color >/dev/null
tofu plan -generate-config-out=generated.tf -no-color | grep -E 'Warning|Plan:'
cat generated.tf

Expected (gateway and subnet may differ):

Plan: 2 to import, 0 to add, 0 to change, 0 to destroy.
Warning: Config generation is experimental
# __generated__ by OpenTofu
# Please review these resources and move them into your main configuration files.
# __generated__ by OpenTofu from "altdaten"
resource "docker_volume" "altdaten" {
  driver      = "local"
  driver_opts = {}
  name        = "altdaten"
}
# __generated__ by OpenTofu from "0657c4de822c..."
resource "docker_network" "altnetz" {
  attachable   = false
  driver       = "bridge"
...
  ipam_config {
    aux_address = {}
    gateway     = "172.28.0.1"
    ip_range    = ""
    subnet      = "172.28.0.0/16"
  }
}
  • The ID depends on the resource type: for the volume it’s the name, for the network the full ID. Which ID a type expects is in the provider docs under Import.
  • The generated code spells out every attribute, including defaults. For volume and network that’s harmless; you’ll clean it up in Drill 4.

First import, then check that nothing is left to do:

tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu plan -no-color | tail -1
tofu state list

Expected:

Apply complete! Resources: 2 imported, 0 added, 0 changed, 0 destroyed.
No changes. Your infrastructure matches the configuration.
docker_network.altnetz
docker_volume.altdaten

An import is only done when the plan afterwards is empty. You can leave the import blocks in place – they no longer have any effect on resources already imported. Many teams delete them after the merge to keep the code tidy.

Save your progress? Sign up for free

Drill 3: The Container Trap

Now the container. The procedure is the same:

WEB_ID=$(docker ps -q --no-trunc --filter name=^altweb$)
cat > import-web.tf <<EOF
import {
  to = docker_container.altweb
  id = "$WEB_ID"
}
EOF
tofu plan -generate-config-out=web.tf -no-color 2>&1 | grep -m1 '^Error'
grep -n 'cpu_set' web.tf
wc -l < web.tf

Expected:

Error: '' doesn't match the pattern '^\d+([,-]\d+)*$'
13:  cpu_set                                     = ""
64

The suggestion for the container has over 60 lines and isn’t even valid. So you write the configuration yourself, with only what really matters:

cat > web.tf <<'EOF'
resource "docker_container" "altweb" {
  name  = "altweb"
  image = "nginx:1.31.8-alpine"
  networks_advanced {
    name = docker_network.altnetz.id
  }
  volumes {
    volume_name    = docker_volume.altdaten.name
    container_path = "/usr/share/nginx/html"
  }
  ports {
    internal = 80
    external = 8099
    ip       = "127.0.0.1"
  }
}
EOF
tofu plan -no-color > plan.txt
grep -E '^      [~+-] [a-z_]+ .*forces replacement' plan.txt | tr -s ' '
grep 'Plan:' plan.txt

Expected:

 + env = (known after apply) # forces replacement
 ~ network_mode = "altnetz" -> "bridge" # forces replacement
 + networks_advanced { # forces replacement
 + ports { # forces replacement
 + volumes { # forces replacement
Plan: 1 to import, 1 to add, 0 to change, 1 to destroy.

Read the last line carefully: “1 to import, 1 to add, 1 to destroy”. OpenTofu would import the container and replace it immediately. On import, the Docker provider doesn’t read back all container attributes – gaps remain that force a replacement.

Here that’s acceptable: the container holds no data; the page lives in the volume. With a database VM, you would abort at this point. This container gets replaced:

tofu apply -auto-approve -no-color | grep 'Apply complete'
curl -s http://127.0.0.1:8099/
tofu plan -no-color | tail -1

Expected:

Apply complete! Resources: 1 imported, 1 added, 0 changed, 1 destroyed.
Altdaten von Hand
No changes. Your infrastructure matches the configuration.

The container is new; the data in the volume has stayed.

Save your progress? Sign up for free

Drill 4: Cleaning Up and Renaming with moved

The names altdaten and altnetz no longer fit. In the code they should be called daten and netz – the real Docker names stay. First without moved:

rm generated.tf import.tf import-web.tf plan.txt
cat > daten.tf <<'EOF'
resource "docker_volume" "daten" {
  name = "altdaten"
}
EOF
cat > netz.tf <<'EOF'
resource "docker_network" "netz" {
  name = "altnetz"
  ipam_config {
    subnet  = "172.28.0.0/16"
    gateway = "172.28.0.1"
  }
}
EOF
printf 'provider "docker" {}\n' > provider.tf
sed -i 's/docker_network.altnetz/docker_network.netz/' web.tf
sed -i 's/docker_volume.altdaten/docker_volume.daten/' web.tf
tofu plan -no-color | grep -E 'will be (created|destroyed)|Plan:'

Expected:

  # docker_network.altnetz will be destroyed
  # docker_network.netz will be created
  # docker_volume.altdaten will be destroyed
  # docker_volume.daten will be created
Plan: 3 to add, 0 to change, 3 to destroy.

For OpenTofu, a new name is a new resource. The volume and its data would be gone – and the container would be replaced along with it. A moved block prevents that:

cat > moved.tf <<'EOF'
moved {
  from = docker_volume.altdaten
  to   = docker_volume.daten
}

moved {
  from = docker_network.altnetz
  to   = docker_network.netz
}
EOF
tofu plan -no-color | grep -E 'has moved|Plan:|No changes'

If the values match, the plan only reports the rename (take subnet and gateway from your run in Drill 2 if they differ):

  # docker_network.altnetz has moved to docker_network.netz
  # docker_volume.altdaten has moved to docker_volume.daten
Plan: 0 to add, 0 to change, 0 to destroy.
tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu state list

Expected:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
docker_container.altweb
docker_network.netz
docker_volume.daten
  • moved also works for modules (module.alt → module.neu) and for switching from count to for_each (docker_volume.x[0] → docker_volume.x["a"]).
  • The block stays as long as a state with the old name still exists somewhere – for a module that other teams use, across several versions.
  • tofu state mv does the same on the command line but leaves no trace in the code. A moved block goes through review and plan like any other change.

Save your progress? Sign up for free

Drill 5: Releasing from Management with removed

From now on, the platform team is to manage the network. You take it out of your state without deleting it. The container still needs the network ID, though. From now on, a data source provides it – it reads, but doesn’t manage:

sed -i 's/docker_network.netz.id/data.docker_network.netz.id/' web.tf
cat > netz.tf <<'EOF'
data "docker_network" "netz" {
  name = "altnetz"
}
EOF
cat > moved.tf <<'EOF'
moved {
  from = docker_volume.altdaten
  to   = docker_volume.daten
}
EOF
cat > removed.tf <<'EOF'
removed {
  from = docker_network.netz
  lifecycle {
    destroy = false
  }
}
EOF
tofu plan -no-color | grep -oE 'docker_network.netz will be removed.*|Plan:.*'

Expected:

docker_network.netz will be removed from the OpenTofu state but will not be destroyed
Plan: 0 to add, 0 to change, 0 to destroy, 1 to forget.

“1 to forget” is the new category: out of the state, the resource stays.

tofu apply -auto-approve -no-color | grep 'Apply complete'
tofu state list
docker network ls --format '{{.Name}}' | grep altnetz

Expected:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed, 1 forgotten.
data.docker_network.netz
docker_container.altweb
docker_volume.daten
altnetz

The data source is in the state too – it is read again on every plan.

Without lifecycle { destroy = false }, OpenTofu would delete the network – removed is then just an explicit way to get rid of a resource.

Save your progress? Sign up for free

Checkpoint

cd ~/tf-lab/tag11 && tofu plan -no-color | tail -1

Expected:

No changes. Your infrastructure matches the configuration.
tofu state list | grep -c '^docker_'

Expected: container and volume, but no longer the network.

2
curl -s http://127.0.0.1:8099/

Expected:

Altdaten von Hand

Challenge

Create another volume fremd by hand and take it over – this time with the command-line tofu import instead of a block. The plan must be empty afterwards.

Hint: tofu import needs the resource to already be in the configuration.

Solution

cd ~/tf-lab/tag11
docker volume create fremd
cat > fremd.tf <<'EOF'
resource "docker_volume" "fremd" {
  name = "fremd"
}
EOF
tofu import -no-color docker_volume.fremd fremd | grep 'Import successful'
tofu plan -no-color | tail -1

Expected:

fremd
Import successful!
No changes. Your infrastructure matches the configuration.

tofu import changes the state immediately, without a plan and without review. That’s why the import block is the better way in a team – it goes through pull request and plan.

Save your progress? Sign up for free

Enterprise Note

  • Import in stages: Large legacy estates are taken over resource by resource, with an empty plan after each step. An import that replaces something “along the way” is an outage.
  • Never adopt generated code unreviewed: It hard-codes defaults and runtime details. Trimmed-down code of your own is more readable and copes better with provider updates.
  • Refactoring without an outage: moved and removed make restructuring in the code reviewable. They belong in the same pull request as the rename itself.