I tried to do so
private_ip_ws0 = ["10.0.10.3"]
private_ip_ws1 = ["10.0.20.3"]
private_ip_db0 = ["10.0.11.3"]
private_ip_db1 = ["10.0.21.3"]
resource "aws_network_interface" "ws_interface" {
count = 2
subnet_id = aws_subnet.ws_net_public[count.index].id
private_ips = "${var.private_ip_ws}[count.index]"[0]
tags = {
Name = "${var.environment}${count.index}-Interface"
}
}
But I get error:
Error: Reference to undeclared input variable
│
│ on vpc.tf line 55, in resource "aws_network_interface" "ws_interface":
│ 55: private_ips = "${var.private_ip_ws}[count.index]"[0]
│
│ An input variable with the name "private_ip_ws" has not been declared. Did you mean "private_ip_ws1"?
How to write code correctly?
And why in one place Terraform allows you to write like this
cidr_block = "${var.public_cidr}${count.index 1}0.0/24"
but in another similar expression it doesn't allow to write:
private_ips = "${var.private_ip_ws}[count.index]"[0]
Why?
CodePudding user response:
You can't reference a variable name via a variable like that. That just isn't a feature supported by Terraform at all. The correct way to do this would be to convert your variables into arrays, but if you want to keep the variables the same you will need to wrap them in a local array before using them:
private_ip_ws0 = ["10.0.10.3"]
private_ip_ws1 = ["10.0.20.3"]
private_ip_db0 = ["10.0.11.3"]
private_ip_db1 = ["10.0.21.3"]
locals {
private_ip_ws = [private_ip_ws0, private_ip_ws1]
}
resource "aws_network_interface" "ws_interface" {
count = 2
subnet_id = aws_subnet.ws_net_public[count.index].id
private_ips = local.private_ip_ws[count.index]
tags = {
Name = "${var.environment}${count.index}-Interface"
}
}
And why in one place Terraform allows you to write like this
cidr_block = "${var.public_cidr}${count.index 1}0.0/24"
but in another similar expression it doesn't allow to write:
private_ips = "${var.private_ip_ws}[count.index]"[0]
Because in the first example you are just doing basic string interpolation, which is perfectly valid Terraform syntax.
In the second example you are building a dynamic variable name and then trying to reference the value inside that variable, which is completely invalid Terraform syntax.