Shashi Techlogues

Terraform accessing data from maps and list in the variable

In this post, we will discuss a use case where we want to access the variable value which is part of the list or the map.

Let’s try to understand the use case with an example:

resource "aws_instance" "myec2" {
    ami           = "ami-082b5a644766e0e6f"
    instance_type = <INSTANCE_TYPE>
}

variable "list" {
    type    = list
    default = ["t2.nano", "t2.micro", "t2.medium"]
}

variable "types" {
    type = map
    default = {
        dev  = "t2.nano"
        int  = "t2.micro"
        prod = "t2.medium"
    }
}

Here we want to assign a value for the instance_type from either variable list or variable types. Variable list is a list type and variable types is a map type.

Accessing a Value from a List

First, let’s use the list variable. To access the value from the list variable we will use the position. We want to assign, let’s say, t2.micro. In that case, we want position 1.

resource "aws_instance" "myec2" {
    ami           = "ami-082b5a644766e0e6f"
    instance_type = var.list[1]
}

Lists use zero-based indexing, so var.list[1] refers to the second item in the list, which is t2.micro.

Accessing a Value from a Map

Similarly, for the map type:

resource "aws_instance" "myec2" {
    ami           = "ami-082b5a644766e0e6f"
    instance_type = var.types["us-east-1"]
}

In the map type, we refer to the key.


In the subsequent article, we will explore more of Terraform.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Happy Coding!!!