Get familiar with useful Terraform functions
Terraform functions are built-in solutions that help you manipulate and transform data. They can make your infrastructure as code more resilient, manageable, and flexible. Here are some practical Terraform functions for everyday use:
1/ format(string, values...): This function allows you to format a string with a specific pattern by interpolating values. Great for naming resources with consistent patterns.
resource_name = format("project-%s-%s", var.project_name, var.environment)
2/ merge(map1, map2, ...): Merge two or more maps into a single one, useful for combining configuration settings from different sources.
locals {
default_settings = {
environment = "dev"
region = "us-west-1"
}
custom_settings = {
region = "us-west-2"
}
}
all_settings = merge(local.default_settings, local.custom_settings)
3/ lookup(map, key, default): Find a value from a given map by key, and if the key is not present, return a default value. Great for creating fallbacks
ami_id = lookup(var.ami_id_map, var.region, "ami-0c94b3cbb99edte5g")
4/ element(list, index): Retrieve an element from a list by index. Handy when working with dynamic data, like IP ranges, subnet IDs, etc.
subnet_id = element(aws_subnet.example.*.id, count.index)
5. coalesce(values...): Return the first non-null value from a list of values. Useful for creating fallbacks.
instance_type = coalesce(var.instance_type, local.default_instance_type, "t2.micro")
Explore the official Terraform documentation to discover more functions to improve your infrastructure as code: Terraform Functions
Stay tuned for more DevOps Tips & Tricks!