It is time to write code and run it. In this lesson EcoMarket's platform team will build its first complete Terraform configuration, end to end, and walk through the whole lifecycle: init, fmt, validate, plan, apply, a modification with its update plan, output, show and finally destroy. We will do it with the hashicorp/local and hashicorp/random providers, which require no cloud account, no credentials and no credit card: everything happens on your own disk. That way you can concentrate on the workflow and on learning to read each command's output, which is exactly the skill you will need when we start deploying to AWS, Azure and GCP in module 5.

  1. What we are going to build

EcoMarket wants to start with something modest but useful: an inventory file documenting the deployed environment, with a random suffix that guarantees unique names. When we get to the cloud, that same suffix will name buckets, whose names must be globally unique.

The result will be:

  • A random suffix generated by random_pet, stable between runs (it is stored in the state).
  • A random hexadecimal identifier generated by random_id, for names that do not accept words.
  • A file ecomarket-inventory.json with the environment's metadata: project, environment, region, name prefix, common tags and the list of planned resources.
flowchart LR
    V["variable<br/>environment, region,<br/>project"] --> M["local_file<br/>ecomarket-inventory.json"]
    RP["random_pet<br/>suffix"] --> M
    RI["random_id<br/>suffix_hex"] --> M
    M --> O["outputs<br/>path, suffix,<br/>name_prefix"]

It is deliberately small: the goal is not infrastructure complexity but mastering the workflow.

  1. File naming conventions

Terraform loads every .tf file in the directory and treats them as if they were one. The order does not matter and neither do the names: you could put everything in a single terraform.tf. But there is a widely accepted convention that makes the code readable to anyone:

File What it holds Required?
versions.tf The terraform block with required_version and required_providers Strongly recommended
providers.tf The provider blocks and their configuration Recommended
main.tf The main resources (resource, data, module) Yes, by convention
variables.tf Input variable declarations (variable) If there are variables
outputs.tf Output values (output) If there are outputs
terraform.tfvars The actual values of the variables Optional
locals.tf Local values (locals), if there are many Optional
.terraform.lock.hcl Generated by init; it is versioned Automatic

Two common confusions worth clearing up right now:

  • variables.tf declares, terraform.tfvars assigns. The first says "there is a variable called environment of type string"; the second says "and its value is dev".
  • versions.tf and providers.tf can be merged in small projects. We keep them separate because that is what you will see in professional repositories and because the terraform block is usually what changes when you upgrade versions.

We will work in the directory we prepared in the lesson Installing Terraform:

$ cd ~/projects/ecomarket-infra/infra
$ pwd
/home/dev/projects/ecomarket-infra/infra

  1. versions.tf: the terraform block

The terraform block configures Terraform itself: which binary version is required and which providers are needed. It is the only block that does not describe infrastructure.

# versions.tf

terraform {
  # Minimum binary version supported. If anyone on the team runs
  # an older version, Terraform will stop with a clear error
  # instead of failing strangely further down the line.
  required_version = ">= 1.5.0"

  required_providers {
    # "local" and "random" are the SHORT NAMES we will use for
    # each provider throughout the rest of the configuration.
    local = {
      source  = "hashicorp/local"  # namespace / type in the registry
      version = "~> 2.5"           # >= 2.5.0 and < 3.0.0
    }

    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"           # >= 3.6.0 and < 4.0.0
    }
  }
}

Important details:

  • source has been mandatory since Terraform 0.13. Without it, Terraform does not know where to download the provider from (the value hashicorp/local expands to registry.terraform.io/hashicorp/local).
  • version is not mandatory, but omitting it means "whatever the latest is", and that makes the plan liable to change overnight. Always pin a constraint.
  • required_version accepts the same operators (>=, ~>, !=) and allows several comma-separated conditions: ">= 1.5.0, < 2.0.0".

  1. providers.tf: the provider block

The provider block configures how a provider behaves: credentials, region, endpoints. Our two providers need no configuration at all, but we declare the blocks anyway so the project has a natural home for them when we add AWS in module 5.

# providers.tf

# The "local" provider manipulates files on the local file system.
# It has no configuration arguments.
provider "local" {}

# The "random" provider generates random values and keeps them in the state
# so they do not change on every run.
provider "random" {}

# From module 5 onwards this file will contain something like:
#
# provider "aws" {
#   region = var.region   # eu-west-1
#   default_tags {
#     tags = local.common_tags
#   }
# }

A useful nuance: if a provider needs no configuration, you can leave the provider block out entirely; Terraform instantiates it with default values. We include it as documentation.

  1. variables.tf and terraform.tfvars

Variables let the same code serve dev, staging and prod by changing only the values. Here we use the bare minimum needed to run; complex types, validations, sensitive values and .auto.tfvars files are the subject of Variables and Outputs.

# variables.tf

variable "project" {
  description = "Project name, used as a prefix for every resource."
  type        = string
  default     = "ecomarket"
}

variable "environment" {
  description = "Deployment environment: dev, staging or prod."
  type        = string
  default     = "dev"
}

variable "region" {
  description = "Region where EcoMarket's infrastructure will be deployed."
  type        = string
  default     = "eu-west-1"
}

Each declaration has three parts:

  • description: documents the variable. It shows up in interactive prompts and in auto-generated documentation. In practice it is not optional: a professional repository has one on every variable.
  • type: the expected type. If someone passes a number where a string is expected, Terraform warns before touching anything.
  • default: the value used if nobody assigns another. A variable without a default is required, and Terraform will either prompt for it or fail in CI.

And the actual values for this environment:

# terraform.tfvars

project     = "ecomarket"
environment = "dev"
region      = "eu-west-1"

Terraform loads the terraform.tfvars file automatically if it exists in the directory; you do not have to point at it. For another environment you would just run terraform plan -var-file=prod.tfvars.

  1. main.tf: the resources

Here is the heart of the configuration.

# main.tf

# ---------------------------------------------------------------------------
# Local values: constants computed from the variables.
# They stop us repeating the same expression in several places.
# ---------------------------------------------------------------------------
locals {
  # EcoMarket's name prefix: ecomarket-dev-...
  prefix = "${var.project}-${var.environment}"

  # Tags common to all of the project's infrastructure.
  common_tags = {
    Project     = var.project
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

# ---------------------------------------------------------------------------
# Readable random suffix, along the lines of "cheerful-mammoth".
# random_pet generates the value ONCE and stores it in the state: on
# subsequent runs it returns the same one, which is why it is stable.
# ---------------------------------------------------------------------------
resource "random_pet" "suffix" {
  length    = 2    # two words
  separator = "-"  # joined by a hyphen

  # "keepers" defines when the value must be REGENERATED: if any of these
  # values changes, Terraform destroys the resource and creates it again.
  # That way each environment gets its own suffix.
  keepers = {
    environment = var.environment
  }
}

# ---------------------------------------------------------------------------
# Random hexadecimal identifier, for names that do not accept words
# (for instance, the global name of an object storage bucket).
# ---------------------------------------------------------------------------
resource "random_id" "suffix_hex" {
  byte_length = 4  # 4 bytes -> 8 hexadecimal characters

  keepers = {
    environment = var.environment
  }
}

# ---------------------------------------------------------------------------
# The inventory file. It documents what has been deployed and under what names.
# ---------------------------------------------------------------------------
resource "local_file" "inventory" {
  # path.module is the path of the directory this configuration lives in.
  filename = "${path.module}/${local.prefix}-inventory.json"

  # jsonencode turns an HCL object into a properly formatted JSON string.
  # It is far safer than building the JSON by hand through concatenation.
  content = jsonencode({
    project           = var.project
    environment       = var.environment
    region            = var.region
    name_prefix       = local.prefix
    unique_suffix     = random_pet.suffix.id
    suffix_hex        = random_id.suffix_hex.hex
    tags              = local.common_tags
    generated_by      = "terraform"

    # Resources EcoMarket will actually deploy from module 5 onwards.
    planned_resources = [
      "${local.prefix}-web",
      "${local.prefix}-lb",
      "${local.prefix}-db",
      "${local.prefix}-images-${random_id.suffix_hex.hex}",
    ]
  })

  # The file's permissions on the file system (octal notation).
  file_permission = "0644"
}

Points that deserve attention:

  1. locals is not an input variable: it is a constant computed inside the configuration. It cannot be overridden from outside. It is referenced as local.prefix (singular, even though the block is locals).
  2. keepers is an argument specific to the random providers. Without it, the random value would never be regenerated even if you changed environment, and dev and prod would share a suffix.
  3. jsonencode takes an HCL object and returns a JSON string. If you wrote the JSON by hand instead, any misplaced quote or comma would produce an invalid file.
  4. path.module guarantees the file is written next to the configuration, not in whichever directory you happen to run the command from.
  5. Two implicit dependencies are created: local_file.inventory references random_pet.suffix and random_id.suffix_hex, so both will be created first.

  1. outputs.tf: the output values

Outputs expose values from the configuration so you can query them later, or so other systems can consume them.

# outputs.tf

output "inventory_path" {
  description = "Path of the generated inventory file."
  value       = local_file.inventory.filename
}

output "unique_suffix" {
  description = "Readable random suffix assigned to this environment."
  value       = random_pet.suffix.id
}

output "suffix_hex" {
  description = "Hexadecimal suffix for globally unique names."
  value       = random_id.suffix_hex.hex
}

output "name_prefix" {
  description = "Prefix used to name every resource in the environment."
  value       = local.prefix
}

output "images_bucket_name" {
  description = "Name the product images bucket will have."
  value       = "${local.prefix}-images-${random_id.suffix_hex.hex}"
}

Every output has a name, a description and a value, which can be any expression. The value is stored in the state and shown at the end of an apply or when you run terraform output.

  1. terraform init step by step

With the five files written, we initialise the working directory:

$ terraform init

Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/local versions matching "~> 2.5"...
- Finding hashicorp/random versions matching "~> 3.6"...
- Installing hashicorp/local v2.5.2...
- Installed hashicorp/local v2.5.2 (signed by HashiCorp)
- Installing hashicorp/random v3.6.3...
- Installed hashicorp/random v3.6.3 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work except that this configuration has not been detected as
requiring any changes.

What it did, line by line:

Message What it means
Initializing the backend... Configures where the state is stored. As we declared no backend, it uses the local one (terraform.tfstate in this directory). Remote backends are module 3
Finding hashicorp/local versions matching "~> 2.5" Queries the registry to see which versions satisfy the constraint
Installing hashicorp/local v2.5.2 Downloads the provider binary
(signed by HashiCorp) Verifies the package's cryptographic signature. If it failed, init would abort
Terraform has created a lock file Writes .terraform.lock.hcl with versions and hashes, and reminds you to version it

And this is what appeared on disk:

$ ls -a
.  ..  .terraform  .terraform.lock.hcl  main.tf  outputs.tf
providers.tf  terraform.tfvars  variables.tf  versions.tf

$ tree .terraform
.terraform
└── providers
    └── registry.terraform.io
        └── hashicorp
            ├── local
            │   └── 2.5.2
            │       └── linux_amd64
            │           └── terraform-provider-local_v2.5.2_x5
            └── random
                └── 3.6.3
                    └── linux_amd64
                        └── terraform-provider-random_v3.6.3_x5

The generated lock file:

$ cat .terraform.lock.hcl
# This file is maintained automatically by "terraform init".
# Manual edits may be lost in future updates.

provider "registry.terraform.io/hashicorp/local" {
  version     = "2.5.2"
  constraints = "~> 2.5"
  hashes = [
    "h1:JlMZD6nYqJ8sSrFfEAH0Vk/SL8WLZRmFaMUF9PJK5wM=",
    "zh:136299545178ce281c56f36965bf91c35407c11897f7082b3b983d86cb79b511",
  ]
}

provider "registry.terraform.io/hashicorp/random" {
  version     = "3.6.3"
  constraints = "~> 3.6"
  hashes = [
    "h1:Ry0Lr0zaoicslZlcUR4rAySPpl/a7QupfMfuAxhW3fw=",
    "zh:04ceb65210251339f07cd4611885d242cd4d0c7306e86dda9785396807c00451",
  ]
}

terraform init is idempotent: running it again breaks nothing. You need to run it again whenever providers, modules or the backend change. If you ever see the error Error: Inconsistent dependency lock file, the fix is terraform init -upgrade.

  1. terraform fmt and terraform validate

Before planning, two cheap checks.

terraform fmt reformats the code into the canonical style: two-space indentation and = signs aligned within each block.

# Shows which files it reformatted.
$ terraform fmt
main.tf

# Second run: no output, everything is already properly formatted.
$ terraform fmt

# In CI it is used like this: it changes nothing and returns exit code 3
# if any file would need formatting. -diff shows what would change.
$ terraform fmt -check -diff -recursive
$ echo $?
0

What it does to the code, exactly. If you had written:

resource "random_pet" "suffix" {
length = 2
    separator="-"
}

terraform fmt turns it into:

resource "random_pet" "suffix" {
  length    = 2
  separator = "-"
}

If you set up format-on-save in VS Code, this happens by itself.

terraform validate checks that the configuration is syntactically correct and internally coherent: that the types line up, that references point at objects that exist and that no required arguments are missing. It does not contact any API or read the state.

$ terraform validate
Success! The configuration is valid.

An example of an error it does catch. If you wrote random_pet.wrong_suffix.id in main.tf:

$ terraform validate
╷
│ Error: Reference to undeclared resource
│
│   on main.tf line 58, in resource "local_file" "inventory":
│   58:     unique_suffix = random_pet.wrong_suffix.id
│
│ A managed resource "random_pet" "wrong_suffix" has not been declared in the
│ root module.
╵

And an example of an error it does not catch: that a bucket name is already taken by another company in the real world. You only find that out when you apply.

  1. terraform plan explained line by line

$ terraform plan

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # local_file.inventory will be created
  + resource "local_file" "inventory" {
      + content              = jsonencode(
            {
              + environment       = "dev"
              + generated_by      = "terraform"
              + name_prefix       = "ecomarket-dev"
              + planned_resources = [
                  + "ecomarket-dev-web",
                  + "ecomarket-dev-lb",
                  + "ecomarket-dev-db",
                ]
              + project           = "ecomarket"
              + region            = "eu-west-1"
              + tags              = {
                  + Environment = "dev"
                  + ManagedBy   = "terraform"
                  + Project     = "ecomarket"
                }
            }
        )
      + content_base64sha256 = (known after apply)
      + content_base64sha512 = (known after apply)
      + content_md5          = (known after apply)
      + content_sha1         = (known after apply)
      + content_sha256       = (known after apply)
      + content_sha512       = (known after apply)
      + directory_permission = "0777"
      + file_permission      = "0644"
      + filename             = "./ecomarket-dev-inventory.json"
      + id                   = (known after apply)
    }

  # random_id.suffix_hex will be created
  + resource "random_id" "suffix_hex" {
      + b64_std     = (known after apply)
      + b64_url     = (known after apply)
      + byte_length = 4
      + dec         = (known after apply)
      + hex         = (known after apply)
      + id          = (known after apply)
      + keepers     = {
          + "environment" = "dev"
        }
    }

  # random_pet.suffix will be created
  + resource "random_pet" "suffix" {
      + id        = (known after apply)
      + keepers   = {
          + "environment" = "dev"
        }
      + length    = 2
      + separator = "-"
    }

Plan: 3 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + images_bucket_name = (known after apply)
  + inventory_path     = "./ecomarket-dev-inventory.json"
  + name_prefix        = "ecomarket-dev"
  + suffix_hex         = (known after apply)
  + unique_suffix      = (known after apply)

Note: You didn't use the -out option to save this plan, so Terraform can't
guarantee to take exactly these actions if you run "terraform apply" now.

Let us dissect it:

  • The symbol legend at the top tells you which actions appear. Here there is only + create, which confirms straight away that nothing is going to be destroyed.
  • # local_file.inventory will be created is the resource address followed by the action.
  • The contents of the jsonencode are broken out and sorted alphabetically. Notice that the values derived from variables and locals (ecomarket-dev, eu-west-1) are already known: they are computed without touching anything.
  • Inside planned_resources the images bucket is missing from this output: because its name contains random_id.suffix_hex.hex, which does not exist yet, the complete list is unknown until the apply. Terraform shows what it can.
  • (known after apply) marks the values the provider will decide when it creates the object: the content hashes, the id, the hexadecimal value and so on.
  • directory_permission = "0777" is a provider default we never wrote. The plan always shows the complete object.
  • Plan: 3 to add, 0 to change, 0 to destroy is the summary line. Always read it first.
  • Changes to Outputs previews which outputs will appear.
  • The closing note reminds you that, without -out, the apply will recompute the plan and could do something slightly different if anything changed in the meantime.

Let us do it properly, saving the plan:

$ terraform plan -out=ecomarket-dev.tfplan
...
Plan: 3 to add, 0 to change, 0 to destroy.

Saved the plan to: ecomarket-dev.tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "ecomarket-dev.tfplan"

The .tfplan file is binary; it is not meant to be read in an editor. To inspect it:

# Readable format
$ terraform show ecomarket-dev.tfplan

# JSON format, for policy analysis tools
$ terraform show -json ecomarket-dev.tfplan | jq '.resource_changes[].change.actions'
[
  "create"
]
[
  "create"
]
[
  "create"
]

Security warning: a plan file can contain sensitive values in the clear. Do not push it to Git or publish it as an unprotected pipeline artefact.

  1. terraform apply and the result on disk

We apply exactly the saved plan:

$ terraform apply "ecomarket-dev.tfplan"

random_pet.suffix: Creating...
random_id.suffix_hex: Creating...
random_pet.suffix: Creation complete after 0s [id=cheerful-mammoth]
random_id.suffix_hex: Creation complete after 0s [id=T3xK9Q]
local_file.inventory: Creating...
local_file.inventory: Creation complete after 0s [id=5f1c3a9e2b7d84c06f11ab3d2e9c7a5b8d4e6f10]

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Outputs:

images_bucket_name = "ecomarket-dev-images-4f7ba2d1"
inventory_path = "./ecomarket-dev-inventory.json"
name_prefix = "ecomarket-dev"
suffix_hex = "4f7ba2d1"
unique_suffix = "cheerful-mammoth"

Key observations about this output:

  • random_pet.suffix and random_id.suffix_hex are created at the same time: they do not depend on each other, and Terraform parallelises them. This is the dependency graph in action.
  • local_file.inventory starts afterwards, once both have finished, because it references their attributes.
  • The [id=...] on each line is the identifier the provider assigned to the object, which is recorded in the state.
  • The outputs are printed at the end, now with their real values.

When you apply without a saved plan, Terraform shows the plan and asks for explicit confirmation:

$ terraform apply

  ... (the complete plan) ...

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

You have to type yes literally; neither y nor Y will do. The -auto-approve flag skips this question: use it in test environments and in pipelines that have already reviewed the plan, never by hand in production.

Let us look at what appeared on disk:

$ ls -la
-rw-r--r--  1 dev dev   612 ecomarket-dev-inventory.json
-rw-r--r--  1 dev dev  4187 ecomarket-dev.tfplan
-rw-r--r--  1 dev dev  1893 main.tf
-rw-r--r--  1 dev dev  1021 outputs.tf
-rw-r--r--  1 dev dev   398 providers.tf
-rw-r--r--  1 dev dev  4862 terraform.tfstate
-rw-r--r--  1 dev dev    87 terraform.tfvars
-rw-r--r--  1 dev dev   612 variables.tf
-rw-r--r--  1 dev dev   487 versions.tf

Two new files: our inventory and the state.

$ cat ecomarket-dev-inventory.json | jq
{
  "environment": "dev",
  "generated_by": "terraform",
  "name_prefix": "ecomarket-dev",
  "planned_resources": [
    "ecomarket-dev-web",
    "ecomarket-dev-lb",
    "ecomarket-dev-db",
    "ecomarket-dev-images-4f7ba2d1"
  ],
  "project": "ecomarket",
  "region": "eu-west-1",
  "suffix_hex": "4f7ba2d1",
  "tags": {
    "Environment": "dev",
    "ManagedBy": "terraform",
    "Project": "ecomarket"
  },
  "unique_suffix": "cheerful-mammoth"
}

And an important idempotence check:

$ terraform apply -auto-approve
random_pet.suffix: Refreshing state... [id=cheerful-mammoth]
random_id.suffix_hex: Refreshing state... [id=T3xK9Q]
local_file.inventory: Refreshing state... [id=5f1c3a9e...]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and
found no differences, so no changes are needed.

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Nothing changed, because nothing needed to change. That is the idempotence we saw in the previous lesson.

  1. Modifying a resource and reading the update plan

Now the EcoMarket team decides to add the generation date and the owner to the inventory. We edit the content block in main.tf:

resource "local_file" "inventory" {
  filename = "${path.module}/${local.prefix}-inventory.json"

  content = jsonencode({
    project        = var.project
    environment    = var.environment
    region         = var.region
    name_prefix    = local.prefix
    unique_suffix  = random_pet.suffix.id
    suffix_hex     = random_id.suffix_hex.hex
    tags           = local.common_tags
    generated_by   = "terraform"

    # --- New lines ---
    team           = "platform"
    contact        = "[email protected]"
    schema_version = "1.1"
    # -----------------

    planned_resources = [
      "${local.prefix}-web",
      "${local.prefix}-lb",
      "${local.prefix}-db",
      "${local.prefix}-images-${random_id.suffix_hex.hex}",
    ]
  })

  file_permission = "0644"
}

And we plan:

$ terraform plan

random_pet.suffix: Refreshing state... [id=cheerful-mammoth]
random_id.suffix_hex: Refreshing state... [id=T3xK9Q]
local_file.inventory: Refreshing state... [id=5f1c3a9e...]

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # local_file.inventory will be updated in-place
  ~ resource "local_file" "inventory" {
      ~ content              = jsonencode(
          ~ {
              + contact        = "[email protected]"
              + schema_version = "1.1"
              + team           = "platform"
                # (8 unchanged attributes hidden)
            }
        )
      ~ content_base64sha256 = "kP2v..." -> (known after apply)
      ~ content_md5          = "8a1f0b..." -> (known after apply)
      ~ id                   = "5f1c3a9e..." -> (known after apply)
        # (5 unchanged attributes hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.

How to read this plan:

  • The legend shows only ~ update in-place: there are no creations and no destructions. It is the least risky scenario.
  • Inside the jsonencode, only the three new keys appear with +, and a note says 8 unchanged attributes are hidden. The plan highlights the difference; it does not repeat what stays the same.
  • The hashes become (known after apply): they will change because the content changes.
  • The id changes too, because in the local provider the id is the SHA-1 hash of the content. Even so, the action is still ~ and not -/+: the provider knows how to rewrite the file without recreating the resource.

We apply:

$ terraform apply -auto-approve
...
local_file.inventory: Modifying... [id=5f1c3a9e...]
local_file.inventory: Modifications complete after 0s [id=c7e0d21b...]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

Now for a very instructive experiment: let us change the environment to staging and see what happens.

$ terraform plan -var="environment=staging"

Terraform will perform the following actions:

  # local_file.inventory must be replaced
-/+ resource "local_file" "inventory" {
      ~ filename = "./ecomarket-dev-inventory.json" -> "./ecomarket-staging-inventory.json" # forces replacement
      ~ id       = "c7e0d21b..." -> (known after apply)
    }

  # random_id.suffix_hex must be replaced
-/+ resource "random_id" "suffix_hex" {
      ~ hex     = "4f7ba2d1" -> (known after apply)
      ~ keepers = { # forces replacement
          ~ "environment" = "dev" -> "staging"
        }
    }

  # random_pet.suffix must be replaced
-/+ resource "random_pet" "suffix" {
      ~ id      = "cheerful-mammoth" -> (known after apply)
      ~ keepers = { # forces replacement
          ~ "environment" = "dev" -> "staging"
        }
    }

Plan: 3 to add, 0 to change, 3 to destroy.

Here the -/+ symbols we studied in the previous lesson show up, and the plan explains exactly why:

  • Changing filename forces replacement: from this provider's point of view, a file cannot be renamed "in place".
  • Changing keepers forces replacement of the random resources: that is precisely their purpose, so each environment gets its own suffix.

This example illustrates a real problem: managing several environments by changing a variable against the same state destroys the previous environment. This is not the solution: workspaces, per-environment directories or separate backends are, and we will see them in module 6 and in Code Organization. Do not apply this plan.

  1. terraform output and terraform show

terraform output queries the outputs stored in the state, recomputing nothing:

# Every output
$ terraform output
images_bucket_name = "ecomarket-dev-images-4f7ba2d1"
inventory_path = "./ecomarket-dev-inventory.json"
name_prefix = "ecomarket-dev"
suffix_hex = "4f7ba2d1"
unique_suffix = "cheerful-mammoth"

# One specific output (quoted, HCL format)
$ terraform output unique_suffix
"cheerful-mammoth"

# Raw, without quotes: ideal for use in scripts
$ terraform output -raw images_bucket_name
ecomarket-dev-images-4f7ba2d1

# As JSON, with the type and the sensitivity flag
$ terraform output -json | jq
{
  "images_bucket_name": {
    "sensitive": false,
    "type": "string",
    "value": "ecomarket-dev-images-4f7ba2d1"
  },
  "inventory_path": {
    "sensitive": false,
    "type": "string",
    "value": "./ecomarket-dev-inventory.json"
  }
}

A real use within EcoMarket's workflow:

# Use a Terraform output in a later deployment script.
BUCKET=$(terraform output -raw images_bucket_name)
echo "Uploading the product images to ${BUCKET}..."

terraform show displays the contents of the state in readable form:

$ terraform show

# local_file.inventory:
resource "local_file" "inventory" {
    content              = jsonencode({...})
    content_base64sha256 = "kP2vXq..."
    content_md5          = "8a1f0b3c..."
    directory_permission = "0777"
    file_permission      = "0644"
    filename             = "./ecomarket-dev-inventory.json"
    id                   = "c7e0d21b..."
}

# random_id.suffix_hex:
resource "random_id" "suffix_hex" {
    b64_std     = "T3ui0Q=="
    b64_url     = "T3ui0Q"
    byte_length = 4
    dec         = "1333354193"
    hex         = "4f7ba2d1"
    id          = "T3ui0Q"
    keepers     = {
        "environment" = "dev"
    }
}

# random_pet.suffix:
resource "random_pet" "suffix" {
    id        = "cheerful-mammoth"
    keepers   = {
        "environment" = "dev"
    }
    length    = 2
    separator = "-"
}


Outputs:

images_bucket_name = "ecomarket-dev-images-4f7ba2d1"
inventory_path = "./ecomarket-dev-inventory.json"
name_prefix = "ecomarket-dev"
suffix_hex = "4f7ba2d1"
unique_suffix = "cheerful-mammoth"

Notice that show reveals every attribute, including the ones you never wrote (b64_std, dec, directory_permission). It is the complete view of what the provider stored in the state.

With -json you get processable output:

# A list of the addresses of every managed resource
$ terraform show -json | jq -r '.values.root_module.resources[].address'
local_file.inventory
random_id.suffix_hex
random_pet.suffix

A quick comparison of the two commands:

terraform output terraform show
What it shows Only the values declared as output Every resource in the state, with all its attributes
Does it query the API? No No (unless you use other flags)
Formats text, -raw, -json text, -json
Typical use Feeding scripts and other systems Inspecting and debugging what is deployed

  1. terraform destroy

To close the cycle, we destroy what we created. In a real environment this is a very serious operation; here it only deletes two local files and clears the state.

$ terraform destroy

random_pet.suffix: Refreshing state... [id=cheerful-mammoth]
random_id.suffix_hex: Refreshing state... [id=T3xK9Q]
local_file.inventory: Refreshing state... [id=c7e0d21b...]

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  # local_file.inventory will be destroyed
  - resource "local_file" "inventory" {
      - content              = jsonencode({...}) -> null
      - filename             = "./ecomarket-dev-inventory.json" -> null
      - id                   = "c7e0d21b..." -> null
    }

  # random_id.suffix_hex will be destroyed
  - resource "random_id" "suffix_hex" {
      - hex         = "4f7ba2d1" -> null
      - id          = "T3ui0Q" -> null
    }

  # random_pet.suffix will be destroyed
  - resource "random_pet" "suffix" {
      - id        = "cheerful-mammoth" -> null
      - length    = 2 -> null
    }

Plan: 0 to add, 0 to change, 3 to destroy.

Changes to Outputs:
  - images_bucket_name = "ecomarket-dev-images-4f7ba2d1" -> null
  - inventory_path     = "./ecomarket-dev-inventory.json" -> null
  - name_prefix        = "ecomarket-dev" -> null
  - suffix_hex         = "4f7ba2d1" -> null
  - unique_suffix      = "cheerful-mammoth" -> null

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

local_file.inventory: Destroying... [id=c7e0d21b...]
local_file.inventory: Destruction complete after 0s
random_pet.suffix: Destroying... [id=cheerful-mammoth]
random_id.suffix_hex: Destroying... [id=T3ui0Q]
random_pet.suffix: Destruction complete after 0s
random_id.suffix_hex: Destruction complete after 0s

Destroy complete! Resources: 3 destroyed.

Notice the destruction order: local_file.inventory first and the two random resources afterwards. This is the dependency graph walked backwards, and Terraform does it without you saying anything. If it went forwards, it would delete the suffix the file depends on.

The result on disk:

$ ls
main.tf  outputs.tf  providers.tf  terraform.tfstate
terraform.tfstate.backup  terraform.tfvars  variables.tf  versions.tf

The inventory file is gone. The state still exists, but empty of resources:

$ terraform show
The state file is empty. No resources are represented.

And terraform.tfstate.backup keeps the previous version, in case you need to recover it.

For an ephemeral CI environment, where there is nobody to type yes:

$ terraform destroy -auto-approve

A serious warning: terraform destroy destroys everything managed in that state, with no undo. In production, the right protection is lifecycle { prevent_destroy = true } on the critical resources (databases, buckets holding data) and restricting who can run the command. We will see this in module 7.

Common Mistakes and Tips

  • Error: Could not load plugin or Inconsistent dependency lock file: you have not run terraform init, or you changed a version constraint. Fix: terraform init -upgrade.
  • Running plan without init: Terraform detects it and tells you literally to run init first. It is not a serious error, it is just the natural order.
  • Confusing variables.tf with terraform.tfvars. Declaring a variable inside terraform.tfvars does not work; assigning a value inside variables.tf only sets the default.
  • Writing JSON by hand instead of using jsonencode. One comma too many produces an invalid file that nobody will notice until something reads it. jsonencode always produces valid JSON.
  • Forgetting path.module. If you write filename = "inventory.json", the file is created relative to whichever directory you run the command from, not next to the configuration. In CI that leads to surprises.
  • Applying without reading the plan. It is the only way Terraform can destroy something and take you by surprise. Always look for to destroy in the summary line.
  • Using -auto-approve out of habit. On your laptop with local resources, go ahead. In production, never without a reviewed and saved plan.
  • Believing that terraform destroy deletes the state. It does not: it leaves the state empty but still there, and creates a .backup. Deleting the state file is something else entirely, and it is dangerous.
  • Managing several environments by changing a variable against the same state, as we saw in section 12. It destroys the previous environment. There are proper solutions in modules 6 and 7.
  • Tip: get used to the sequence fmt → validate → plan -out → apply <plan>. It is the flow professional teams use and the one we will automate in module 8.
  • Tip: make a Git commit after every change that works. The infrastructure's history is as valuable as the application code's.

Exercises

Exercise 1: adding the deployment log

Extend EcoMarket's configuration with a second local_file resource called deployment_log that generates a file ecomarket-dev-deployment.txt with this content:

Project: ecomarket
Environment: dev
Region: eu-west-1
Suffix: cheerful-mammoth
Managed by: terraform

Requirements:

  1. Use the prefix from locals and references to the random resources.
  2. Add an output deployment_log_path with the new file's path.
  3. Run plan and check that the summary says 1 to add, 0 to change, 0 to destroy.
  4. Apply and verify the file's contents.

Exercise 2: triggering and reading a replacement

Starting from the configuration you have already applied:

  1. Change file_permission on local_file.inventory from "0644" to "0640" and look at the plan. Is it an update or a replacement?
  2. Change byte_length on random_id.suffix_hex from 4 to 8. What action does Terraform propose, and what knock-on effect does it have on the inventory?
  3. Explain why the two situations behave differently.

Exercise 3: a complete cycle for staging without destroying dev

The EcoMarket team wants the staging inventory without losing the dev one. Using only what you have learned in this module (no workspaces, which belong to module 6):

  1. Describe what would happen if you ran terraform apply -var="environment=staging" in the same directory.
  2. Propose a directory-based solution and explain which files would have to be duplicated and which would not.
  3. Implement the solution and check that both inventory files coexist.

Solutions

Solution 1:

In main.tf:

resource "local_file" "deployment_log" {
  filename = "${path.module}/${local.prefix}-deployment.txt"

  # <<-EOT is an "indented heredoc": it lets you write multi-line text
  # and strips the common indentation, so the file comes out clean.
  content = <<-EOT
    Project: ${var.project}
    Environment: ${var.environment}
    Region: ${var.region}
    Suffix: ${random_pet.suffix.id}
    Managed by: terraform
  EOT

  file_permission = "0644"
}

In outputs.tf:

output "deployment_log_path" {
  description = "Path of the generated deployment log."
  value       = local_file.deployment_log.filename
}

Running it:

$ terraform fmt
$ terraform validate
Success! The configuration is valid.

$ terraform plan
...
Plan: 1 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + deployment_log_path = "./ecomarket-dev-deployment.txt"

$ terraform apply -auto-approve
local_file.deployment_log: Creating...
local_file.deployment_log: Creation complete after 0s [id=...]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

$ cat ecomarket-dev-deployment.txt
Project: ecomarket
Environment: dev
Region: eu-west-1
Suffix: cheerful-mammoth
Managed by: terraform

The summary says 1 to add and leaves the existing resources alone because we only added a new block that depends on resources that already exist.

Solution 2:

  1. An in-place update (~). The local provider can change the permissions with a chmod, without recreating the file:
  # local_file.inventory will be updated in-place
  ~ resource "local_file" "inventory" {
      ~ file_permission = "0644" -> "0640"
        # (9 unchanged attributes hidden)
    }

Plan: 0 to add, 1 to change, 0 to destroy.
  1. A replacement (-/+) of random_id, plus a knock-on update of the inventory:
  # local_file.inventory will be updated in-place
  ~ resource "local_file" "inventory" {
      ~ content = jsonencode(
          ~ {
              ~ suffix_hex = "4f7ba2d1" -> (known after apply)
            }
        )
    }

  # random_id.suffix_hex must be replaced
-/+ resource "random_id" "suffix_hex" {
      ~ byte_length = 4 -> 8 # forces replacement
      ~ hex         = "4f7ba2d1" -> (known after apply)
    }

Plan: 1 to add, 1 to change, 1 to destroy.

The knock-on effect is that the inventory changes too, because it references random_id.suffix_hex.hex. And with it, the images bucket's name would change: in the real cloud, that would mean destroying and recreating the bucket, losing its contents. A valuable lesson in why random suffixes must be handled with care.

  1. The difference lies in the provider's schema: file_permission is an updatable attribute, whereas byte_length is marked as forcing a new object, because you cannot "lengthen" an already generated random value without generating another one. Terraform always flags this with the # forces replacement comment.

Solution 3:

  1. It would destroy the dev environment. As we saw in section 12, changing environment modifies keepers (replacing the two random resources) and filename (replacing the file). The plan would be 3 to add, 0 to change, 3 to destroy: there is only one state and it cannot represent two environments at once.

  2. A directory-based solution: one directory per environment, each with its own state.

ecomarket-infra/
├── .gitignore
├── .terraform-version
└── infra/
    ├── dev/
    │   ├── main.tf          -> copy or link
    │   ├── outputs.tf
    │   ├── providers.tf
    │   ├── variables.tf
    │   ├── versions.tf
    │   └── terraform.tfvars  (environment = "dev")
    └── staging/
        ├── main.tf
        ├── outputs.tf
        ├── providers.tf
        ├── variables.tf
        ├── versions.tf
        └── terraform.tfvars  (environment = "staging")

What gets duplicated and what does not:

Item Duplicated? Reason
terraform.tfvars Yes, with different values It is the only thing that differentiates the environments
terraform.tfstate Yes (one per directory) Each environment needs its own state; this is the key point
.terraform.lock.hcl Yes (init generates one in each) It must be versioned in both
main.tf, variables.tf, outputs.tf, versions.tf, providers.tf It should not be Duplicating code leads to divergence. The correct solution is to extract a shared module (module 4) that both directories call
  1. A quick implementation so you can check it:
cd ~/projects/ecomarket-infra/infra
mkdir -p dev staging

# Move the current configuration into dev
mv *.tf terraform.tfvars dev/
mv terraform.tfstate* dev/ 2>/dev/null

# Copy it into staging and change only the values file
cp dev/*.tf staging/
cat > staging/terraform.tfvars <<'EOF'
project     = "ecomarket"
environment = "staging"
region      = "eu-west-1"
EOF

# Each directory is initialised and applied separately
cd dev     && terraform init && terraform apply -auto-approve && cd ..
cd staging && terraform init && terraform apply -auto-approve && cd ..

# Check: both inventories coexist
find . -name '*-inventory.json'
./dev/ecomarket-dev-inventory.json
./staging/ecomarket-staging-inventory.json

Each directory has its own terraform.tfstate, so the environments are independent: applying in staging does not affect dev. This structure works, but it duplicates code; in module 4 we will remove that duplication with modules, and in module 7 we will see how to organise it at scale.

Conclusion

You have completed your first real Terraform lifecycle, end to end:

  • The file convention (versions.tf, providers.tf, main.tf, variables.tf, outputs.tf, terraform.tfvars) organises the project even though Terraform loads every .tf indiscriminately.
  • The terraform block pins the binary's version and the providers'; provider configures them; resource describes the objects; variable parameterises; locals computes constants; output exposes results.
  • init downloads the providers, writes .terraform/ and generates the lock file you must version.
  • fmt and validate are cheap checks that remove noise and errors before you plan.
  • plan shows you exactly what is going to happen, with its symbols and its (known after apply) markers; saving it with -out and applying that file is the professional practice.
  • apply executes the plan respecting the dependency graph and parallelising what it can; repeating it with no changes does nothing (idempotence).
  • A modification produces a ~ update in-place, whereas changing a forcing argument produces a -/+ that destroys and recreates: reading that difference properly prevents incidents.
  • output and show let you query what is deployed, as text or as JSON to feed other systems.
  • destroy walks the graph backwards and removes everything it manages; in production you protect it with prevent_destroy and with permissions.

With this you close module 1: you know what Terraform is and which problem it solves, you have the environment installed and configured, you command the vocabulary and you have run a complete project without needing a cloud account. What you have written so far was the bare minimum needed to run; from here on it is time to master the language. In module 2, The Terraform Configuration Language, we will begin with HCL Syntax to understand blocks, expressions, types, interpolations and control structures in depth; then we will go deeper into Variables and Outputs with complex types, validations, sensitive values and .auto.tfvars files; we will continue with Resource and Data Blocks to squeeze everything out of count, for_each and lifecycle; and we will close with Providers, where we will configure aliases, versions and multiple regions, leaving EcoMarket ready to make the leap to real cloud infrastructure.

© Copyright 2026. All rights reserved