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
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
- 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 address it returns. The last host number is too big for a /24 network:
> 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
| Mistake | What happens | Do this instead |
|---|---|---|
| A host number that doesn’t fit the prefix | It 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 server | The 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