Faced with an issue during working on terraform code, wrote a little example and hope somebody of you will help me to resolve my issue.
Current code looks like:
variable "aws-subnets" {
description = "Test rule"
default = [
"10.0.0.0/32:us-east-1-s3",
"10.0.0.1/32:us-east-2-s3",
"10.0.0.2/32",
"",
]
}
data "template_file" "ipset-wrapper" {
count = "${length(var.aws-subnets)}"
template = <<TXT
$${SUBNET_RANGE} comment $${SUBNET_COMMENT}
TXT
vars {
SUBNET_RANGE = "${element(split(":",var.aws-subnets[count.index]),0) != "" ? "${element(split(":",var.aws-subnets[count.index]),0)}" : "no_ip" }"
SUBNET_COMMENT = "${element(split(":",var.aws-subnets[count.index]),1) != "" ? "${element(split(":",var.aws-subnets[count.index]),1)}" : "no_comment_provided" }"
),2))}"
}
}
output "ipset-rules" {
value = "${data.template_file.ipset-wrapper.*.rendered}"
}
The output now:
Outputs:
ipset-rules = [
10.0.0.0/32 comment us-east-1-s3
,
10.0.0.1/32 comment us-east-2-s3
,
10.0.0.2/32 comment 10.0.0.2/32
,
no_ip comment 0 no_comment_provided
]
3d string, instead of return unknown element or element empty, returned the last element from split command, that's why condition:
${element(split(":",var.aws-subnets[count.index]),1) != ""}
doesn't work for me as expected
what is the best approach in that case to write a code, if second index wasn't defined?
I understand that code:
SUBNET_COMMENT = "${element(split(":",var.aws-subnets[count.index]),1) != element(split(":",var.aws-subnets[count.index]),0) ? "${element(split(":",var.aws-subnets[count.index]),1)}" : "no_comment_provided" }"
works well in that case, but if won't work if I will have more than 2 indexes.
any help?