Skip to main content
0 reactions

How to Use optional Object Attributes in OpenTofu

Card titled optional Object Attributes, labelled OpenTofu Basics, showing port = optional(number, 8080) and the result port = 8080.
Mark attributes of an OpenTofu object type as optional, with or without a default

An object type normally needs every attribute it lists. Mark one with optional, and callers can leave it out: OpenTofu® fills in a default value, or null when you don’t give one.

Syntax

SyntaxHCL
<NAME> = optional(<TYPE>, <DEFAULT>)
  • <NAME>: the attribute inside the object({ … }) type.
  • <TYPE>: the attribute’s type, such as number or string.
  • <DEFAULT>: optional. The value used when the attribute is missing. Without it, OpenTofu uses null.

The rules are in Optional Object Type Attributes (opens in a new tab) in the OpenTofu docs.

Prerequisites

Step 1: Declare the Object

In an empty folder, create main.tf with a variable whose type has two optional attributes, and an output that shows it:

main.tfHCL
variable "server" {
  type = object({
    name = string
    port = optional(number, 8080)
    tag  = optional(string)
  })
  default = {
    name = "web"
  }
}

output "server" {
  value = var.server
}

The default value only sets name.

Step 2: Apply It

This configuration uses no providers, so tofu apply works without tofu init. Run it and type yes:

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

server = {
  "name" = "web"
  "port" = 8080
  "tag" = tostring(null)
}

port got its default, 8080, and tag is null.

Step 3: Set Some Attributes

Create terraform.tfvars with a value that sets port but still leaves out tag:

terraform.tfvarsHCL
server = {
  name = "api"
  port = 9000
}
TerminalBash
tofu apply
Output (the lines that matter)Plain text
Outputs:

server = {
  "name" = "api"
  "port" = 9000
  "tag" = tostring(null)
}

Clean Up

Run tofu destroy and type yes to remove the output from the state, then delete the folder.

Common Mistakes

MistakeWhat happensDo this instead
Leaving out an attribute that isn’t optionalOpenTofu rejects the value: every other attribute is required.Mark it optional(…), or always set it.
Checking an optional attribute without a default for a valueIt can be null.Give it a default, or handle null.

FAQ

What if a caller sets the attribute to null?

The docs say a non-null default is used then too, so the attribute is never null.

Can a default be a whole object?

Yes. The docs show nested objects with their own optional attributes.

Conclusion

Write optional(<TYPE>, <DEFAULT>) inside an object type to let callers leave an attribute out.

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.

0 comments