You can use the split()
function in Terraform to allow you to split up a string in your terraform plans. The terraform split function has two inputs, the separator character, and the string we wish to perform the split operation on. The syntax here is similar to the terraform join function.
split(separator, string)
Let’s take a look at how to use the split function in the terraform console.
> split(",", "one,two,three")
[
"one",
"two",
"three",
]
As you can see in the example above, we have taken the string “one,two,three” and have told terraform to split it using the comma as the separator. This has resulted in a list of three separate items. We can then use the list index to retrieve a individual item:
> split(",", "one,two,three")[0]
"one"
> split(",", "one,two,three")[2]
"three"
So, how could this be used in a terraform plan? Read on!
A common reason to use the split function in a Terraform plan is to split up a string that has been returned as an output (or a module output). For example, if we had a output that contained a string of comma separated IP addresses, we may have a need to split the string into a list so that we can use the individual IP addresses elsewhere in the plan, or to output the individual values. This could be used, for example, to create a DNS entry.
Let’s take a look at how this might be done.
# Defined Output
output "ip_addresses" {
value = demo.mydempapp.outbound_ip_addresses
}
# Terraform Plan Output
Changes to Outputs:
+ ipaddreses = "192.168.0.1,192.168.0.2,192.168.0.3"
This has returned a single string with some comma separated IP addresses. Now, if we wanted to return only the middle IP address we could use the split function to split the string into a list:
# split up the string
output "ip_addresses" {
value = split(",",demo.mydempapp.outbound_ip_addresses)
}
# Terraform Plan Output
Changes to Outputs:
+ ipaddreses = [
+ "192.168.0.1",
+ "192.168.0.2",
+ "192.168.0.3",
]
# return only the middle IP
output "middle_ip" {
value = split(",",demo.mydempapp.outbound_ip_addresses)[1]
}
# Terraform Plan Output
Changes to Outputs:
+ ipaddreses = "192.168.0.2"
A short article, but hopefully one that demonstrates how you can use the split function in Terraform to split up a string into a list, and return individual values.