How to use Terraform Variables

Tech Lead & Architect | 13+ Years in Cloud, Backend, and AI - Experienced software engineer with expertise in Java, Spring Boot, Microservices, Angular, React, Kafka, DevOps, Python, PySpark, Databricks, and Generative AI. Certified in TOGAF, AWS, and Google Cloud. Passionate about building scalable, secure, and high-performance systems. Enthusiast in Data Engineering & Agentic AI. Author of 1,200+ technical articles sharing insights across diverse tech stacks.
Date: 2022-02-07
Terraform: Managing Infrastructure with Variables
Terraform is a powerful, open-source tool developed by HashiCorp that simplifies the process of building, modifying, and versioning infrastructure. It allows for the efficient and safe management of infrastructure across various cloud service providers and even custom internal solutions. Whether dealing with low-level components like compute, storage, and networking, or higher-level elements such as SaaS integrations and DNS management, Terraform streamlines the entire process. At its core, Terraform utilizes a declarative configuration language, meaning you define the desired state of your infrastructure, and Terraform figures out how to achieve it.
The Terraform configuration language is designed specifically for infrastructure automation. It centers around the concept of resources – individual components of your infrastructure – and modules, which group resources together to represent larger, more complex units of configuration. The language itself is composed of blocks, arguments, and expressions, which work together to describe your infrastructure in a structured and readable way. Deployment using Terraform involves a sequence of commands, though the specifics can vary depending on the workflow and the complexity of the infrastructure being managed.
Variables play a crucial role in making Terraform configurations more dynamic and reusable. Instead of hardcoding values directly into the configuration files, variables allow you to parameterize your infrastructure. This is particularly useful when you need to deploy the same infrastructure in multiple environments (e.g., development, testing, production) with slightly different configurations. Terraform supports two main types of variables: input and output variables.
Input variables provide a way to specify values at runtime. This allows for flexibility and avoids the need to modify the main Terraform configuration file each time you want to change a setting. Best practice dictates that these input variables are defined in a separate file, commonly named variables.tf, to enhance readability and maintain organization. Within this file, each variable is declared within a variable block, which includes a unique label name. Optional arguments within the variable block can further define things such as default values, descriptions, and data types. These variables are then accessed within the main Terraform configuration using the syntax var.variable_name. Imagine, for instance, a variable defining the instance type for an Amazon EC2 instance. Instead of hardcoding t2.micro, you define a variable instance_type, and then set its value when running Terraform. This makes it simple to change the instance type without altering the core configuration.
Output variables, on the other hand, allow you to expose information from your Terraform configuration. This is beneficial for sharing important data with other resources or users. A common use case is to display the public IP address or the ID of an EC2 instance after it has been created. Output variables are defined within an output block, similar to input variables. Each variable requires a unique label name and specifies the value to be returned. This might involve referencing attributes of resources created during the deployment process. For example, you might define an output variable to return the public IP address of a newly created EC2 instance, making it readily accessible for use in other scripts or tools.
Consider a simple scenario involving the creation of an Amazon EC2 instance. The variables.tf file might contain definitions for the instance type, AMI ID, key name, and security group ID. The main Terraform configuration (ec2.tf, for example) would then use these variables to define the EC2 resource. This ensures that only the variables.tf file needs adjustments when you want to create an instance with different specifications. A separate outputs.tf file would define variables to return the instance ID, public IP address, and other relevant information after deployment.
Before deploying any Terraform configuration, a provider file is typically needed to specify the cloud provider (e.g., AWS, Azure, Google Cloud). This file defines the connection details for your cloud environment and allows Terraform to interact with the provider's APIs. Once the configuration files (including the provider file, variables.tf, ec2.tf, and outputs.tf) are prepared, deployment involves executing a series of Terraform commands. These commands typically include terraform init (to initialize the working directory and download necessary plugins), terraform plan (to create an execution plan showing the changes that will be made), and terraform apply (to actually create or update the infrastructure). After the deployment, you can verify the changes by examining the cloud provider’s console.
The use of variables significantly enhances the maintainability, reusability, and overall efficiency of Terraform configurations. It promotes modularity and facilitates collaboration, allowing developers to manage complex infrastructure with greater ease and control. By separating concerns and promoting a more structured approach, variables transform Terraform from a tool for managing individual infrastructure components into a platform for managing entire environments and applications across various deployment stages. This allows for better version control, easier testing, and a more robust overall infrastructure management system. The benefits extend beyond simply managing individual components; it streamlines the entire process of infrastructure deployment and management, enabling faster iteration cycles and enhanced collaboration amongst teams.