user3616775
user3616775

Reputation: 85

Convert from Tuple of strings to strings in terraform

I have an issue where I want to pass a list of vpc_ids to aws_route53_zone while getting the id from a couple of module calls and iterating it from the state file.

The out put format I am using is:

output "development_vpc_id" {
  value       = [for vpc in values(module.layout)[*] : vpc.id if vpc.environment == "development"]
  description = "VPC id for development env"
}

where I get the output like:

  "development_vpc_id": {
      "value": [
        "xxxx"
      ],
      "type": [
        "tuple",
        [
          "string"
        ]
      ]
    },

instead I want to achieve below:

  "developmemt_vpc_id": {
      "value": "xxx",
      "type": "string"
    },

Can someone please help me with the same.

Upvotes: 1

Views: 5917

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74064

There isn't any automatic way to "convert" a sequence of strings into a single string, because you need to decide how you want to represent the multiple separate strings once you've reduced it into only a single string.

One solution would be to apply JSON encoding so that your output value is a string containing JSON array syntax:

output "development_vpc_id" {
  value = jsonencode([
    for vpc in values(module.layout)[*] : vpc.id
    if vpc.environment == "development"
  ])
}

Another possibility is to concatenate all of the strings together with a particular character as a marker to separate each one, such as a comma:

output "development_vpc_id" {
  value = join(",", [
    for vpc in values(module.layout)[*] : vpc.id
    if vpc.environment == "development"
  ])
}

If you expect that this list will always contain exactly one item -- that is, if each of your objects has a unique environment value -- then you could also tell Terraform about that assumption using the one function:

output "development_vpc_id" {
  value = one([
    for vpc in values(module.layout)[*] : vpc.id
    if vpc.environment == "development"
  ])
}

In this case, Terraform will either return the one element of this sequence or will raise an error saying there are too many items in the sequence. The one function therefore acts as an assertion to help you detect if there's a bug which causes there to be more than one item in this list, rather than just silently discarding some of the items.

Upvotes: 2

Related Questions