ipeacocks
ipeacocks

Reputation: 2317

Modify simple list/array in Terraform

I have a next list:

azs = ["us-east-1a", "us-east-1b", "us-east-1c"]

And I am using it during subnets creation. In names of subnets I would like to use short names like a, b, c so I need a list ["a", "b", "c"]. Obviously I need to generate it dynamically (in locals block for example) when azs will be set manually.

How to create such list with Terraform?

Upvotes: 3

Views: 3573

Answers (2)

Alex Rodriguez
Alex Rodriguez

Reputation: 11

You can use a combination of for and the regex function to manipulate the items in your list.

locals {
    azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
}

output "azsList" {
    value = [for v in local.azs : regex("us-east-1([a-z])", v)]
}

output "azsMap" {
    value = {for v in local.azs : v => regex("us-east-1([a-z])", v)}
}

...

resource "example" "example"{
  dynamic "setting_section_name" {
    for_each = [for v in local.azs : regex("us-east-1([a-z])", v)]
    content {
      value = setting_section_name.value
    }
  }
}

You can change out the regex pattern to whatever you want.

Here are some helpful links:

Terraform Regex Reference

Regex 101 an online regex tool

Upvotes: 1

ydaetskcoR
ydaetskcoR

Reputation: 56997

You can use the formatlist function here to format a list.

It uses the string format syntax, taking n lists and returning a single list.

So in your case you probably want something like:

locals {
  azs = [
    "a",
    "b",
    "c",
  ]
}

output "azs" {
  value = "${formatlist("us-east-1%s", local.azs)}"
}

Upvotes: 4

Related Questions