The equality operators compare two values: == is true when they’re the same, and != when they’re different. Both the value and the type have to match.
Syntax
<A> == <B>
<A> != <B>
<A>,<B>: any two values. The result istrueorfalse.
The docs say == is true only when both have the same type and value: Equality 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: Try It in tofu console
Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:
tofu console
Type each expression to see the result. The last one compares text with a number:
> "tea" == "tea"
true
> "tea" != "cake"
true
> 8080 == 8080
true
> "8080" == 8080
false
> exit
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 |
|---|---|---|
Comparing "8080" with 8080 | It’s false: one is a string, the other a number. | Compare values of the same type. |
Checking whether a list is empty with == [] | The docs explain it’s never true, because [] is a tuple. | Use length(var.list) == 0. |
FAQ
Can I compare lists and maps?
Yes, but the docs recommend it mainly for simple values, because their types must match exactly.
Is there an exclusive OR?
No; the docs say != between two bools does the same.
Conclusion
== and != compare two values, and they’re equal only when the type matches too.
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