Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: Convert list of object to list of single element from object

Tags:

terraform

I have a list of objects from a variable in terraform

variable "persons" {
  type = list(object({
    name = string,
    phonenumber = string,
    tshirtSize = string
  }))
    description = "List of person"
}

Now I want a list of the person's names so I can use it to define an AWS Resource

How can I convert this object list to a list of names ["bob", "amy", "jane"]

I'm on terraform 0.12.24, though can upgrade if needed

like image 454
GoldFlsh Avatar asked Jul 10 '20 14:07

GoldFlsh


People also ask

What terraform function is used to return a single element from a list at the given index?

» element Function element retrieves a single element from a list. The index is zero-based.

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);


1 Answers

Updated Answer:
Use the splat expression

var.persons[*].name

https://www.terraform.io/docs/configuration/expressions.html#splat-expressions

Original Answer:
I was able to do this in locals file

locals {
  names = [
    for person in var.persons:
    person.name
  ]
}

For additional reading SEE: https://www.hashicorp.com/blog/hashicorp-terraform-0-12-preview-for-and-for-each/

like image 128
GoldFlsh Avatar answered Nov 15 '22 10:11

GoldFlsh