in this section

How to Use Terraform Variables: Best Practices

Yuval Margules

Yuval Margules

Backend Developer, ControlMonkey

7 min read
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, however the underlying architecture remains the same. Without Terraform variables, you would create copies of the same configurations with minor changes in values. Therefor, 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. You can create a variable to set an AWS region, instance type, or S3 bucket name. You can then use this variable throughout your Terraform scripts.

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 Terraform 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. To keep it simple, let’s say this application runs on an EC2 instance and needs 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. Therefor, 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. Likewise, 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 setup: this snippet defines inputs for region, VPC CIDR, instance type, and AMI ID. This helps make deployments reusable and not tied to any specific environment.

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

In this paragraph we will show variables and locals in our script.

First Step: Define your variables

 Step 2: Local values and tags

Step 3: Configure the provider and networking resources

Create a security group

Step 5: Launch EC2 instance(s)

✅ Last Step: Create an S3 bucket and IAM policy

 

Notice how we used the common_tags and name_prefix locals in all our resources. We declared them 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 Terraform Variables

We can apply this script by substituting values;

Terminal command showing a multi-line terraform apply with inline 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 .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 ”

Furthermore, 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 Terraform 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

Visual summary of common Terraform variable pitfalls: overusing variables, not using locals for intermediate calculations, and failing to mark sensitive data appropriately. Includes example of using 'locals' block to combine variables into a name prefix

1️⃣ Overusing Terraform variables:

despite this article, not everything needs to be a variable.

2️⃣ Use local values for intermediate calculations:

When you can instead of using variables within resources:

3️⃣Neglecting sensitive data:

Lastly it is important to 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 keep deployments consistent in different environments. You can find configuration drift early. Working with best practices will help you avoid common mistakes. This will help you create secure Infrastructure as Code (IaC) configurations. One more thing you should look into is to detect configuration drift early. These can grow with your organization’s needs.

With ControlMonkey, you can automate managing Terraform variables. It helps you follow best practices and makes deployments easier for different environments. Enjoy AI-driven efficiency and multi-cloud compliance. Request a demo or learn more in our resource library.

gif

FAQ on Terraform Variables

After you declare the variables in your terraform configuration, you can set environment variables. Use the prefix TF_VAR to assign values to 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 show up after you run a terraform apply command. This happens 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

AWS and Atlantis logos around a grid
Visual showcasing Terraform file being automated into AWS
DevOps icons next to the official FedRamp logo
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