Sling Academy
Home/DevOps/Terraform: How to manipulate variables

Terraform: How to manipulate variables

Last updated: February 04, 2024

Introduction

Terraform, an open-source infrastructure as code software tool created by HashiCorp, allows users to define and provision data center infrastructure using a high-level configuration language known as HashiCorp Configuration Language (HCL). One of Terraform’s core concepts is the use of variables. Variables in Terraform allow you to write configurations that are flexible and reusable without altering the core logic.

In this comprehensive tutorial, we’re diving deep into the world of Terraform variables. From understanding simple variable declarations to mastering complex data structures and operations, you’re about to embark on a journey that will significantly enhance your Terraform proficiency.

Basic Variable Declarations

To start, let’s understand how to declare variables in Terraform. A variable declaration is quite straightforward. Here’s a basic example:

variable "my_variable" {
  type        = string
  description = "A simple variable example."
}

After declaring the variable, you can reference it within your Terraform configuration like so:

resource "aws_instance" "example" {
  ami           = var.my_variable
  instance_type = "t2.micro"
}

Assigning Values to Variables

Variables can be assigned values in several ways, including through Terraform CLI arguments, in a terraform.tfvars file, or directly within the variable declaration. Here’s an example of assigning a value directly:

variable "my_variable" {
  type        = string
  default     = "ami-12345678"
}

Advanced Types and Structures

As you become more comfortable with basic variable declarations and assignments, it’s time to explore more complex types and structures. Terraform supports a variety of types, including:

  • string
  • number
  • bool
  • list()
  • map()
  • object({})

These types can be used to handle more complex configurations. For example, here’s how you can declare a list of strings:

variable "regions" {
  type    = list(string)
  default = ["us-west-1", "us-east-1"]
}

Working with maps is especially useful for creating a more dynamic and configurable infrastructure:

variable "instance_sizes" {
  type    = map(number)
  default = {
    small  = 1
    medium = 2
    large  = 3
  }
}

Manipulating Variables with Functions

One of Terraform’s powerful features is its support for built-in functions. These functions can be used to manipulate variables in various ways. For example, the lookup function allows you to extract values from a map based on a key:

resource "aws_instance" "example" {
  ami = lookup(var.instance_sizes, var.size, "small")
}

This example selects the instance size based on a variable called size. If the size is not found, it defaults to “small”.

Conditional Expressions

Another powerful tool in your Terraform toolkit is the use of conditional expressions. These allow you to dynamically alter your configuration based on the values of variables. Here’s a simple example:

variable "environment" {
  type    = string
  default = "development"
}

resource "aws_instance" "example" {
  count = var.environment == "production" ? 2 : 1
}

In this case, the number of AWS instances created depends on whether the environment is set to production or not.

Conclusion

Mastering variables in Terraform is key to writing efficient, reusable, and flexible infrastructure code. By understanding how to declare, assign, and manipulate variables, especially with the help of complex data structures and built-in functions, you can significantly enhance your Terraform projects. Remember, practice makes perfect, so dive into these examples and experiment with them in your own configurations.

Next Article: How to use local variables to simplify your Terraform code

Previous Article: Terraform: Store and retrieve secrets the right way (4 approaches)

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • 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 Merge 2 Maps
  • 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