Site icon JD Bots

OpenTofu Logical Operators: &&, || and !

Card titled Logical Operators, labelled OpenTofu Operators, showing true || false and the result true.

Combine true and false values in OpenTofu with &&, || and !

The logical operators combine true and false values: && needs both, || needs either, and ! turns one into the other.

Syntax

Syntax

<A> && <B>
<A> || <B>
!<A>

The docs describe them in Logical Operators.

Prerequisites

Step 1: Create a Small Configuration

In an empty folder, create main.tf with a variable that’s null by default:

main.tf

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:

Terminal

tofu console

Type each expression to see the result:

tofu console

> 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

MistakeWhat happensDo this instead
Writing and or or in wordstrue and false stops with Extra characters after expression.Use && and ||.
Expecting the skipped side to be ignored completelyThe 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.

Exit mobile version