Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a comma separated string

I have an output that is a multi-valued, comma separated string.

input.tf

resource "azurerm_app_service" "testap" {
  name                = "MySuperCoolAppServer001"
  location            = "eastus"
  resource_group_name = "notshown"
  app_service_plan_id = "notshown"
}

output.tf

output "output_tf_testap_outbound_ip_addresses" {
  value = "${azurerm_app_service.testap.outbound_ip_addresses}"
}

And I get this in the console:

output_tf_testap_outbound_ip_addresses = 1.2.3.4,1.2.3.5,1.2.3.6,1.2.3.7,1.2.3.8,1.2.3.9

How do I get the first item of the list? In this case, I'm trying to isolate the value:

1.2.3.4

Is there a way to get a "collection" of all the items when the total number of items is not known before run time? (The list above has 6 items).

The following code doesn't seem to work:

output "first_ip" {
  value = ["${azurerm_app_service.testap.outbound_ip_addresses[0]}"]
}

===================== APPEND =================

first_ip_no_index works. first_ip does not

output "first_ip_no_index" {
  value = ["${split(",", azurerm_app_service.tf_middle_tier_azurerm_app_service.outbound_ip_addresses)}"]
}

output "first_ip" {
  value = "${split(",", azurerm_app_service.tf_middle_tier_azurerm_app_service.outbound_ip_addresses)[0]}"
}

first_ip generated this error:

Error reading config for output first_ip: parse error at 1:91: expected "}" but found "["

like image 445
granadaCoder Avatar asked Jul 13 '18 14:07

granadaCoder


1 Answers

You can use the split() function to split a string into a list.

output "output_tf_testap_outbound_ip_addresses" {
  value = ["${split(",", azurerm_app_service.testap.outbound_ip_addresses)}"]
}

After that you can then index it by using the element(list, index) syntax:

output "first_ip" {
  value = "${element(split(",", azurerm_app_service.testap.outbound_ip_addresses), 0}"
}

You should also normally be able to use the list\[index\] syntax like this:

output "first_ip" {
  value = "${split(",", azurerm_app_service.testap.outbound_ip_addresses)[0]}"
}

However there seems to be a bug in Terraform 0.11 that prevents slicing the result of the split function, throwing the following error:

Error: Error loading /tmp/tf-split-test/main.tf: Error reading config for output foo: parse error at 1:25: expected "}" but found "["

You could use a local to split the list and then slice that to get around this if you'd prefer to use this syntax over the element function.

locals {
  outbound_ip_addresses_list = "${split(",", azurerm_app_service.testap.outbound_ip_addresses)}"
}

output "first_ip" {
  value = "${local.outbound_ip_addresses_list[0]}"
}
like image 144
ydaetskcoR Avatar answered Nov 01 '22 17:11

ydaetskcoR