Skip to main content
0 reactions

OpenTofu Tutorial — Part 5: Locals, Expressions and tofu console

Card titled Locals, Expressions and tofu console, labelled OpenTofu Tutorial Part 5, showing a main.tf locals block with heading and books_in_stock, and a console window where local.heading prints Welcome to the Riverside Bookshop.
Build the Bookshop’s book list with a template, a conditional and a for expression

In Part 4, the Bookshop page took its name and its featured book from variables, but it still showed a single line of text. In this part, the page lists every book from a variable, marks the ones that are sold out, and two new outputs list book titles for you.

Along the way you’ll name a value once with a local value, build the page with a template, choose text with a conditional expression, filter a list with a for expression, pick values with a splat expression, and try all of it in tofu console. By the end, http://localhost:8080 shows the full book list with a stock label after each book.

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

  • Part 4: Variables, tfvars and Outputs
  • Part 5: Locals, Expressions and tofu console (you are here)
  • 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

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: Team and Automation

  • Part 29: Multiple Provider Instances
  • Part 30: Manage GitHub with OpenTofu
  • Part 31: GitHub Actions CI/CD

Module I: Kubernetes

  • Part 32: Kubernetes for Free with kind
  • Part 33: Helm Charts and Kubernetes Secrets

Module J: Azure for Free

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

Module K: Finish

  • Part 36: Migrate from Terraform to OpenTofu
  • Part 37: 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 Catalogue Website in Docker with OpenTofu on Dewiride Store → (opens in a new tab)
It turns this part’s book list into a catalogue website for any list of items, with checked settings and a health check.

Where Your Project Is Now

Part 4 ended with a bookshop folder holding main.tf, variables.tf, outputs.tf, terraform.tfvars, 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 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 ${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
  }
}
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
}
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
}
terraform.tfvarsHCL
shop_name     = "Riverside Bookshop"
featured_book = "A Map of Quiet Places by Tomas Vell"
.gitignorePlain text
.terraform/
*.tfstate
*.tfstate.*

Prerequisites

Step 1: Name the Heading Once with a Local Value

A local value gives a name to a value or an expression inside your configuration, so you can use the name instead of repeating the expression. Unlike a variable, nobody sets it from outside. Locals vs variables compares the two.

Add a locals block to main.tf, under the provider "docker" {} line:

main.tf (excerpt)HCL
locals {
  heading = "Welcome to the ${var.shop_name}"
}

Then replace the content line of the home_page resource, so it uses the local value:

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

You declare local values in a locals block (plural) and read them as local.<NAME> (singular). Run tofu apply and type yes when it asks:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
Plan: 3 to add, 0 to change, 0 to destroy.

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

Outputs:

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

The website is back at http://localhost:8080 and looks exactly as it did at the end of Part 4. A local value changes nothing on its own: it only gives a value a name.

Step 2: List the Books from a Variable

The page should list every book the shop sells. Add this variable to the end of variables.tf. It’s a list of objects, one per book, each with a title, an author and whether it’s in stock (OpenTofu variable types explains lists and objects):

variables.tf (excerpt)HCL
variable "books" {
  description = "Books listed on the home page."
  type = list(object({
    title    = string
    author   = string
    in_stock = bool
  }))
  default = [
    {
      title    = "The Paper Lantern Café"
      author   = "Mira Kale"
      in_stock = true
    },
    {
      title    = "A Map of Quiet Places"
      author   = "Tomas Vell"
      in_stock = true
    },
    {
      title    = "The Clockmaker's Garden"
      author   = "Mira Kale"
      in_stock = false
    },
    {
      title    = "Salt and Starlight"
      author   = "Nadia Quill"
      in_stock = true
    },
  ]
}

Now build the page from that list. Replace the locals block in main.tf with this one:

main.tf (excerpt)HCL
locals {
  heading   = "Welcome to the ${var.shop_name}"
  home_page = <<EOT
<meta charset="utf-8">
<h1>${local.heading}</h1>
<p>New this week: ${var.featured_book}.</p>
<ul>
%{for book in var.books~}
  <li>${book.title} by ${book.author}</li>
%{endfor~}
</ul>
EOT
}
  • <<EOT starts a heredoc: text over several lines that ends at the line holding only EOT. Its lines start at the left edge, because an indented heredoc (<<-EOT) keeps the spaces on the lines after a ~: Fixed: OpenTofu indented heredoc not trimming spaces shows why.
  • %{for book in var.books~} and %{endfor~} repeat the line between them once for each book, with book set to that book. The ~ removes the line break after each directive, so no empty lines appear.
  • ${book.title} puts a value into the text, as in Part 4.
  • <meta charset="utf-8"> tells the browser the page is UTF-8, so the é in Café shows correctly. Without it, accented letters show as é.

String templates and heredocs covers all of this with a smaller example. Then replace the content line of the home_page resource:

main.tf (excerpt)HCL
  content  = local.home_page

Run tofu apply and type yes. The plan shows the new page, line by line:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
  # local_file.home_page must be replaced
-/+ resource "local_file" "home_page" {
      ~ content              = <<-EOT # forces replacement
          - <h1>Welcome to the Riverside Bookshop</h1><p>New this week: A Map of Quiet Places by Tomas Vell.</p>
          + <meta charset="utf-8">
          + <h1>Welcome to the Riverside Bookshop</h1>
          + <p>New this week: A Map of Quiet Places by Tomas Vell.</p>
          + <ul>
          +   <li>The Paper Lantern Café by Mira Kale</li>
          +   <li>A Map of Quiet Places by Tomas Vell</li>
          +   <li>The Clockmaker's Garden by Mira Kale</li>
          +   <li>Salt and Starlight by Nadia Quill</li>
          + </ul>
        EOT

The new page changes both the page file and the page uploaded to the container, so OpenTofu replaces them. The end of the output:

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

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

Outputs:

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

Refresh http://localhost:8080. The page lists the four books:

A web browser showing the Bookshop page at localhost port 8080: the heading Welcome to the Riverside Bookshop, the line New this week: A Map of Quiet Places by Tomas Vell, and a list of four books with their authors.
The book list, built from the books variable with a template.

Advertisement

Step 3: Label Sold-Out Books with a Conditional

A conditional expression picks one of two values: <CONDITION> ? <IF TRUE> : <IF FALSE>. In main.tf, replace the <li> line of the template with this line:

main.tf (excerpt)HCL
  <li>${book.title} by ${book.author}: ${book.in_stock ? "in stock" : "sold out"}</li>

For each book, book.in_stock is true or false, so the label reads in stock or sold out. Conditional expressions shows more. Run tofu apply and type yes:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
  # local_file.home_page must be replaced
-/+ resource "local_file" "home_page" {
      ~ content              = <<-EOT # forces replacement
            <meta charset="utf-8">
            <h1>Welcome to the Riverside Bookshop</h1>
            <p>New this week: A Map of Quiet Places by Tomas Vell.</p>
            <ul>
          -   <li>The Paper Lantern Café by Mira Kale</li>
          -   <li>A Map of Quiet Places by Tomas Vell</li>
          -   <li>The Clockmaker's Garden by Mira Kale</li>
          -   <li>Salt and Starlight by Nadia Quill</li>
          +   <li>The Paper Lantern Café by Mira Kale: in stock</li>
          +   <li>A Map of Quiet Places by Tomas Vell: in stock</li>
          +   <li>The Clockmaker's Garden by Mira Kale: sold out</li>
          +   <li>Salt and Starlight by Nadia Quill: in stock</li>
            </ul>
        EOT

Refresh the browser. Every book now has its label, and The Clockmaker's Garden is sold out:

The same browser page with a label after each book: three books say in stock and The Clockmaker’s Garden by Mira Kale says sold out.
A conditional expression labels each book in stock or sold out.

Step 4: List the Books in Stock with a for Expression

A for expression builds a new list from an existing one, and its if part keeps only some items. Add this line to the locals block, under heading:

main.tf (excerpt)HCL
  books_in_stock = [for book in var.books : book.title if book.in_stock]

It reads: for each book in var.books, take book.title, but only if book.in_stock is true. for expressions shows the other forms. 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" {}

locals {
  heading        = "Welcome to the ${var.shop_name}"
  books_in_stock = [for book in var.books : book.title if book.in_stock]
  home_page      = <<EOT
<meta charset="utf-8">
<h1>${local.heading}</h1>
<p>New this week: ${var.featured_book}.</p>
<ul>
%{for book in var.books~}
  <li>${book.title} by ${book.author}: ${book.in_stock ? "in stock" : "sold out"}</li>
%{endfor~}
</ul>
EOT
}

resource "local_file" "home_page" {
  filename = "index.html"
  content  = local.home_page
}

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
  }
}

To see the result, add an output to the end of outputs.tf:

outputs.tf (excerpt)HCL
output "books_in_stock" {
  description = "Titles of the books that are in stock."
  value       = local.books_in_stock
}

Run tofu apply and type yes. Only the output is new, so nothing in Docker changes:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
Changes to Outputs:
  + books_in_stock = [
      + "The Paper Lantern Café",
      + "A Map of Quiet Places",
      + "Salt and Starlight",
    ]

The three books in stock are listed; The Clockmaker's Garden isn’t.

Step 5: List Every Title with a Splat Expression

When you only need one attribute from every item of a list, a splat expression is shorter than a for expression: var.books[*].title gives the title of every book. Add this output to the end of outputs.tf:

outputs.tf (excerpt)HCL
output "book_titles" {
  description = "Titles of every book on the home page."
  value       = var.books[*].title
}

Run tofu apply and type yes:

TerminalBash
tofu apply
Output (the lines that matter)Plain text
Outputs:

book_titles = tolist([
  "The Paper Lantern Café",
  "A Map of Quiet Places",
  "The Clockmaker's Garden",
  "Salt and Starlight",
])
books_in_stock = [
  "The Paper Lantern Café",
  "A Map of Quiet Places",
  "Salt and Starlight",
]
container_name = "bookshop"
website_url = "http://localhost:8080"

OpenTofu prints book_titles as tolist([…]) because a splat expression keeps the list type of var.books, while a for expression with square brackets makes a tuple, printed as plain […]. You use both the same way. Splat expressions has more.

Step 6: Try Expressions in tofu console

tofu console evaluates expressions against your configuration and state, so you can test one before you put it in a file. Start it in the bookshop folder:

TerminalBash
tofu console

At the > prompt, type an expression and press Return (Enter on Windows and Linux) to see its value. Type exit to leave:

tofu consolePlain text
> local.heading
"Welcome to the Riverside Bookshop"
> var.books[0].title
"The Paper Lantern Café"
> var.books[*].author
tolist([
  "Mira Kale",
  "Tomas Vell",
  "Mira Kale",
  "Nadia Quill",
])
> var.books[2].in_stock ? "in stock" : "sold out"
"sold out"
> exit

While the console is open, it locks the state, so close it before you run tofu apply. tofu console covers it in more detail.

Clean Up

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

TerminalBash
tofu destroy
Output (the lines that matter)Plain text
Plan: 0 to add, 0 to change, 3 to destroy.

Destroy complete! Resources: 3 destroyed.

Your bookshop folder keeps all its files, ready for Part 6.

Common Mistakes

MistakeWhat happensDo this instead
Writing locals.heading instead of local.headingOpenTofu stops with Reference to undeclared resource.Declare in locals, read with local..
Indenting the heredoc with <<-EOT and using ~ in its directivesThe lines after each directive keep their spaces.Write the heredoc flush left with <<EOT, as above.
Leaving out <meta charset="utf-8">Accented letters show as two odd characters, such as Café.Keep the meta line at the top of the page.
Giving the two results of a conditional different types, such as a list and a stringOpenTofu stops with Inconsistent conditional result types.Make both results the same type.

Troubleshooting

ProblemWhyFix
Error: Error acquiring the state lock when you run tofu applytofu console is still open in another window and holds the lock.Type exit in the console, then run the command again.
Bind for 127.0.0.1:8080 failed: port is already allocatedAnother container already uses port 8080.Add host_port = 8081 to terraform.tfvars 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 and open the address the output prints.

FAQ

When should I use a local value instead of a variable?

Use a variable for a value that someone sets from outside, such as the shop’s name. Use a local value for something the configuration works out itself, such as the heading built from that name. The OpenTofu docs advise using local values in moderation: for a value that’s used in several places and likely to change.

Can a local value use another local value?

Yes. home_page uses local.heading here. The docs say a local value can refer to variables, resource attributes and other local values.

Does tofu console change anything?

No. It reads your configuration and state and prints the values of the expressions you type. It holds a lock on the state while it’s open, so other commands wait until you leave.

Conclusion

The Bookshop page is now built from a list: a local value names the heading, a heredoc template repeats a line for each book, a conditional labels the stock, and the outputs list titles with a for expression and a splat expression. tofu console lets you try any of them first.

← Previous: Part 4: Variables, tfvars and Outputs

Coming next: Part 6: Functions.

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