What You Will Build
In the Docker lesson you started the practice app with one long docker run
command. Now you will describe the same app in a Terraform configuration and
let Terraform create it, check it, and remove it again. By the end you will
have run every command in the core workflow, init, fmt, validate,
plan, apply and destroy, and seen what each one changes.
How Terraform Reads Your Files
Terraform works on one folder at a time, called the working directory: the
folder you are in when you run terraform. It reads every file in that folder
whose name ends in .tf and treats them together as one configuration. File
names are for people; main.tf is the usual name for the main file.
The files are written in HCL, the HashiCorp Configuration Language. It is built from blocks and arguments:
resource "docker_container" "app" {
name = "tfp-first-app"
}
This is an illustrative fragment. resource is the block's type. The two
quoted words are labels: for a resource, the first is the resource type,
docker_container, defined by the Docker provider, and the second, app, is a
name you choose for use inside your configuration. Together they form the
resource's address, docker_container.app. Inside the braces,
name = "tfp-first-app" is an argument: a name, an equals sign and a
value. Text values go in double quotes; numbers do not; lists go in square
brackets; and some settings are nested blocks with braces of their own. A #
starts a comment.
The Configuration
This is the complete main.tf for the exercise:
terraform {
required_version = ">= 1.16.0"
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 4.6"
}
}
}
provider "docker" {}
resource "docker_image" "app" {
name = "hashicorp/http-echo:1.0"
keep_locally = true
}
resource "docker_container" "app" {
name = "tfp-first-app"
image = docker_image.app.image_id
command = ["-text=hello from Terraform"]
ports {
internal = 5678
external = 18080
ip = "127.0.0.1"
}
}
The terraform block
This block configures Terraform itself. required_version = ">= 1.16.0" makes
older versions of Terraform refuse to run this configuration, with a clear
error, instead of failing in a confusing way later.
required_providers lists the providers the configuration needs. Here, the
local name docker refers to the provider at kreuzwerker/docker in the
public Terraform Registry. version = "~> 4.6" accepts 4.6 and any later
4.x release, but not 5.0, which could contain breaking changes. The lesson on
versions explains constraints fully.
The provider block
provider "docker" {} configures the Docker provider. It is empty, so the
provider uses its defaults: the address in DOCKER_HOST or, if that is not
set, unix:///var/run/docker.sock. That is why the installation lesson checked
that Terraform and the docker command use the same engine.
The image
docker_image.app makes sure the image hashicorp/http-echo:1.0 is present,
downloading it if needed. keep_locally = true means that when you destroy
this configuration, Terraform forgets the image but leaves it in Docker. Every
exercise in this module uses the same image, so this saves downloading it
again.
The container
docker_container.app is the running app. Compare it with the command from the
Docker lesson:
In docker run | In the configuration |
|---|---|
--name | name |
| The image name | image |
-text="..." after the image | command |
-p 127.0.0.1:18080:5678 | ports block: ip, external, internal |
Three values deserve a closer look.
image = docker_image.app.image_idis a reference to an attribute of the image resource: the ID Docker gives the image once it has been downloaded. The provider's documentation recommends exactly this. Because of the reference, Terraform knows the image must exist before the container is created, and the container always runs the exact image Terraform pulled.commandis a list of strings. This image's entrypoint is thehttp-echoprogram itself, so the list becomes the program's arguments, just like the words after the image name indocker run.- The
portsblock publishes container port 5678 as port 18080 on your computer. Withoutip = "127.0.0.1", the provider's default is0.0.0.0, every network address of your computer, so other devices could reach the app. Withoutexternal, Docker would pick a random high port.
What Each Command Does
terraform initprepares the working directory by downloading the providers listed inrequired_providers. It creates.terraform/and.terraform.lock.hcl.terraform fmtrewrites your.tffiles in the standard layout and prints the names of the files it changed. Only the layout changes.terraform validatechecks that the configuration makes sense on its own: syntax, names, references and value types. It changes nothing and does not contact Docker.terraform planproposes actions, as in the previous lesson. It changes nothing.terraform applyplans, asks for approval, then makes the changes in Docker and records them in the state file.terraform destroyplans to destroy everything in state, asks for approval, then destroys it and updates the state file.
init leaves two things behind. .terraform/ holds the downloaded provider; it
is recreated whenever you run init, so you never edit or share it.
.terraform.lock.hcl, the dependency lock file, records exactly which
provider version was selected, with checksums of its files. It belongs in
version control so that everyone gets the same provider; the versions lesson
explains it.
apply creates a third file, terraform.tfstate. This is the state from the
previous lesson, stored in the working directory because nothing has told
Terraform to store it anywhere else. Do not edit it, and do not commit it to
version control; the state lessons explain why and where it should live
instead.
Exercise: Deploy and Remove One Container
You will write the configuration, run every workflow command, check the result, and then remove everything.
Starting state: the toolchain from install-the-toolchain, including the
check that Terraform and the docker command use the same Docker engine.
Port 18080 must be free: curl http://127.0.0.1:18080/ should fail to connect.
No container named tfp-first-app should exist:
docker ps -a --filter name=tfp-first shows only its heading line.
-
Create the exercise folder and the configuration file:
mkdir -p ~/terraform-practice/first-apply cd ~/terraform-practice/first-apply cat > main.tf <<'EOF' terraform { required_version = ">= 1.16.0" required_providers { docker = { source = "kreuzwerker/docker" version = "~> 4.6" } } } provider "docker" {} resource "docker_image" "app" { name = "hashicorp/http-echo:1.0" keep_locally = true } resource "docker_container" "app" { name = "tfp-first-app" image = docker_image.app.image_id command = ["-text=hello from Terraform"] ports { internal = 5678 external = 18080 ip = "127.0.0.1" } } EOFThis block writes the file with a construction called a here document. Everything between the line
cat > main.tf <<'EOF'and the lineEOFis written intomain.tf, replacing any previous content. The quotes around the firstEOFkeep the text exactly as written. Copy the whole block, frommkdirto the closingEOF.The container block is written slightly untidily on purpose, with its equals signs not lined up, so that step 3 has something to tidy.
-
Initialise the working directory:
terraform init ls -aIllustrative output, shortened:
Initializing provider plugins... - Finding kreuzwerker/docker versions matching "~> 4.6"... - Installing kreuzwerker/docker v4.6.0... - Installed kreuzwerker/docker v4.6.0 (self-signed, key ID 0DCE698927DAF8EC) Partner and community providers are signed by their developers. ... Terraform has created a lock file .terraform.lock.hcl to record the provider selections it made above. ... Terraform has been successfully initialized!self-signedmeans the provider is signed by its own developers rather than by HashiCorp:kreuzwerker/dockeris a community provider. The version may be newer than 4.6.0 if a later 4.x release exists.ls -a, which also lists names starting with a dot, now shows.terraform,.terraform.lock.hclandmain.tf. -
Tidy and check the configuration:
terraform fmt terraform fmt terraform validateThe first
terraform fmtprintsmain.tf, the file it rewrote; open it and the equals signs in the container block now line up. The second prints nothing, because there is nothing left to tidy.terraform validateprintsSuccess! The configuration is valid. -
Before you plan, predict: how many resources will be created, and which values can Terraform not know yet? Then run:
terraform planIllustrative output, shortened:
# docker_container.app will be created + resource "docker_container" "app" { + command = [ + "-text=hello from Terraform", ] + id = (known after apply) ... + name = "tfp-first-app" ... + ports { + external = 18080 + internal = 5678 + ip = "127.0.0.1" + protocol = "tcp" } } # docker_image.app will be created + resource "docker_image" "app" { + id = (known after apply) + image_id = (known after apply) + keep_locally = true + name = "hashicorp/http-echo:1.0" + repo_digest = (known after apply) } Plan: 2 to add, 0 to change, 0 to destroy.Both resources are marked
+.(known after apply)marks values Docker decides only when the object is created, such as IDs, so Terraform cannot show them yet. The real plan also lists many container settings with their defaults; the...marks lines left out here.protocol = "tcp"is one of those defaults. -
Apply the change:
terraform applyTerraform shows the same plan, then asks:
Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value:Type
yesand press Enter. Illustrative output:docker_image.app: Creating... docker_image.app: Creation complete after 1s [id=sha256:fcb75f691c8b...hashicorp/http-echo:1.0] docker_container.app: Creating... docker_container.app: Creation complete after 0s [id=8182455a322e...] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.The image is created before the container, because of the reference between them. The IDs will differ on your computer.
-
Check the result:
curl http://127.0.0.1:18080/ docker ps --filter name=tfp-first terraform state list ls -acurlprintshello from Terraform.docker psshows the running containertfp-first-appwith127.0.0.1:18080->5678/tcpunder PORTS; its IMAGE column shows the start of the image's ID rather than its name, because the container was created from the ID.terraform state listprints the two resource addresses,docker_container.appanddocker_image.app.ls -anow also showsterraform.tfstate. -
Plan again without changing anything:
terraform planIt ends with
No changes. Your infrastructure matches the configuration.This is the normal resting state: the configuration, state and Docker agree. -
Destroy everything this configuration created:
terraform destroyTerraform plans to destroy both resources (
Plan: 0 to add, 0 to change, 2 to destroy.) and asksDo you really want to destroy all resources?, warning that there is no undo. Typeyes. Then check:docker ps -a --filter name=tfp-first curl http://127.0.0.1:18080/ echo $? docker image ls hashicorp/http-echoNo
tfp-first-appcontainer is listed,curlfails to connect and exit code7confirms it, and the image is still listed because ofkeep_locally = true.
Success: the app answered hello from Terraform while it existed; a plan
with no edits reported no changes; after destroy, no tfp-first-app
container remains and port 18080 is free again.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
Error: Unsupported Terraform Core version from init | Terraform older than 1.16 | Update it as in install-the-toolchain |
init stops with an error after Finding kreuzwerker/docker versions | Terraform cannot reach the provider registry | Check your internet connection or proxy, then rerun terraform init |
Error: Invalid multi-line string or Unterminated template string | A quote is missing in main.tf | Compare with the configuration above, or rerun step 1 |
apply fails with failed to create Docker client ... Cannot connect to the Docker daemon (plan may still have worked) | Docker is not running, or Terraform uses a different engine from the docker command | Start Docker, then repeat the engine check in install-the-toolchain |
Error: Unable to start container ... port is already allocated | Something else publishes port 18080 | Find it with docker ps and stop it if it is yours, then run terraform apply again. The plan says docker_container.app is tainted, so must be replaced: Terraform recorded the container that could not start and now replaces it |
Error: Unable to create container ... The container name "/tfp-first-app" is already in use | A container with that name exists outside this folder's state, perhaps from an earlier attempt | Check it with docker ps -a --filter name=tfp-first; it is a practice container, so remove it with docker rm -f tfp-first-app, then apply again |
Apply cancelled. or Destroy cancelled. | Anything other than yes was typed | Run the command again and type yes in full |
curl fails just after apply | The app has not started listening yet | Wait a second and try again |
| The second plan shows changes | The container was changed outside Terraform, or the file was edited | Check docker ps; read the plan lines to see what differs |
Independent task: with the exercise folder still in place, run
terraform apply again to recreate the app. Then open main.tf in your
editor, change hello from Terraform to hello again and save. Before running
anything, write down the plan you expect: the action for each resource, the
line that causes it, and the summary counts. Then run terraform plan and
compare, apply the change, check it with curl, and finish with
terraform destroy.
Cleanup: after the independent task, make sure terraform destroy has
run, then remove the exercise folder:
cd ~/terraform-practice
ls
rm -rf first-apply
ls
Check that the first ls lists first-apply before removing it. The image
hashicorp/http-echo:1.0 stays in Docker for the next lessons.
Check Your Understanding
- Which two things did
terraform initcreate, and which of them belongs in version control? - Why does the container use
image = docker_image.app.image_idinstead of the text"hashicorp/http-echo:1.0"? - What does
(known after apply)mean in a plan? - After
terraform destroy,docker image lsstill listshashicorp/http-echo. Why?
Answer and Reasoning
Independent task
The image is unchanged, so it has no action. The container must be replaced,
because the reply text is part of its command, which cannot change on an
existing container. The plan shows:
# docker_container.app must be replaced
-/+ resource "docker_container" "app" {
~ command = [ # forces replacement
~ "-text=hello from Terraform" -> "-text=hello again",
...
Plan: 1 to add, 0 to change, 1 to destroy.
1 to add and 1 to destroy are the two halves of one replacement. After
apply, curl http://127.0.0.1:18080/ prints hello again. terraform destroy then removes both resources from state, leaving the image in Docker.
Understanding check
- The
.terraform/folder, holding the downloaded provider, and the dependency lock file.terraform.lock.hcl. The lock file belongs in version control, so everyone uses the same provider version;.terraform/is recreated byterraform init. - The reference makes Terraform create the image first and gives the container the exact ID of the image Terraform pulled. With plain text, Terraform would see no relationship between the two resources and might try to create the container before the image is ready.
- The value is decided by Docker when the object is created, such as an ID, so Terraform cannot know it during planning.
keep_locally = truetells the provider to leave the image in Docker on destroy. Terraform removed it from state, but not from Docker.
References
- S10: terraform block reference
- S11: provider block reference
- S12: resource block reference
- S35: Version constraints
- S38: Dependency lock file
- S50: local backend
- S63: terraform init
- S64: terraform plan
- S65: terraform apply
- S66: terraform fmt
- S67: terraform validate
- S73: terraform state commands
- S85: kreuzwerker/docker 4.6.0: docker_container
- S86: kreuzwerker/docker 4.6.0: docker_image