I want to get host IPs out of two subnets in AWS using Terraform/Terragrunt and the cidrhost function.
For some reason, the subnets are being injected into cidrhost in the wrong order.
The remote state it's checking looks like this:
"firewall_subnets_cidr_blocks": {["10.0.0.96/28", "10.0.0.112/28"]}
The first subnet is in 1a and the second in 1b
And this is my code:
resource "aws_network_interface" "private" {
count = length(var.firewall_subnets) > 0 ? length(var.firewall_subnets) : 0
subnet_id = element(var.firewall_subnets, count.index)
private_ip = cidrhost(tolist(var.firewall_subnets_cidr_blocks)[count.index], 10)
description = "Private Interface"
security_groups = [aws_security_group.sg_firewall_private.id]
source_dest_check = false
}
Whenever I run it, it puts the first subnet into the second - the 1b - interface and vice versa.
# aws_network_interface.private[0] will be created
+ resource "aws_network_interface" "private" {
+ description = "Private Interface"
+ private_ip = "10.0.0.122"
# aws_network_interface.private[1] will be created
+ resource "aws_network_interface" "private" {
+ description = "Private Interface"
+ private_ip = "10.0.0.106"
It only happens on this interface script; management and public are identical and behaving as expected.
TF 1.1.9 TG 0.37.3
Digging into the documentation I found this statement:
For a new network interface, the same primary IP address is consistently selected from a given set of addresses, regardless of the order provided.
This sorting happens before the list is passed to my functions resulting in the wrong IPs going to the wrong subnet/AZ.
To override this behaviour I've set private_ip_list_enabled
to true
.
Here's my working code:
resource "aws_network_interface" "private" {
count = length(var.private_subnets) > 0 ? length(var.private_subnets) : 0
subnet_id = element(var.private_subnets, count.index)
private_ip_list_enabled = true
private_ip_list = tolist([cidrhost(element(var.private_subnets_cidr_blocks, count.index), 10)])
description = "Private Interface"
source_dest_check = false
}
Victory is mine!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.