Skip to main content
0 reactions

OpenTofu Tutorial — Part 4: Variables, tfvars and Outputs

Card titled Variables, tfvars and Outputs, labelled OpenTofu Tutorial Part 4, showing a terraform.tfvars file that sets shop_name to Riverside Bookshop and an output window with container_name and website_url http://localhost:8080.
OpenTofu Tutorial, Part 4: Variables, tfvars and Outputs.

In Part 3, the Bookshop’s name, its featured book and its port were typed straight into main.tf. To change one, you had to edit the configuration. In this part, OpenTofu® reads them from input variables instead, you set new values in a terraform.tfvars file, and outputs print the website’s address for you.

By the end of this part, the same website runs at http://localhost:8080 under a new name, and tofu apply ends by printing its address.

This is Part 4 of the OpenTofu Tutorial. The parts in Module B, Write Configuration:

  • Part 4: Variables, tfvars and Outputs (you are here)
  • Part 5: Locals, Expressions and tofu console
  • Part 6: Functions
  • Part 7: Data Sources
  • Part 8: count, for_each and enabled
  • Part 9: Dependencies, Networks, Volumes, Dynamic Blocks and the Graph
  • Part 10: Lifecycle Rules
  • Part 11: Validation, Conditions and Check Blocks
All parts of the OpenTofu Tutorial

Module A: Start Here

Module B: Write Configuration

  • Part 4: Variables, tfvars and Outputs
  • Part 5: Locals, Expressions and tofu console
  • Part 6: Functions
  • Part 7: Data Sources
  • Part 8: count, for_each and enabled
  • Part 9: Dependencies, Networks, Volumes, Dynamic Blocks and the Graph
  • Part 10: Lifecycle Rules
  • Part 11: Validation, Conditions and Check Blocks

Module C: Add a Database

  • Part 12: PostgreSQL in Docker, Managed with OpenTofu

Module D: Modules

  • Part 13: Your First Module
  • Part 14: Module Sources and Versions
  • Part 15: OCI Registries for Modules and Providers

Module E: State

  • Part 16: Inside OpenTofu State
  • Part 17: Refactor Safely: moved, removed, state mv and rm
  • Part 18: Import Existing Infrastructure
  • Part 19: Remote State in PostgreSQL with Locking
  • Part 20: S3 Backend with Native Locking
  • Part 21: Encrypt State and Plan Files
  • Part 22: Workspaces and Sharing Outputs

Module F: Secrets

  • Part 23: Ephemeral Values and Write-Only Attributes
  • Part 24: Secrets with OpenBao

Module G: Operations

  • Part 25: Plan and Apply Options
  • Part 26: CLI Configuration and Provider Installation
  • Part 27: Logs and Tracing
  • Part 28: Provisioners and terraform_data

Module H: Test and Team

  • Part 29: Test Your Configuration with tofu test
  • Part 30: Mock Providers and Overrides
  • Part 31: Multiple Provider Instances
  • Part 32: Manage GitHub with OpenTofu
  • Part 33: GitHub Actions CI/CD

Module I: Kubernetes

  • Part 34: Kubernetes for Free with kind
  • Part 35: Helm Charts and Kubernetes Secrets

Module J: Azure for Free

  • Part 36: Deploy to Azure for Free: Resource Group and App Service F1
  • Part 37: Azure Static Web Apps Free and Clean Up

Module K: Finish

  • Part 38: Migrate from Terraform to OpenTofu
  • Part 39: Final Project, Cheat Sheet and What to Learn Next

Cost: free. Everything in this part runs on your own computer, and you don’t need an account.

Every command and output on this page is real, run on OpenTofu 1.13 with Docker Desktop on macOS. The OpenTofu commands are the same in Windows PowerShell and on Linux.

Get the Source Code

Get the complete source code of Static Website in Docker with OpenTofu on Dewiride Store → (opens in a new tab)
It’s a finished, tested version of this website setup: every setting is a checked variable, with an example tfvars file, outputs for the address and the container, and seven tests.

Where Your Project Is Now

Part 3 ended with a bookshop folder holding main.tf, a .gitignore file and the lock file, with nothing running: its last step removed the website with tofu destroy. If you’re starting at this part, create a bookshop folder with these two files, then run tofu init in it.

main.tfHCL
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.7"
    }
  }
}

provider "docker" {}

resource "local_file" "home_page" {
  filename = "index.html"
  content  = "<h1>Welcome to the Bookshop</h1><p>New this week: Salt and Starlight by Nadia Quill.</p>"
}

resource "docker_image" "nginx" {
  name = "nginx:1.31-alpine"
}

resource "docker_container" "website" {
  name  = "bookshop"
  image = docker_image.nginx.image_id

  ports {
    internal = 80
    external = 8080
    ip       = "127.0.0.1"
  }

  upload {
    file    = "/usr/share/nginx/html/index.html"
    content = local_file.home_page.content
  }
}
.gitignorePlain text
.terraform/
*.tfstate
*.tfstate.*

Prerequisites

Step 1: Declare the Variables

An input variable is a named value that you set from outside the configuration, so the same files work with different values. Create a file named variables.tf in the bookshop folder:

variables.tfHCL
variable "shop_name" {
  description = "Name of the shop, shown in the page heading."
  type        = string
  default     = "Bookshop"
}

variable "featured_book" {
  description = "Book shown under New this week."
  type        = string
  default     = "Salt and Starlight by Nadia Quill"
}

variable "host_port" {
  description = "Port on your computer where the website opens."
  type        = number
  default     = 8080
}
  • variable "shop_name" declares a variable named shop_name. Every variable in a project needs its own name.
  • description says what the variable is for. OpenTofu shows it when it has to ask you for a value.
  • type sets which values the variable accepts: string for text and number for numbers. OpenTofu variable types covers lists, maps and the rest.
  • default is the value OpenTofu uses when you don’t set one, which makes the variable optional. Required vs optional variables shows what happens without one.

The defaults are the values Part 3 typed into main.tf, so the website won’t change yet.

Step 2: Use the Variables in main.tf

Inside the configuration, you read a variable as var.<NAME>. In main.tf, replace the content line of the home_page resource with this line:

main.tf (excerpt)HCL
  content  = "<h1>Welcome to the ${var.shop_name}</h1><p>New this week: ${var.featured_book}.</p>"

${…} puts a value inside text: OpenTofu replaces ${var.shop_name} with the variable’s value.

Then, in the ports block of the website resource, replace the external line:

main.tf (excerpt)HCL
    external = var.host_port

A value on its own, such as var.host_port, needs no quotes. Your complete main.tf now looks like this:

main.tfHCL
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.7"
    }
  }
}

provider "docker" {}

resource "local_file" "home_page" {
  filename = "index.html"
  content  = "<h1>Welcome to the ${var.shop_name}</h1><p>New this week: ${var.featured_book}.</p>"
}

resource "docker_image" "nginx" {
  name = "nginx:1.31-alpine"
}

resource "docker_container" "website" {
  name  = "bookshop"
  image = docker_image.nginx.image_id

  ports {
    internal = 80
    external = var.host_port
    ip       = "127.0.0.1"
  }

  upload {
    file    = "/usr/share/nginx/html/index.html"
    content = local_file.home_page.content
  }
}

Step 3: Apply with the Default Values

Run tofu apply and type yes when it asks:

TerminalBash
tofu apply

OpenTofu plans the same three resources as in Part 3, with the variables’ default values filled in. The published port and the page in the container’s plan:

Output (the lines that matter)Plain text
      + ports {
          + external = 8080
          + internal = 80
          + ip       = "127.0.0.1"
          + protocol = "tcp"
        }

      + upload {
          + content    = "<h1>Welcome to the Bookshop</h1><p>New this week: Salt and Starlight by Nadia Quill.</p>"
          + executable = false
          + file       = "/usr/share/nginx/html/index.html"
        }

The end of the output:

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

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

  Enter a value: yes

local_file.home_page: Creating...
local_file.home_page: Creation complete after 0s [id=74f5ffb6ae858818389a6a63c1b19e8d38e31119]
docker_image.nginx: Creating...
docker_image.nginx: Creation complete after 6s [id=sha256:7db22640b020292f56a05da2a1ccdf7d44c1f321b71444ffca55192dae23f664nginx:1.31-alpine]
docker_container.website: Creating...
docker_container.website: Creation complete after 1s [id=37204918c10070c6c69d1cf76d051fd78490e2880762b8151bd759fcc404ad22]

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

If you kept Part 3’s website running, the plan says No changes instead, because the defaults give exactly the values that are running.

Open http://localhost:8080. The page is the same as at the end of Part 3, now built from the variables:

A web browser showing the Bookshop page at localhost port 8080, with the heading Welcome to the Bookshop and the line New this week: Salt and Starlight by Nadia Quill.
The page built from the default values: the same as at the end of Part 3.

Step 4: Set New Values in terraform.tfvars

To use other values, you don’t touch the configuration. Create a file named terraform.tfvars in the bookshop folder:

terraform.tfvarsHCL
shop_name     = "Riverside Bookshop"
featured_book = "A Map of Quiet Places by Tomas Vell"

A .tfvars file holds only assignments: a variable’s name, = and its value. OpenTofu reads a file named exactly terraform.tfvars by itself, every time you run tofu plan or tofu apply. .tfvars vs .auto.tfvars shows which other files it reads. host_port isn’t in the file, so it keeps its default, 8080.

Run tofu apply again and type yes:

TerminalBash
tofu apply

The new text changes the page file and the page uploaded to the container, so OpenTofu replaces both. The page file’s part of the plan:

Output (the lines that matter)Plain text
  # local_file.home_page must be replaced
-/+ resource "local_file" "home_page" {
      ~ content              = "<h1>Welcome to the Bookshop</h1><p>New this week: Salt and Starlight by Nadia Quill.</p>" -> "<h1>Welcome to the Riverside Bookshop</h1><p>New this week: A Map of Quiet Places by Tomas Vell.</p>" # forces replacement

The end of the output:

OutputPlain text
Plan: 2 to add, 0 to change, 2 to destroy.

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

  Enter a value: yes

docker_container.website: Destroying... [id=37204918c10070c6c69d1cf76d051fd78490e2880762b8151bd759fcc404ad22]
docker_container.website: Destruction complete after 1s
local_file.home_page: Destroying... [id=74f5ffb6ae858818389a6a63c1b19e8d38e31119]
local_file.home_page: Destruction complete after 0s
local_file.home_page: Creating...
local_file.home_page: Creation complete after 0s [id=39d22aa2e69ccf05796e9dbe2ee0bf9912e604b5]
docker_container.website: Creating...
docker_container.website: Creation complete after 0s [id=48378f2496834d78933c7563f3f72914ba063601ceaeb7b1f9695388bcf1aa33]

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

Refresh the browser. The page shows the values from terraform.tfvars:

The same browser page after the change, with the heading Welcome to the Riverside Bookshop and the line New this week: A Map of Quiet Places by Tomas Vell.
The values from terraform.tfvars are on the page.

Step 5: Print the Address with Outputs

An output prints a value at the end of tofu apply, so you don’t have to work it out yourself. Create a file named outputs.tf:

outputs.tfHCL
output "website_url" {
  description = "Address of the Bookshop website."
  value       = "http://localhost:${var.host_port}"
}

output "container_name" {
  description = "Name of the Docker container that serves the website."
  value       = docker_container.website.name
}
  • output "website_url" declares an output named website_url, and description says what it holds.
  • value is what the output prints. The address is built from var.host_port, so it always shows the port you set.
  • docker_container.website.name reads the name of the container that OpenTofu manages.

Run tofu apply and type yes:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
Changes to Outputs:
  + container_name = "bookshop"
  + website_url    = "http://localhost:8080"

You can apply this plan to save these new output values to the OpenTofu state, without
changing any real infrastructure.

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

  Enter a value: yes


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

Outputs:

container_name = "bookshop"
website_url = "http://localhost:8080"

Nothing in Docker changed: OpenTofu only saved the two values in its state, and printed them under Outputs.

Step 6: Read the Outputs with tofu output

tofu output prints the saved outputs at any time, without planning anything:

TerminalBash
tofu output
OutputPlain text
container_name = "bookshop"
website_url = "http://localhost:8080"

Add -raw and an output’s name to print just that value, without quotes, ready to paste into a browser or a script:

TerminalBash
tofu output -raw website_url
OutputPlain text
http://localhost:8080

tofu output -raw and -json covers the JSON format that other tools read.

Clean Up

Run tofu destroy and type yes. It removes the container, the nginx image and index.html:

TerminalBash
tofu destroy
OutputPlain text
Plan: 0 to add, 0 to change, 3 to destroy.

Changes to Outputs:
  - container_name = "bookshop" -> null
  - website_url    = "http://localhost:8080" -> null

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

  Enter a value: yes

docker_container.website: Destroying... [id=48378f2496834d78933c7563f3f72914ba063601ceaeb7b1f9695388bcf1aa33]
docker_container.website: Destruction complete after 0s
docker_image.nginx: Destroying... [id=sha256:7db22640b020292f56a05da2a1ccdf7d44c1f321b71444ffca55192dae23f664nginx:1.31-alpine]
local_file.home_page: Destroying... [id=39d22aa2e69ccf05796e9dbe2ee0bf9912e604b5]
local_file.home_page: Destruction complete after 0s
docker_image.nginx: Destruction complete after 0s

Destroy complete! Resources: 3 destroyed.

Your bookshop folder keeps main.tf, variables.tf, outputs.tf, terraform.tfvars, the lock file and .gitignore, ready for Part 5.

Common Mistakes

MistakeWhat happensDo this instead
Naming the file terraform.tfvars.txt or bookshop.tfvarsOpenTofu doesn’t read it by itself, so the defaults stay.Name it exactly terraform.tfvars, or pass another name with -var-file.
Spelling a name differently in terraform.tfvars, such as shopnameOpenTofu warns Value for undeclared variable and ignores that line.Use the exact name from variables.tf.
Putting a password or key in terraform.tfvars and committing it to GitAnyone who can read the repository can read the secret.Keep secrets out of Git, and mark their variables as sensitive.

Troubleshooting

ProblemWhyFix
Error: Reference to undeclared input variablemain.tf uses var. with a name that no variable block declares, often a typo.Use the name from variables.tf. OpenTofu suggests it: Did you mean "shop_name"?
Error: Invalid value for input variable … a number is required.host_port is set to text, such as "eighty".Set it to a whole number, such as 8081.
Bind for 127.0.0.1:8080 failed: port is already allocatedAnother container already uses port 8080.Add host_port = 8081 to terraform.tfvars, run tofu apply and open the address the output prints.
ports are not available … bind: address already in useAnother program on your computer already uses port 8080.Add host_port = 8081 to terraform.tfvars, run tofu apply and open the address the output prints.

FAQ

Do variables have to be in variables.tf?

No. OpenTofu reads every .tf file in the folder, so a variable block works in any of them (Files and Directories (opens in a new tab)). variables.tf and outputs.tf are names most projects use, so other people find them quickly.

Should terraform.tfvars go into Git?

If it holds only ordinary settings, like this one, yes: it records how the project is set up. Never commit passwords or keys.

Can I set a variable without a file?

Yes, with the -var option of tofu plan and tofu apply, or with an environment variable named TF_VAR_ followed by the variable’s name. When the same variable is set in several places, OpenTofu uses the last one it reads, in the order of Variable Definition Precedence (opens in a new tab).

What happens if a variable has no default?

It becomes required: OpenTofu asks you for its value when you run tofu plan or tofu apply, unless a file or an option already sets it.

Conclusion

The Bookshop now takes its name, featured book and port from input variables. terraform.tfvars sets new values without touching main.tf, and outputs print the website’s address after every apply. Variables are how one configuration serves many sites, which the coming parts build on.

← Previous: Part 3: Providers: Run the Website in Docker

Coming next: Part 5: Locals, Expressions and tofu console.

Additional Resources

OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.

Docker and Docker Desktop are trademarks of Docker, Inc. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by Docker, Inc.

0 comments