in this section

How to Use Terraform Variables: Best Practices

Yuval Margules

Yuval Margules

Backend Developer, ControlMonkey

Visual showcasing Terraform Variables

in this section

Imagine you are using your favorite IaC tool – Terraform, to deploy infrastructure for three environments: development, staging, and production. Each environment needs its own configurations, resource names, tags, and other customizations, but the underlying architecture remains the same. Without Terraform variables, you would create copies of the same configurations with minor changes in values. Terraform variables allow you to parameterize your code to be flexible, maintainable, and reusable. Mastering the use of variables is essential for creating configurations that are both reusable and flexible to changing requirements.

What Are Terraform Variables?

Terraform variables act as placeholders that allow you to parameterize your infrastructure configuration without modifying the underlying code. Similar to variables in programming languages, you declare them with names and assign values that Terraform interpolates during execution. For example, you can define a variable to specify an AWS region, instance type, or an S3 bucket name, which you can then reference throughout the Terraform scripts consistently.

Similar to most programming languages, Terraform variables have various types.

  • Strings: Text values
  • Numbers: Numeric values
  • Booleans: true/false values
  • Lists: Ordered collections of values
  • Maps: Collections of key-value pairs
  • Objects: Complex structured data
  • Sets: Unordered collections of unique values

Here is how you define a variable in Terraform:

You can then reference the variable across your code:

Using Variables in AWS Deployments

Managing Terraform variables effectively is essential in cloud environments such as AWS, where infrastructure spans multiple services and environments. Variables allow you to maintain consistency and standardize your complex AWS environments. For example, almost all AWS resources support tagging. You can enforce mandatory tags for all resources and use variables to configure the tag values.

Identifying variables

A good starting point is identifying the environment-specific (Infrastructure-related) data and naming conventions suitable for your deployments. Let’s take a scenario where you deploy an application for different customers on AWS. Each customer requires dedicated infrastructure. Some customers require several environments and have requirements on which region they need their application deployed.

We can recognize the following variables change based on the customer and environment:

  • Customer Name
  • Region
  • Environment Name

Environment name and Customer Name are not AWS-related concepts. So we can categorize them for naming conventions.

The region is environment-specific and AWS related. Apart from the region, what else can we parameterize? Well, that depends on what AWS resources you deploy. For simplicity, let’s consider that this application runs on an EC2 instance and requires access to an S3 bucket. So, at a minimum, we should create a VPC, an EC2, an S3 bucket, and an IAM Policy.

We will use customer name as a prefix and environment as a suffix for resource names. This helps us create distinct and easily identifiable resources and ensures resource names are not repeated across deployments. Also note that resources such as S3 buckets and IAM Policies are global and cannot have the same name across regions.

We would need to create different VPCs without CIDR overlap, and we will also need to change the instance type for each customer. So, we will create some AWS-related variables that are also customer—and environment-specific.

 

Terraform variable declarations for configuring AWS region, VPC CIDR block, EC2 instance type, and AMI ID, including default values for region (us-east-1) and instance type (t2.micro).
Terraform variables for AWS infrastructure provisioning: this snippet defines inputs for region, VPC CIDR, instance type, and AMI ID to parameterize deployments in a reusable and environment-agnostic way.

Note that you can maintain all your variables in a separate file, typically named variables.tf

Identifying Locals

Terraform locals are a type of variable that you declare for internal calculations and derived values. You cannot provide them externally. If you want to construct a new variable based on some values, you should use locals.

Let’s use locals to satisfy the following requirements;

  • We use tags in many of our resources. Locals can be used to create a single local variable that holds all our tags
  • We will prefix all our resource names with “-”.
  • We want to create two EC2 instances if the environment is prod

Creating reusable scripts

Let’s use these variables and locals in our script.

Step 1: Define your variables

 Step 2: Set local values and tags

Step 3: Configure the provider and networking resources

Step 4: Create a security group

Step 5: Launch EC2 instance(s)

✅ Step 6: Create an S3 bucket and IAM policy

 

Notice how we have used the common_tags and name_prefix locals across all our resources and variables we have declared as values for arguments in our resources. We also used the count meta-argument to conditionally set the number of EC2 instances based on our environment.

Declaring Outputs

Outputs are another kind of variable. You can use outputs to print the actual infrastructure information provisioned by your configurations.

 

Declaring Outputs Provisioning with Variables

We can apply this script by substituting values;

Terminal command showing a multi-line terraform apply with inline variable definitions for customer name, AWS region, environment, VPC CIDR block, and AMI ID.

 

Our script is now reusable and flexible, but there is still a problem. Depending on our deployment, we want to vary the values we use for each variable. We should also version-control which values we use for each deployment.

Terraform has a neat way to handle this requirement — learn how to automate your deployments. You can create a .tfvars file that sets these variables and overrides defaults. You can maintain this file in your version control.

Folder structure of a Terraform project showing separate .tfvars files for each customer and environment (e.g., customerA-dev.tfvars, customerB-prod.tfvars) alongside main.tf and variables.tf at the root level.

Here is our .tfvars file. Let’s call it customerA-dev.tfvars.

Let’s apply it with the command;

terraform apply -var-file=” ./tfvars/customerA-dev.tfvars ”

Let’s say we have another customer – CustomerB, and we should deploy their “prod” environment. Our “ customerB-prod.tfvars ” file would be

Notice we did not provide instance_type for customerA. That is because we have set a default value for that variable.

4 Best Practices for Using Variables

1) Group related variables: 

Organize variables by function or resource type.

2) Always include descriptions

Document what each variable is for:

3) Set sensible defaults: 

Provide reasonable default values when appropriate:

4) Validate inputs: 

Use validation rules to prevent errors:

5)Use variable files for environment-specific values: 

Create separate .tfvars  files for dev, staging, and production.

Common Terraform Variables Pitfalls to Avoid

1️⃣ Overusing variables:

Not everything needs to be a variable.

2️⃣ Use local values for intermediate calculations:

instead of using variables within resources:

3️⃣Neglecting sensitive data:

Mark sensitive variables accordingly.

Terraform Variables Conclusion

The power of Terraform variables is in transforming your static infrastructure code into dynamic and reusable configurations. By using variables, you can maintain consistent deployments across multiple environments — and detect configuration drift early. Following best practices and being aware of common mistakes can help you develop secure IaC configurations that can grow alongside your organizational needs.

With ControlMonkey, you can automate Terraform variable management, enforce best practices, and streamline environment-specific deployments with AI-driven efficiency and multi-cloud compliance — request a demo or learn more in our resource library.

gif

FAQ on Terraform Variables

Once you have declared the variables of your terraform configuration, you can define environment variables with the prefix `TF_VAR` to set values for those variables.

Prefix with TF_VAR_ for automatic mapping:

export TF_VAR_bucket_name=my-terraform-bucket

Terraform CLI also supports environment variables to modify its default behaviour.

You can set environment variables for Terraform in Windows using the Command Prompt or PowerShell. The syntax varies between the command-line interpreter you use:

 

Command Prompt:

set TF_VAR_region=us-west-2

PowerShell:

$env:TF_VAR_region = “us-west-2”

 

You can access output variables using the `terraform output` command after applying your configuration. Output variables will always be printed after a terraform apply command even if there are no changes to your infrastructure.

Terraform variables are declared in .tf files using the` variable` block.

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

Once you have declared the variables, you can pass values (or override) using;

  • terraform.tfvars files
  • Command-line flags: -var=”region=us-east-1″
  • Environment variables (see below)

About the writer
Yuval Margules
Yuval Margules

Backend Developer, ControlMonkey

Yuval is a software engineer at ControlMonkey with a strong focus on DevOps and cloud infrastructure. He specializes in Infrastructure as Code, CI/CD pipelines, and drift detection. Drawing from real-world conversations with engineering teams, Yuval writes about practical ways to automate, scale, and secure cloud environments with clarity and control.

Related Resources

Magnifying glass over broken terraform like debugging
AWS-networking-with-Terraform-webinar-preview
End to End IaC Automation Platform_02
Compliant AWS environments in minutes, with Self-service Infrastructure
Learn how to enable other teams such as Dev and QA to launch pre-defined compliant AWS environments in minutes, by using Terraform.

Contact us

We look forward to hearing from you

ControlMonkey
AWS Governance & DevOps Productivity with Terraform

Learn how how to shift-left cloud governance with Terraform in this webinar brought to you by AWS and ControlMonkey.

We look forward to hearing from you!

ControlMonkey

Terraform Best Practices with ControlMonkey Webinar

Check out our latest webinar with DoIT International.

In this webinar we showcase together with DoIT how ControlMonkey is helping DevOps teams to make the transition from ClickOps to GitOps easily with Terraform.

This website uses cookies. We use cookies to ensure that we give you the best experience on our website. Privacy policy