How to write conditional logic in Terraform

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Terraform, by HashiCorp, is a tool that allows for the definition, preview, and deployment of infrastructure as code. The tool utilizes a declarative configuration language known as HCL (HashiCorp Configuration Language) to describe the desired state of your infrastructure. This enables version control of your infrastructure in the same way as you might with application code. An essential aspect of writing Terraform configurations is implementing conditional logic. Conditional logic allows for dynamic configurations that can adapt based on variables or the current state of the provisioned infrastructure.

Understanding the Basics

Before diving into conditional logic, it’s important to grasp a few fundamentals of Terraform syntax, particularly regarding variables and the
count parameter, which will play a significant role in our conditional structures.

variable "deploy_instance" {
  description = "Whether or not to deploy an instance"
  type        = bool
  default     = true
}

resource "aws_instance" "example" {
  count         = var.deploy_instance ? 1 : 0
  ami           = "ami-1234567"
  instance_type = "t2.micro"
}

In this basic example, we create a variable, deploy_instance, that controls whether an AWS EC2 instance is deployed. The count argument is used to conditionally create the instance based on the variable’s boolean value.

Implementing Conditional Expressions

Conditional expressions in Terraform use a simple condition ? true_val : false_val syntax, which mirrors many programming languages. These expressions can dynamically set the values for arguments within your Terraform configuration based on any logic you define.

resource "aws_security_group" "example" {
  name        = "sg-example"
  description = "An example security group"

  ingress = var.create_security_group ? [
    {
      from_port   = 22
      to_port     = 22
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  ] : []
}

This example demonstrates how to use conditional expressions to manage the creation of a security group’s ingress rules based on a boolean variable.

Using Conditional Logic with Collections

Terraform’s advanced features include the ability to work with complex data types such as lists and maps. Conditional logic can extend to these types, enabling more nuanced configurations.

locals {
  environment_settings = {
    prod = {
      instance_size = "m4.large"
      min_instances = 3
    }
    dev = {
      instance_size = "t2.small"
      min_instances = 1
    }
  }
}

resource "aws_autoscaling_group" "example" {
  min_size = lookup(local.environment_settings[var.environment].min_instances, var.environment, 1)
  max_size = 5
}

In this more complex scenario, we use a map of maps stored in local to define settings for different environments. The look-up function determines the minimum instance size based on the deployed environment.

Advanced Conditional Logic

More complex conditional logic might involve using expressions within expressions or applying conditions based on the output of other resources. Creating modular and dynamic configurations greatly increases the power and flexibility of your Terraform code.

module "server" {
  source = "./modules/server"
  count  = terraform.workspace == "prod" ? var.num_servers_prod : var.num_servers_dev

  settings = {
    instance_type = terraform.workspace == "prod" ? "m4.large" : "t2.small",
  }
}

This example illustrates how to use the terraform.workspace as a condition to dynamically configure a module, including the number of instances to deploy based on the current workspace.

Error Handling and Conditional Logic

It’s important to remember that while conditional logic can greatly enhance the flexibility of your Terraform configurations, it can also introduce complexity that could lead to errors. Clear documentation, thorough testing, and understanding the limitations of HCL’s conditional logic are paramount.

Conclusion

Conditional logic in Terraform allows for dynamic and flexible infrastructure configurations. By understanding and implementing basic to advanced conditional expressions, Terraform configurations can adapt to various scenarios, providing a robust infrastructure as code solution. Always test and document your configurations to ensure their reliability and maintainability.