Site icon JD Bots

OpenTofu Equality Operators: == and !=

Card titled Equality Operators, labelled OpenTofu Operators, showing “8080” == 8080 and the result false.

Check whether two OpenTofu values are the same with == and !=, and see why the type has to match too

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

Syntax

<A> == <B>
<A> != <B>

The docs say == is true only when both have the same type and value: Equality Operators.

Prerequisites

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:

Terminal

tofu console

Type each expression to see the result. The last one compares text with a number:

tofu console

> "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

MistakeWhat happensDo this instead
Comparing "8080" with 8080It’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.

Exit mobile version