Terraform in Practice / Terraform Core Workflow

Write and apply your first configuration

Lesson 5 of 35. Open to read. No account needed.

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 runIn the configuration
--namename
The image nameimage
-text="..." after the imagecommand
-p 127.0.0.1:18080:5678ports block: ip, external, internal

Three values deserve a closer look.

  • image = docker_image.app.image_id is 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.
  • command is a list of strings. This image's entrypoint is the http-echo program itself, so the list becomes the program's arguments, just like the words after the image name in docker run.
  • The ports block publishes container port 5678 as port 18080 on your computer. Without ip = "127.0.0.1", the provider's default is 0.0.0.0, every network address of your computer, so other devices could reach the app. Without external, Docker would pick a random high port.

What Each Command Does

  • terraform init prepares the working directory by downloading the providers listed in required_providers. It creates .terraform/ and .terraform.lock.hcl.
  • terraform fmt rewrites your .tf files in the standard layout and prints the names of the files it changed. Only the layout changes.
  • terraform validate checks that the configuration makes sense on its own: syntax, names, references and value types. It changes nothing and does not contact Docker.
  • terraform plan proposes actions, as in the previous lesson. It changes nothing.
  • terraform apply plans, asks for approval, then makes the changes in Docker and records them in the state file.
  • terraform destroy plans 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.

  1. 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"
      }
    }
    EOF
    

    This block writes the file with a construction called a here document. Everything between the line cat > main.tf <<'EOF' and the line EOF is written into main.tf, replacing any previous content. The quotes around the first EOF keep the text exactly as written. Copy the whole block, from mkdir to the closing EOF.

    The container block is written slightly untidily on purpose, with its equals signs not lined up, so that step 3 has something to tidy.

  2. Initialise the working directory:

    terraform init
    ls -a
    

    Illustrative 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-signed means the provider is signed by its own developers rather than by HashiCorp: kreuzwerker/docker is 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.hcl and main.tf.

  3. Tidy and check the configuration:

    terraform fmt
    terraform fmt
    terraform validate
    

    The first terraform fmt prints main.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 validate prints Success! The configuration is valid.

  4. Before you plan, predict: how many resources will be created, and which values can Terraform not know yet? Then run:

    terraform plan
    

    Illustrative 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.

  5. Apply the change:

    terraform apply
    

    Terraform 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 yes and 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.

  6. Check the result:

    curl http://127.0.0.1:18080/
    docker ps --filter name=tfp-first
    terraform state list
    ls -a
    

    curl prints hello from Terraform. docker ps shows the running container tfp-first-app with 127.0.0.1:18080->5678/tcp under 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 list prints the two resource addresses, docker_container.app and docker_image.app. ls -a now also shows terraform.tfstate.

  7. Plan again without changing anything:

    terraform plan
    

    It ends with No changes. Your infrastructure matches the configuration. This is the normal resting state: the configuration, state and Docker agree.

  8. Destroy everything this configuration created:

    terraform destroy
    

    Terraform plans to destroy both resources (Plan: 0 to add, 0 to change, 2 to destroy.) and asks Do you really want to destroy all resources?, warning that there is no undo. Type yes. Then check:

    docker ps -a --filter name=tfp-first
    curl http://127.0.0.1:18080/
    echo $?
    docker image ls hashicorp/http-echo
    

    No tfp-first-app container is listed, curl fails to connect and exit code 7 confirms it, and the image is still listed because of keep_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 seeLikely causeNext step
Error: Unsupported Terraform Core version from initTerraform older than 1.16Update it as in install-the-toolchain
init stops with an error after Finding kreuzwerker/docker versionsTerraform cannot reach the provider registryCheck your internet connection or proxy, then rerun terraform init
Error: Invalid multi-line string or Unterminated template stringA quote is missing in main.tfCompare 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 commandStart Docker, then repeat the engine check in install-the-toolchain
Error: Unable to start container ... port is already allocatedSomething else publishes port 18080Find 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 useA container with that name exists outside this folder's state, perhaps from an earlier attemptCheck 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 typedRun the command again and type yes in full
curl fails just after applyThe app has not started listening yetWait a second and try again
The second plan shows changesThe container was changed outside Terraform, or the file was editedCheck 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

  1. Which two things did terraform init create, and which of them belongs in version control?
  2. Why does the container use image = docker_image.app.image_id instead of the text "hashicorp/http-echo:1.0"?
  3. What does (known after apply) mean in a plan?
  4. After terraform destroy, docker image ls still lists hashicorp/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

  1. 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 by terraform init.
  2. 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.
  3. The value is decided by Docker when the object is created, such as an ID, so Terraform cannot know it during planning.
  4. keep_locally = true tells the provider to leave the image in Docker on destroy. Terraform removed it from state, but not from Docker.

References

30 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 99 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy