terraform element code example

Example 1: element function in terraform

#Element retrieves single element from the list
element(list, index)

#Example to Understand
element(["a", "b", "c"], 1)
b

element(["a", "b" , "c"], 0)
a

Example 2: lookup function in terraform

#lookup retrieves the value of a single element from a map, given its key. 
#If the given key does not exist, a the given default value is returned instead.

lookup(map, key, default)

#Example to Understand

lookup({a="ay", b="bee"}, "a", "what?")
ay

lookup({a="ay", b="bee"}, "c", "what?")
what?

Example 3: terraform element function

resource "aws_instance" "ec2_instance" {

count = 2
user_data = element([data.template_file.user_data_file1.rendered, 
                     data.template_file.user_data_file2.rendered], 
                     count.index)

tags = {
    Name = element(var.ec2_instance_names, count.index)
  }

}