Terraform conditional expression and functions - Day 4

·

1 min read

Conditional expression

In Terraform, conditional expressions are used to define logic that determines whether a particular resource or block of code should be included or excluded based on certain conditions. These expressions are useful for making your infrastructure code more dynamic and flexible.

Syntax: condition ? true_val : false_val

If the condition is true, then the result is true_val. If the condition is false, then the result is false_val.

In the configuration file below, the concept of conditional expression is applied. The tag name depends on the instance type. If the instance type is 't2.micro', the tag will be 'Dev_Instance', otherwise, if the instance type is different from 't2.micro', the tag will be 'Stage_Instance'.

resource "aws_instance" "dev" {
  ami           = var.ami_value
  instance_type = var.instance_type_value
  key_name      = var.key_name_value

  tags = {
    Name = var.instance_type_value == "t2.micro" ? "Dev_Instance" : "Stage_Instance"
  }
}

Built-In Functions

Terraform provides several built-in functions that are valuable for DevOps engineers when working with infrastructure as code. Here are some commonly used functions:

  • Collection Functions

  • String Functions

  • Date and Time Functions

  • Numeric Function

  • Type Conversion Function

  • Filesystem Functions

Reference: https://developer.hashicorp.com/terraform/language/functions