The logical operators combine true and false values: && needs both, || needs either, and ! turns one into the other.
Syntax
<A> && <B>
<A> || <B>
!<A>
<A>,<B>: bool values, or expressions that give one, such as a comparison.
The docs describe them in Logical Operators (opens in a new tab).
Prerequisites
- OpenTofu® installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Create a Small Configuration
In an empty folder, create main.tf with a variable that’s null by default:
variable "settings" {
type = object({
port = number
})
default = null
}
Step 2: Try It in tofu console
This configuration uses no providers, so the console works without tofu init. Start it in the folder:
tofu console
Type each expression to see the result:
> true && false
false
> true || false
true
> !true
false
> var.settings == null || var.settings.port > 0
true
> exit
The last line didn’t fail on var.settings.port, although var.settings is null: the docs say that since OpenTofu 1.10, || and && skip the right side once the left side decides the result.
Clean Up
Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Writing and or or in words | true and false stops with Extra characters after expression. | Use && and ||. |
| Expecting the skipped side to be ignored completely | The docs say it’s still checked, for example that the variable it uses exists. | Refer only to things that are declared. |
FAQ
Which goes first, && or ||?
Use parentheses to make the order clear, such as (a || b) && c.
Is there an exclusive OR?
No. The docs say != between two bools does the same.
Conclusion
&&, || and ! combine bool values, and the first two skip their right side when the left side already decides.
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