0

There is a list of strings which are the output of vnet peering details. I need to extract all the source vnet names in one list and destination vnet names in another list. My vnet peering names are as below

Peer =["vnet1tovnet2",
       "vnet1tovnet3",
       "vnet4tovnet5"]

I need two lists in below format

source=["vnet1","vnet1",vnet4"]
dest=["vnet2","vnet3","vnet5"]

How can this be achieved in terraform

Madhuraj Vadde
  • 1,099
  • 1
  • 5
  • 13
kanmani1303
  • 85
  • 3
  • 13
  • You can use **substr** function to get the desired output : https://www.terraform.io/language/functions/substr – RamaraoAdapa Jan 13 '22 at 03:38
  • I need to get the string before the word "to" and after the word "to". Can we achieve this through substring function since it expects offset and length. The string length before and to will not be the same always right. – kanmani1303 Jan 13 '22 at 06:56
  • Since Peer is a list of strings we cannot use split function for all the values. Count index cannot be used in local block. What can be done to fetch the values and store the values in a new list – kanmani1303 Jan 13 '22 at 08:01

1 Answers1

2

You can do that as follows:

locals{

  Peer =["vnet1tovnet2",
         "vnet1tovnet3",
         "vnet4tovnet5"]
    
  source = [for v in local.Peer: split("to", v)[0]]
  dest = [for v in local.Peer: split("to", v)[1]]

}
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • using the index gives only the first element in the array. I am not able to use this snippet in local block since I couldn't use COUNT in local block. Is there any other way to implement it to get all the elements into a new array after split function. – kanmani1303 Jan 13 '22 at 11:37
  • @Ramya Your question does not mention any count or provides any examples of how are you using it with any errors. I would suggest making new question with tf code exemplifying your issue. – Marcin Jan 13 '22 at 11:56
  • The source list returns only vnet1 and vnet4 though there are 2 entries of vnet1 but the other list dest returns all the 3 entries like vnet2,vnet3,vnet3. I want all the 3 entries of source array. – kanmani1303 Jan 13 '22 at 13:11
  • If the same value appears multiple times in keyslist when zipmap is used then the value with the highest index is used in the resulting map. This is how it behaves. How can we overcome this behaviour? – kanmani1303 Jan 13 '22 at 19:09