Sling Academy
Home/DevOps/Terraform: How to Merge 2 Maps

Terraform: How to Merge 2 Maps

Last updated: February 04, 2024

Introduction

In the world of Terraform, managing infrastructure as code is both a practice and a philosophy. One common task that often puzzles newcomers and seasoned users alike is merging 2 maps. This article will guide you through the process, providing insight and real-world code examples to make you proficient in this vital operation.

Understanding Maps in Terraform Context

First, let’s understand what maps are in Terraform. Maps are collections of key-value pairs, where each key maps to exactly one value. They are highly useful for configuring resources with dynamic or complex configurations.

Using the merge() function

To merge two maps in Terraform, we primarily use the merge function. The merge function takes two or more maps as inputs and produces a single map that contains a union of the keys and values from all the input maps. When keys overlap, the value from the map that is later in the argument list will take precedence.

Let’s start with a basic example:

locals {
  map1 = {
    key1 = "value1"
    key2 = "value2"
  }
  map2 = {
    key2 = "newvalue2"
    key3 = "value3"
  }
  merged_map = merge(local.map1, local.map2)
}

output "merged_map" {
  value = local.merged_map
}

In this example, map1 and map2 are merged into merged_map. Note that map1 and map2 have an overlapping key, key2. The value of key2 in the resulting merged_map is newvalue2, showing the precedence of the second map in the merge function arguments.

Dealing with Complex Maps

Now, let’s delve into a more complex scenario involving dynamic blocks. Assume we are managing an AWS resource that requires a complex map of tags:

resource "aws_instance" "example" {
  // other configuration...

  tags = merge(
    var.common_tags,
    {
      "Name" = "ExampleInstance"
    }
  )
}

This code snipett demonstrates merging a variable var.common_tags containing common tags with another map specifying instance-specific tags. This approach allows for flexible and dynamic resource tagging strategies.

Understanding map precedence is crucial when merging maps. If there’s a conflict between map entries, as mentioned earlier, the entry in the map that is rightmost in the merge function’s argument list will prevail. This behavior is useful for overriding default or common configurations with specific settings.

Merging Maps Conditionally

Beyond just merging static maps, Terraform’s dynamic nature enables you to merge maps conditionally. You can incorporate conditionals within your merges to tailor the final map more accurately to your infrastructure needs. For example:

locals {
  condition = terraform.workspace == "production"
  map_prod = {
    env = "production"
  }
  map_default = {
    env = "development"
  }
  merged_map = merge(
    local.map_default,
    local.condition ? local.map_prod : {}
  )
}

Here, merged_map will contain the env: "production" key-value pair only if the Terraform workspace is set to “production”. Otherwise, it defaults to env: "development".

As a final piece of advice, while Terraform’s merge function is powerful, it’s also essential to use it judiciously. Overusing merge, especially with very large maps or in complex configurations, can make your Terraform code harder to understand and maintain. Always aim for clarity and simplicity in your infrastructure code.

Closing Thoughts

Understanding how to merge maps in Terraform is a fundamental skill for anyone looking to harness the full power of infrastructure as code. Through the examples we’ve discussed, you should now feel confident applying this operation in various scenarios.

To further your knowledge, explore the Terraform documentation and experiment with merging maps in your projects. Practical experience, combined with a solid grasp of the basics, will make you proficient in managing complex configurations with ease.

Next Article: Terraform: How to concatenate lists

Previous Article: Terraform: 3 Ways to Remove Duplicates from a List

Series: Terraform Tutorials

DevOps

You May Also Like

  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide
  • Terraform: 3 Ways to Remove Duplicates from a List
  • Terraform: How to convert a number to a string and vice versa
  • Using bcrypt() and md5() functions in Terraform
  • Terraform: Read CSV data and convert it into a list of maps