Open In App

Terraform Variables

Last Updated : 24 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Terraform variables give developers the idea of creating templates that are reusable throughout different environments with minimal duplication of code and greater flexibility of the code. Rather, if you manage infrastructure through variables rather than hardcoding specific values into your scripts, the usage of variables allows you to simplify the management of your infrastructure.

As with other languages, variables in the terraform have specific uses in the master plan. The best practices for using them and their types will be covered in this guide, along with recommendations that will assist in writing scalable and well-maintained infrastructure code.

Use of Variables in Terraform

Instead of hardcoding specific details like instance types or region names, Terraform variables act as placeholders that store dynamic values. This makes your code reusable and flexible. For instance, you can use the same configuration file for different environments by simply changing variable values instead of rewriting the whole script.

Types of Terraform Variables

There are several variable types in Terraform that you can use depending on your specific needs. Below are some of the most important ones:

  • String Variables: These can be used to store textual values. For example, user names or AMI IDs
  • Number Variables: These are used to store numeric values. For example, the number of instances or their size.
  • Boolean Variables: These define a true or false value. They are useful for feature flags or turning on and off something.
  • List Variables: These maintain an ordered collection of items, such as IP addresses or instance IDs.
  • Map Variables: These store key-value pairs, making them ideal for storing settings or configurations.
  • Object Variables: These represent structured data with multiple attributes, suitable for complex configurations.
  • Tuple Variables: These contain ordered collections of values of different types, making them useful for diverse configurations.

Declaring Terraform Variables

To start using variables in Terraform, you first need to declare them in your configuration file. Here’s an example of how to declare a string variable:

variable "instance_type" {
type = string
default = "t2.micro"
}

In this case, the variable instance_type is declared with a default value of t2.micro. The type of the variable is defined as string.

Assigning Values to Variables

There are several ways to assign values to variables in Terraform:

  • Default Values: When declaring a variable, you can set a default value. This will be used if no other value is provided.
  • Input Variables: You can override the default value by passing a value when running Terraform commands using the -var flag or by specifying values in .tfvars files.

Example of passing a value via the -var flag:

terraform apply -var="instance_type=t2.large"

This overrides the default value for instance_type and sets it to t2.large.

Using Variables in Terraform Resources

Once a variable is declared and assigned a value, you can use it throughout your Terraform configurations. Here’s an example of how to use a variable in a resource block:

resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
}

In this case, the instance_type for the aws_instance resource is dynamically set using the value of the instance_type variable.

Validating Variables

Terraform allows you to validate variables before they are used, ensuring they meet certain conditions. You can add validation rules to your variables to enforce rules like acceptable value ranges or formats.

Example:

variable "instance_type" {
type = string
default = "t2.micro"
validation {
condition = contains(["t2.micro", "t2.small", "t2.medium"], var.instance_type)
error_message = "Instance type must be one of t2.micro, t2.small, or t2.medium."
}
}

This validation ensures that only allowed instance types can be used.

Using .tfvars Files

For better organization, especially in multi-environment setups, you can define variables in .tfvars files instead of hardcoding them into the configuration. This makes it easier to manage values for different environments (e.g., development, production).

Example .tfvars file (terraform.tfvars)

instance_type = "t2.medium"
ami_id = "ami-0c55b159cbfafe1f0"

You can then specify this file when running Terraform commands:

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

Best Practices for using Terraform Variables

To ensure your Terraform configurations are maintainable and scalable, here are some best practices for using variables:

  • Use descriptive names: Use meaningful names for variables (e.g., instance_type, ami_id, region) to make your code easier to understand.
  • Define default values wisely: While defaults are good to have but don't overuse them. Always explicitly define critical variables like region or instance type in the environment.
  • Avoid hardcoding values: Don't put the value of resource blocks directly, use variables which can be reused and help you to make environment flexible.
  • Leverage .tfvars files: Use .tfvars files for managing environment-specific configurations. This approach keeps your configurations clean and helps maintain consistency across environments.
  • Use locals: For computed or derived values which aren't required to be input by user and are used multiple times in configuration, use locals.

Conclusion

Terraform variables are a powerful feature that increases the flexibility, scalability, and maintainability of your infrastructure code. By using variables, you can make your code more adaptable, maintainable, and reusable across different environments. Whether you’re declaring variables, assigning values, or validating inputs, mastering the use of variables is an essential skill for managing infrastructure with Terraform.


Next Article
Article Tags :

Similar Reads