Terraform Variables: How to Use Them in Your Configuration Files

Are you tired of hardcoding values in your Terraform configuration files? Do you want to make your infrastructure more flexible and reusable? Then you need to learn about Terraform variables!

Variables are a powerful feature of Terraform that allow you to parameterize your configuration files. With variables, you can define values that can be reused across multiple resources, modules, and environments. You can also pass variables from the command line or from other sources, such as environment variables or files.

In this article, we'll explore the basics of Terraform variables and show you how to use them in your configuration files. We'll cover the following topics:

So, let's get started!

Defining variables

To define a variable in Terraform, you use the variable block. The variable block has two required arguments: the name of the variable and its type. For example, here's how you define a variable named region of type string:

variable "region" {
  type = string
}

You can also provide an optional default value for the variable, like this:

variable "region" {
  type    = string
  default = "us-west-2"
}

With this definition, the region variable will default to "us-west-2" if no value is provided.

You can define variables in a separate file, like variables.tf, or inline in your configuration file. If you define variables in a separate file, make sure to include it in your Terraform module using the terraform block:

terraform {
  required_version = ">= 0.12"
  source = "./modules/my-module"
}

# Load variables from a separate file
variable "region" {
  type    = string
  default = "us-west-2"
}

Using variables in resource blocks

Once you've defined a variable, you can use it in your resource blocks by enclosing the variable name in ${}. For example, here's how you can use the region variable in an AWS S3 bucket resource:

resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket-${var.region}"
  acl    = "private"
}

In this example, the bucket name will be "my-bucket-us-west-2" if the region variable is set to "us-west-2". Note that you can use variables in any string attribute of a resource block.

You can also use variables in other types of attributes, such as lists, maps, and objects. For example, here's how you can use the region variable in an AWS EC2 instance resource:

resource "aws_instance" "my_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "my-instance"
    Region = var.region
  }
}

In this example, the tags attribute is a map that includes the Name and Region keys. The Region value is set to the region variable.

Using variables in module blocks

You can also use variables in module blocks to pass values to child modules. To use a variable in a module block, you need to specify its value using the variables argument. For example, here's how you can use the region variable in a child module:

module "my_module" {
  source = "./modules/my-module"

  # Pass the region variable to the child module
  variables = {
    region = var.region
  }
}

In this example, the variables argument is a map that includes the region key. The value of the region key is set to the region variable.

You can also use variables in the source argument of a module block to dynamically load modules based on the value of a variable. For example, here's how you can load a module based on the value of the environment variable:

module "my_module" {
  source = "./modules/${var.environment}-module"
}

In this example, the source argument includes the ${} syntax to interpolate the value of the environment variable.

Using variables in locals blocks

Locals are a way to define values that are computed from other values in your configuration files. You can use variables in locals blocks to make them more dynamic and reusable. To use a variable in a locals block, you need to reference it using the var prefix. For example, here's how you can define a local variable that depends on the region variable:

locals {
  bucket_name = "my-bucket-${var.region}"
}

In this example, the bucket_name local variable is defined as "my-bucket-${var.region}". You can use this local variable in other parts of your configuration files, like resource blocks or outputs.

Using variables in data blocks

Data blocks are a way to retrieve information from external sources, such as APIs or databases. You can use variables in data blocks to make them more flexible and reusable. To use a variable in a data block, you need to reference it using the var prefix. For example, here's how you can retrieve an AWS AMI based on the region variable:

data "aws_ami" "my_ami" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }

  filter {
    name   = "root-device-type"
    values = ["ebs"]
  }

  filter {
    name   = "region"
    values = [var.region]
  }
}

In this example, the filter block includes a filter on the region attribute that uses the var.region variable.

Using variables in outputs

Outputs are a way to export values from your Terraform module. You can use variables in outputs to make them more dynamic and reusable. To use a variable in an output block, you need to reference it using the var prefix. For example, here's how you can export the region variable as an output:

output "region" {
  value = var.region
}

In this example, the value attribute is set to the var.region variable.

Passing variables from the command line

You can pass variables from the command line using the -var option. For example, here's how you can set the region variable to "us-east-1":

terraform apply -var="region=us-east-1"

You can also pass variables from a file using the -var-file option. For example, here's how you can set the region variable using a file named vars.tfvars:

terraform apply -var-file="vars.tfvars"

The vars.tfvars file should contain the variable values in a key-value format, like this:

region = "us-east-1"

Using environment variables and files

You can also use environment variables and files to set variable values. To use an environment variable, you need to reference it using the env prefix. For example, here's how you can set the region variable using an environment variable named TF_VAR_region:

export TF_VAR_region=us-east-1
terraform apply

To use a file to set variable values, you need to reference it using the file function. For example, here's how you can set the region variable using a file named region.txt:

variable "region" {
  type    = string
  default = file("region.txt")
}

In this example, the default attribute is set to the contents of the region.txt file.

Best practices for using variables

Here are some best practices for using variables in your Terraform configuration files:

By following these best practices, you can make your Terraform configuration files more flexible, reusable, and maintainable.

Conclusion

Terraform variables are a powerful feature that allow you to parameterize your configuration files and make your infrastructure more flexible and reusable. In this article, we've covered the basics of Terraform variables and shown you how to use them in your configuration files. We've also provided some best practices for using variables in your Terraform projects.

We hope this article has been helpful in your Terraform learning journey. If you have any questions or feedback, please let us know in the comments below. Happy Terraforming!

Editor Recommended Sites

AI and Tech News
Best Online AI Courses
Classic Writing Analysis
Tears of the Kingdom Roleplay
Developer Cheatsheets - Software Engineer Cheat sheet & Programming Cheatsheet: Developer Cheat sheets to learn any language, framework or cloud service
Deploy Code: Learn how to deploy code on the cloud using various services. The tradeoffs. AWS / GCP
Neo4j Guide: Neo4j Guides and tutorials from depoloyment to application python and java development
LLM training course: Find the best guides, tutorials and courses on LLM fine tuning for the cloud, on-prem
Last Edu: Find online education online. Free university and college courses on machine learning, AI, computer science