Skip to main content
0 reactions

How to Use the cidrhost Function in OpenTofu

Card titled The cidrhost Function, labelled OpenTofu Functions, showing cidrhost(192.168.1.0/24, 10) and the result 192.168.1.10.
Work out a host’s IP address in a network with OpenTofu’s cidrhost function

cidrhost gives the IP address of a numbered host inside a network written in CIDR notation, such as 192.168.1.0/24. It works for IPv4 and IPv6.

Syntax

SyntaxHCL
cidrhost(<PREFIX>, <HOSTNUM>)
  • <PREFIX>: a network in CIDR notation, an address and a prefix length, such as "10.0.0.0/24".
  • <HOSTNUM>: the host’s number inside that network. It has to fit into the bits that the prefix leaves free.

The docs say host 0 is usually the network’s own address and the all-ones number its broadcast address: cidrhost Function (opens in a new tab).

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:

TerminalBash
tofu console

Type each expression to see the address it returns. The last host number is too big for a /24 network:

tofu consolePlain text
> cidrhost("192.168.1.0/24", 10)
"192.168.1.10"
> cidrhost("10.0.0.0/24", 255)
"10.0.0.255"
> cidrhost("127.0.0.1/32", 0)
"127.0.0.1"
> cidrhost("10.0.0.0/24", 300)
╷
│ Error: Error in function call
│
│   on <console-input> line 1:
│   (source code not available)
│
│ Call to function "cidrhost" failed: prefix of 24 does not accommodate a host numbered 300.
╵

> 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
A host number that doesn’t fit the prefixIt stops with prefix of 24 does not accommodate a host numbered 300.Use a number inside the network’s range, or a shorter prefix.
Using host 0 or the last number for a serverThe docs say those are usually the network and broadcast addresses.Number hosts from 1.

FAQ

Can cidrhost check that an IPv4 address is valid?

Yes: cidrhost("127.0.0.1/32", 0) returns the address itself, and an invalid one fails, so can(cidrhost("${var.address}/32", 0)) works as a check.

Does it work with IPv6?

Yes. The docs say the result uses the same address family as the prefix.

Conclusion

cidrhost(<PREFIX>, <HOSTNUM>) returns the IP address of a numbered host inside a network.

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