Mastering the Terraform Lookup Function for Dynamic Keys

1. Introduction

Infrastructure as code (IaC) is a key part of gaining efficiency, scalability, and manageability in the rapidly changing tech world of today. Many DevOps teams now use Terraform, which is a famous IaC tool.

The Terraform lookup function for dynamic keys has become a powerful way to improve your IaC workflows. This is one of its many benefits. In this piece, we'll go over the Terraform lookup function for dynamic keys and show you how to use it to its full potential.

Table of Content

  1. Introduction
  2. Terraform Lookup Function for Dynamic Keys
  3. Advanced Applications of the Terraform Lookup Function
  4. Frequently Asked Questions on lookup function
  5. Conclusion

2. Terraform Lookup Function for Dynamic Keys

The Terraform lookup function for dynamic keys is a useful tool that lets you get to values in a map or object data structure.

By giving a key and a default value, you can get data quickly and make sure your code is flexible and easy to keep up-to-date.

2.1 Syntax and Usage

The basic syntax for the Terraform lookup function is as follows:

1lookup(map, key, default) 
  • map: The map or object data structure you want to access.
  • key: The key within the map that you want to look up.
  • default: The value to return if the key is not found in the map.

Examples of how the Lookup function works

Here are two examples of how the Terraform lookup method for dynamic keys can be used:

 1variable "regions" {
 2  default = {
 3    "us-west-1" = "us-west-1a"
 4    "us-west-2" = "us-west-2a"
 5  }
 6}
 7
 8output "availability_zone" {
 9  value = lookup(var.regions, "us-west-1", "us-west-1b")
10} 

In this example, the lookup function retrieves the value for the "us-west-1" key, returning "us-west-1a".

 1locals {
 2  instance_types = {
 3    "t2.micro"   = "free tier"
 4    "m5.large"   = "general purpose"
 5    "c5.xlarge"  = "compute optimized"
 6  }
 7}
 8
 9output "instance_type_info" {
10  value = lookup(local.instance_types, "t2.micro", "unknown")
11} 

This example shows how to use the lookup function in a locals block by giving the key t2.micro the value free tier for the key.


3. Advanced Applications of the Terraform Lookup Function

The lookup method for dynamic keys in Terraform can be used in a number of advanced ways to improve your IaC workflows:

3.1 1. Conditional resource creation

Use the lookup function with the count meta-argument to make resources based on which configuration keys are present.

 1variable "instance_types" {
 2  default = {
 3    "t2.micro"   = "free tier"
 4    "m5.large"   = "general purpose"
 5    "c5.xlarge"  = "compute optimized"
 6  }
 7}
 8
 9resource "aws_instance" "example" {
10  count         = lookup(var.instance_types, "t2.micro", "") != "" ? 1 : 0
11  instance_type = "t2.micro"
12  ami           = "ami-0c94855ba95b798c7" # Example Amazon Linux 2 AMI ID
13} 

In this case, the aws_instance resource is only created if the instance_types variable has a "t2.micro" key.


3.2 2. Dynamic module inputs

Use the lookup function inside a module to give the module inputs that are flexible and changeable. This makes it easy to reuse and change your code.

 1# main.tf
 2module "aws_vpc" {
 3  source      = "./modules/vpc"
 4  region_info = {
 5    "us-west-1" = "us-west-1a"
 6    "us-west-2" = "us-west-2a"
 7  }
 8  region = "us-west-1"
 9}
10
11# modules/vpc/main.tf
12variable "region_info" {
13  type = map(string)
14}
15
16variable "region" {
17  type = string
18}
19
20resource "aws_vpc" "example" {
21  cidr_block = "10.0.0.0/16"
22  tags = {
23    Name = "example-vpc"
24    Zone = lookup(var.region_info, var.region, "unknown")
25  }
26} 

In this case, the "Zone" tag of the aws_vpc resource in the module will be set based on the region input and the value in the region_info map that goes with it.


3.3 Attribute validation

Use the lookup tool to check if attributes are correct and to make sure that your Terraform configuration only uses valid keys.

 1variable "allowed_instance_types" {
 2  default = {
 3    "t2.micro"   = true
 4    "m5.large"   = true
 5    "c5.xlarge"  = true
 6  }
 7}
 8
 9variable "selected_instance_type" {
10  default = "t2.micro"
11}
12
13locals {
14  is_instance_type_allowed = lookup(var.allowed_instance_types, var.selected_instance_type, false)
15}
16
17resource "aws_instance" "example" {
18  count         = local.is_instance_type_allowed ? 1 : 0
19  instance_type = var.selected_instance_type
20  ami           = "ami-0c94855ba95b798c7" # Example Amazon Linux 2 AMI ID
21} 

In this example, the aws_instance resource will only be made if the chosen instance type is in the allowed_instance_types map.


3.4 Combine Lookup with Other Terraform Functions

You can make even more powerful and flexible configurations by combining the lookup function with other Terraform methods.

For example, you can use the [merge()][12] method to combine multiple maps before calling the lookup function.

 1locals {
 2  default_tags = {
 3    Owner       = "DevOps Team"
 4    Environment = "Development"
 5  }
 6
 7  custom_tags = {
 8    Project = "example-project"
 9  }
10
11  all_tags = merge(local.default_tags, local.custom_tags)
12}
13
14resource "aws_instance" "example" {
15  ami           = "ami-0c94855ba95b798c7" # Example Amazon Linux 2 AMI ID
16  instance_type = "t2.micro"
17
18  tags = {
19    Name = "example-instance"
20    Team = lookup(local.all_tags, "Owner", "unknown")
21  }
22} 

In this case, the "Team" tag of the aws_instance resource is taken from the map of both default and custom tags.


3.5 Error Handling with the Terraform Lookup Function

Even though the lookup method gives a default value if the given key isn't found, it's important to deal with errors in a good way.

When you use the try() function with the lookup function, you can make sure that your Terraform setup keeps working even if you run into keys or data structures you didn't expect.

 1locals {
 2  instance_info = {
 3    "t2.micro"   = "free tier"
 4    "m5.large"   = "general purpose"
 5    "c5.xlarge"  = "compute optimized"
 6  }
 7}
 8
 9output "instance_description" {
10  value = try(lookup(local.instance_info, "t2.micro", ""), "Key not found")
11} 

In this example, the try() function is used to handle cases where the lookup function might fail, providing a fallback message when the key is not found.


3.6 Use Lookup Function for Simplifying Complex Configurations

The lookup function for dynamic keys in Terraform can also be used to simplify complicated setups by getting rid of code blocks that do the same thing over and over again.

By making a map of values for different keys, you can use the lookup function to set traits for your resources on the fly. This makes your code more concise and easier to keep up-to-date.

 1variable "env_info" {
 2  default = {
 3    "prod" = {
 4      "instance_type" = "m5.large"
 5      "ami"           = "ami-0c94855ba95b798c7"
 6    }
 7    "dev" = {
 8      "instance_type" = "t2.micro"
 9      "ami"           = "ami-0c94855ba95b798c7"
10    }
11  }
12}
13
14locals {
15  current_env = "dev"
16}
17
18resource "aws_instance" "example" {
19  ami           = lookup(var.env_info[local.current_env], "ami", "ami-0c94855ba95b798c7")
20  instance_type = lookup(var.env_info[local.current_env], "instance_type", "t2.micro")
21}
22 

4. Frequently Asked Questions on lookup function

1. What is the point of the lookup method for dynamic keys in Terraform?

The lookup method for dynamic keys in Terraform is used to get to values in a map or object data structure. By giving a key and a default value, you can get data quickly and make sure that your code is flexible and easy to keep up to date.

2. How do I use Terraform's finding function?

Follow this code in Terraform to use the search function:

1lookup(map, key, default) 

map: The map or object data structure you want to access. key: The key within the map that you want to look up. default: The value to return if the key is not found in the map.

3. Can I use the lookup function with lists or arrays?

No, the Terraform lookup method for dynamic keys is not made to work with lists or arrays. Instead, it is made to work with map and object data structures. But you can get to the items in a list by using the element() method.

4. What happens if the specified key is not found in the map?

If the given key isn't in the map, the lookup method of Terraform will return the default value.

5. Can I use the lookup function within a module?

Yes, you can use the Terraform lookup function to add more freedom to module inputs by using dynamic keys in a module.

6. Is the Terraform lookup function available in all versions of Terraform?

After Terraform 0.12, you can use the lookup tool. For older versions, you might have to use the map() and element() methods to get the same results.


5. Conclusion

The lookup function for dynamic keys in Terraform is a powerful and flexible tool that can improve your IaC workflows in a big way. If you know a lot about its syntax, how to use it, and more advanced uses, you'll be ready to handle difficult infrastructure providing problems.

So, whether you're an experienced DevOps worker or a newcomer to the world of IaC, we hope this detailed guide has helped you learn more about the lookup function for dynamic keys in Terraform. By using this powerful tool, you'll be able to set up infrastructures that are more efficient, scalable, and easy to handle.

Posts in this series