1

I am working with vm deployments over AWS with terraform(v1.0.9) as infrastructure as code. i have Terraform output.tf to print two lan a ips and code prints, list of lists like [["ip_a",],["ip_b",]] but i want a list like this ["ip_a", "ip_b"].

output.tf code

`output "foo" {
 value = {
 name = "xyz"
 all_ips = tolist(aws_network_interface.vm_a_eni_lan_a.*.private_ips)
}
}`

printing --> "name" = "xyz" "lan_a_ips" = tolist(\[ toset(\[ "10.0.27.116",\]), toset(\[ "10.0.28.201",\]), \])

but i want "lan_a_ips" = ["10.0.27.116", "10.0.28.201"]

I beleive tweaking output.tf can help. Any help is appreciated.

Vinay Gowda
  • 25
  • 1
  • 5

1 Answers1

2

In your case, you have just set the splat expression [1] in a wrong place, i.e., instead of setting aws_network_interface.vm_a_eni_lan_a.private_ips[*] you set it to aws_network_interface.vm_a_eni_lan_a.*.private_ips. So you only need to change the output value:

output "foo" {
 value = {
  name = "xyz"
  all_ips = aws_network_interface.vm_a_eni_lan_a.private_ips[*]
 }
}

EDIT: The above applies when only a single instance of an aws_network_interface resource is created. For situations where there are multiple instance of this resource created with count meta-argument, the following can be used to get a list of IPs:

output "foo" {
  value = {
    name    = "xyz"
    all_ips = flatten([for i in aws_network_interface.test[*] : i.private_ips[*]])
  }
}

Here, the for [2] loop is used to iterate over all the instances of a resource, hence the splat expression when referencing them aws_network_interface.test[*]. Additionally, since this will create a list of lists (as private_ips[*] returns a list), flatten [3] built-in function can be used to create a single list of IP addresses.


[1] https://www.terraform.io/language/expressions/splat

[2] https://www.terraform.io/language/expressions/for

[3] https://www.terraform.io/language/functions/flatten

Marko E
  • 13,362
  • 2
  • 19
  • 28
  • Thanks Marko for replying. But we are having two interface lan_a[0] and lan_a[1]. We are using count.index to create two ips. By tring as u mentioned gives this error -->"aws_network_interface.vm_a_eni_lan_a has "count" set, its attributes must be accessed on specific instances. │ │ For example, to correlate with indices of a referring resource, use: │ aws_network_interface_vm_a_eni_lan_a[count.index] " – Vinay Gowda Apr 05 '22 at 09:43
  • So there is one private IP but two interfaces? – Marko E Apr 05 '22 at 09:57
  • no, we have two Interface named lan_a[0] and lan_a[1] and correspondingly two private IP add (like each interface has unique IP) – Vinay Gowda Apr 05 '22 at 10:30
  • I edited the question, it should work with multiple IPs assigned to multiple interfaces as well. – Marko E Apr 05 '22 at 10:36