Terraform Function - Part 1 [lookup] - with examples

Terraform Function - Part 1 [lookup] - with examples

Terraform Functions

In this blog, we'll explore two practical examples that illustrate how to leverage the lookup function in real-world scenarios.

Understanding the Lookup Function

Before diving into the examples, let's clarify what the lookup function does. It's used to retrieve the value of a specified key from a map, with the option of returning a default value if the key is not found. The syntax is straightforward:

lookup(map, key, default)
#In terraform console: 
--> lookup({a="ab",b="bc"},"a","default"}
--> output : ab

Example 1: Basic Dynamic Instance Types

Scenario

You're tasked with creating EC2 instances in AWS for different environments, such as development and production, each requiring different instance types.

Implementation

First, we define a map of environment types to their corresponding AWS instance types:

varaible "instance_types" {
    description = "Mapping of environments to instance types"
    type = map(string)
    default = {
        "dev" = "t2.micro"
        "stage" = "t2.small"
        "prod" = "t2.medium"
    }
}

variable "environment" {
    description = "The selected environment (dev,stage or prod)
    type = string
    default = "dev"
}

resource "aws_instance" "my_instance" {
    ami = "ami-0c55b159cbfafe1f0"
    instance_type = lookup(var.instance_types, var.environment, t2.micro)
    # Additional configurations
}

This script dynamically sets the instance_type based on the environment variable value passed.

Example 2: Complex Application Configurations

Scenario

Now, consider a scenario where you need to manage a variety of EC2 instances for different applications, each requiring specific configurations such as instance types, security groups, and IAM roles.

Implementation

We expand our Terraform script to include a more complex structure:

variable "app_configs" {
    description = "Mapping app type to configurations"
    type = map(any)
    default = {
        "web" = {
            instance_type = "t2.micro"
            security_groups = ["web-sg"]
            iam_role = "web-role"
        },
        "database" = {
            instance_type = "t3.large"
            security_groups = ["db-sg"]
            iam_role = "db-role"
        }
    }
}

resource "aws_instance" "app_instance" {
    for_each = var.app_configs

    ami = "ami-0c55b159cbfafe1f0"
    instance_type = lookup(each.value, "instance_type", "t2.micro"
    instance_role = lookup(each.value, "iam_role", null)

    tags = {
        Name = "Instance-${each.key}"
    }
    #Additional Configurations
}

output "instance_id" {
    value = { for k, v in aws_instance.app_instance : k => v.id }
}

In this script, we use a for_each loop to create instances for each application type, with their configurations specified in the app_configs map. The lookup function dynamically sets each instance's properties.