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
<NAME> = optional(<TYPE>, <DEFAULT>)
<NAME>: the attribute inside theobject({ … })type.<TYPE>: the attribute’s type, such asnumberorstring.<DEFAULT>: optional. The value used when the attribute is missing. Without it, OpenTofu usesnull.
The rules are in Optional Object Type Attributes (opens in a new tab) in the OpenTofu docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
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:
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:
tofu apply
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:
server = {
name = "api"
port = 9000
}
tofu apply
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
| Mistake | What happens | Do this instead |
|---|---|---|
| Leaving out an attribute that isn’t optional | OpenTofu rejects the value: every other attribute is required. | Mark it optional(…), or always set it. |
| Checking an optional attribute without a default for a value | It 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