terraform
module
optional variables
map variables
infrastructure as code

Optional map variables in terraform module

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When creating infrastructure as code using Terraform, reusability and flexibility of modules are fundamental. Terraform modules with optional and default parameters allow you to customize configuration without duplicating code. One powerful feature is using optional map variables in a Terraform module, which can simplify input handling and improve module robustness.

Understanding Map Variables

In Terraform, a map is a collection of keys, each associated with a value. Maps are akin to dictionaries in languages like Python. They offer a convenient mechanism to manage configurations that can vary based on environment or instance type. Terraform's ability to handle map variables enables a more dynamic infrastructure setup.

Declaring Optional Map Variables

To declare optional map variables in a Terraform module, you must define the variable in the module's variables.tf file and provide default values. Here is a simple example:

hcl
1variable "tags" {
2  description = "A map of tags to apply to the resources."
3  type        = map(string)
4  default     = {
5    Environment = "Development"
6    Owner       = "DevOps"
7  }
8}

In the above declaration, tags is a map variable with default key-value pairs. If a user does not override this map, Terraform will apply the default tags.

Using Map Variables within Modules

Once you have defined a map variable, you can use it within your module's resources. For instance, when defining an AWS EC2 instance, you can apply tags from the map as follows:

hcl
1resource "aws_instance" "example" {
2  ami           = "ami-123456"
3  instance_type = "t2.micro"
4
5  tags = var.tags
6}

This approach applies the tags map to all instances created by the module, ensuring consistency and minimizing redundant specification of tags across different instances.

Conditional Logic with Maps

Map variables in Terraform also facilitate conditional logic. Suppose you want to apply different tags based on the environment. Here's how you could achieve this:

hcl
1variable "environment" {
2  description = "The environment of the deployment"
3  type        = string
4  default     = "development"
5}
6
7variable "tags" {
8  description = "A map of tags to apply to the resources."
9  type        = map(string)
10  default     = {
11    "development" = {
12      Environment = "Development"
13      Owner       = "DevOps"
14    }
15    "production" = {
16      Environment = "Production"
17      Owner       = "Operations"
18    }
19  }
20}
21
22locals {
23  selected_tags = lookup(var.tags, var.environment, var.tags["development"])
24}

In this scenario, the local block is used to select the appropriate tags based on the environment variable. If environment is specified as production, the production tags are applied. Otherwise, it defaults to the development tags.

Best Practices

  1. Default Values: Always provide sensible defaults for map variables to ensure modules function as expected if no user input is provided.
  2. Validation Rules: Implement validation within your map variable declaration to ensure integrity and correctness of input.
hcl
1   variable "tags" {
2     description = "A map of tags."
3     type        = map(string)
4     default     = {
5       Environment = "Development"
6     }
7     validation {
8       condition     = alltrue([for k, v in var.tags : contains(["Environment", "Owner"], k)])
9       error_message = "Tags must include 'Environment' and 'Owner'."
10     }
11   }
  1. Documentation: Thoroughly document the purpose and structure of your map variables for module users.
  2. Refactoring: Use map variables to reduce complexity and length of input variable lists, especially when dealing with configurations that may change frequently.

Key Points Summary

AspectExplanation
DefinitionMap variables are key-value pairs, useful for dynamic configurations.
OptionalityDefaults can make map variables optional, providing fallback values when not specified by users.
Usage in ResourcesYou can pass map variables to resources to define attributes like tags or configurations.
Conditional LogicMaps facilitate advanced conditional logic for different deployment scenarios.
Best PracticesInclude defaults, validation, and proper documentation to improve module robustness.

Conclusion

Optional map variables in Terraform modules provide a streamlined approach to managing configurations, enhancing flexibility, and improving the clarity and maintainability of Terraform code. By leveraging these features, you can build more dynamic, adaptable infrastructure plans that align with diverse deployment environments and usage scenarios. Make sure to apply best practices for even greater efficiency and reliability in your Terraform projects.


Course illustration
Course illustration

All Rights Reserved.