This page shows how to declare and use Terraform input variables of type number, string, bool, list and map with AWS and Azure resources. Below the original examples you will find corrected versions you can run, the ways to supply variable values and which one wins, and fixes for the errors people hit most often.
Terraform Variable AWS Example
variable "instance_count" {
type = number
default = 1
}
variable "region" {
type = string
default = "us-east-1"
}
variable "instance_name" {
type = string
default = "devopsschool-instance"
}
variable "security_groups" {
type = list(string)
default = ["default", "launch-wizard-1", "launch-wizard-2"]
}
variable "amis" {
type = map
default = {
"us-east-1" = "ami-007855ac798b5175e"
"us-west-2" = "ami-4b32be2b"
}
}
variable "create_vm" {
description = "If set to true, it will create vm"
type = bool
}
resource "aws_instance" "example" {
count = var.instance_count
ami = var.amis[var.region]
instance_type = "t2.micro"
vpc_security_group_ids = var.security_groups
tags = {
Name = var.instance_name
}
}
resource "aws_instance" "example1" {
count = var.create_vm ? 1 : 0
ami = var.amis[var.region]
instance_type = "t2.micro"
}Code language: PHP (php)
Terraform Variable Azure Example
variable "numofrg" {
type = number
description = "This is for demo of number variable"
default = 3
}
variable "grpname" {
type = string
description = "This is for demo of string variable"
default = "devopsschool-grp"
}
variable "users" {
type = list
default = ["devops-school-1", "devops-school-2", "devops-school-3"]
description = "This is for demo of list variable"
}
variable "grps" {
type = map
default = {
one = "hello1"
two = "hello2"
}
}
resource "azurerm_resource_group" "mapdemo1" {
name = var.grps["one"]
location = "South India"
}
output "resource_group" {
value = azurerm_resource_group.mapdemo1.grps["one"]
}
resource "azurerm_resource_group" "mapdemo2" {
name = var.grps["two"]
location = "South India"
}
resource "azurerm_resource_group" "listdemo" {
name = var.users[0]
location = "South India"
}
resource "azurerm_resource_group" "listdemo1" {
name = var.users[1]
location = "South India"
}
resource "azurerm_resource_group" "listdemo2" {
name = var.users[2]
location = "South India"
}
resource "azurerm_resource_group" "example1" {
name = var.grpname
location = "South India"
}
resource "azurerm_resource_group" "example" {
count = var.numofrg
name = "devopsschool-${count.index}"
location = "South India"
}
output "resource_group4" {
value = azurerm_resource_group.example1.name
}
Code language: PHP (php)
How Terraform input variables work
A variable block declares an input for a module. You read its value anywhere in the module with var.<name>. A default makes the variable optional. If a variable has no default and you don't supply a value, terraform plan asks for one interactively. This is why the create_vm variable in the example above triggers a prompt.
| Type | Example declaration | How it is referenced |
|---|---|---|
| number | type = number | count = var.instance_count |
| string | type = string | name = var.grpname |
| bool | type = bool | count = var.create_vm ? 1 : 0 |
| list | type = list(string) | var.users[0] (index starts at 0) |
| map | type = map(string) | var.grps["one"] or lookup(var.amis, var.region, "fallback") |
Note: The examples above use bare type = map and type = list. Terraform still accepts them and treats them as map(any) and list(any). Declaring the element type, as in map(string) and list(string), gives clearer errors and is the current recommended style.
Recommended file layout
Terraform loads every .tf file in the working directory, so a single file works. Splitting the configuration makes it easier to read and review:
versions.tf: theterraformblock withrequired_providers, plus theproviderblock.variables.tf: everyvariableblock, each with adescription.main.tf: resources and data sources.outputs.tf:outputblocks.terraform.tfvars: values for this environment. Terraform loads this file automatically.
Corrected AWS example
The AWS example above has no provider block, so var.region picks an AMI but never sets the region Terraform deploys to. It also passes security group names to vpc_security_group_ids, which only accepts IDs such as sg-0abc.... In addition, hard-coded AMI IDs go out of date and are specific to one region. The version below fixes all three problems. It still shows every variable type, and it uses lookup() to fall back to the latest Amazon Linux 2023 AMI when the map has no entry for the region.
terraform {
required_version = ">= 1.3"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">= 5.0"
}
}
}
provider "aws" {
region = var.region
}
variable "instance_count" {
description = "Number of instances to create"
type = number
default = 1
}
variable "region" {
description = "AWS region to deploy into"
type = string
default = "us-east-1"
validation {
condition = contains(["us-east-1", "us-west-2"], var.region)
error_message = "region must be us-east-1 or us-west-2."
}
}
variable "instance_name" {
description = "Prefix for the Name tag"
type = string
default = "devopsschool-instance"
}
variable "security_group_ids" {
description = "Security group IDs (sg-...). Empty list = VPC default group"
type = list(string)
default = []
}
variable "amis" {
description = "Optional per-region AMI overrides"
type = map(string)
default = {}
}
variable "create_vm" {
description = "If true, create the extra instance"
type = bool
default = false
}
data "aws_ami" "al2023" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["al2023-ami-2023.*-x86_64"]
}
}
locals {
ami_id = lookup(var.amis, var.region, data.aws_ami.al2023.id)
}
resource "aws_instance" "example" {
count = var.instance_count
ami = local.ami_id
instance_type = "t3.micro"
vpc_security_group_ids = var.security_group_ids
tags = {
Name = "${var.instance_name}-${count.index}"
}
}
resource "aws_instance" "example1" {
count = var.create_vm ? 1 : 0
ami = local.ami_id
instance_type = "t3.micro"
}
output "instance_ids" {
value = aws_instance.example[*].id
}Code language: PHP (php)
provider "aws" { region = var.region }means the region variable now controls where resources are created.- The
validationblock rejects unsupported regions at plan time, before any API call is made. lookup(map, key, default)returns the override when it exists and the data source AMI when it doesn't.- Adding
count.indexto the Name tag gives each instance a unique name, instead of several identical tags. aws_instance.example[*].idis a splat expression that returns a list with one ID per instance.
Note: t2.micro still works where it is available. This example uses t3.micro because newer accounts and regions support it more widely. Check the free tier terms for your account before you choose a size.
Corrected Azure example
The Azure example above has two blocking problems. First, the output azurerm_resource_group.mapdemo1.grps["one"] refers to an attribute the resource doesn't have, so terraform validate fails with an "Unsupported attribute" error. The value you want is azurerm_resource_group.mapdemo1.name. Second, there is no provider block. The azurerm provider needs features {}, and from provider version 4.0 it also needs a subscription ID, either in the block or in the ARM_SUBSCRIPTION_ID environment variable.
terraform {
required_version = ">= 1.3"
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = ">= 4.0"
}
}
}
provider "azurerm" {
features {}
subscription_id = var.subscription_id
}
variable "subscription_id" {
description = "Azure subscription ID"
type = string
}
variable "location" {
type = string
default = "South India"
}
variable "numofrg" {
type = number
default = 3
}
variable "grpname" {
type = string
default = "devopsschool-grp"
}
variable "users" {
type = list(string)
default = ["devops-school-1", "devops-school-2", "devops-school-3"]
}
variable "grps" {
type = map(string)
default = {
one = "hello1"
two = "hello2"
}
}
resource "azurerm_resource_group" "mapdemo1" {
name = var.grps["one"]
location = var.location
}
resource "azurerm_resource_group" "mapdemo2" {
name = var.grps["two"]
location = var.location
}
resource "azurerm_resource_group" "listdemo" {
for_each = toset(var.users)
name = each.value
location = var.location
}
resource "azurerm_resource_group" "example1" {
name = var.grpname
location = var.location
}
resource "azurerm_resource_group" "example" {
count = var.numofrg
name = "devopsschool-${count.index}"
location = var.location
}
output "resource_group" {
value = azurerm_resource_group.mapdemo1.name
}
output "resource_group4" {
value = azurerm_resource_group.example1.name
}Code language: PHP (php)
The three listdemo resources that indexed the list one by one are replaced by a single for_each over the list. That version still works when you add or remove users. Indexing with var.users[0] is fine for learning, but it fails with an "Invalid index" error when the list is shorter than the code expects. For more on count and for_each, see Terraform Loops and Iteration.
Supplying variable values and precedence
Defaults are only the fallback. You can override any variable without editing code:
# 1. terraform.tfvars (loaded automatically)
cat > terraform.tfvars <<'EOF'
region = "us-west-2"
instance_count = 2
create_vm = true
EOF
# 2. A named file, loaded only when passed explicitly
terraform plan -var-file=prod.tfvars
# 3. A single value on the command line
terraform plan -var="instance_count=3" -var='security_group_ids=["sg-0123456789abcdef0"]'
# 4. Environment variable (prefix TF_VAR_ + variable name)
export TF_VAR_subscription_id="00000000-0000-0000-0000-000000000000"Code language: PHP (php)
When the same variable is set in more than one place, the source loaded later wins. The order, from lowest to highest priority, is:
- The
defaultin the variable block TF_VAR_<name>environment variablesterraform.tfvarsterraform.tfvars.json*.auto.tfvarsand*.auto.tfvars.json, in lexical filename order-varand-var-fileoptions, in the order they appear on the command line
Running the examples
terraform init # downloads the provider
terraform fmt # normalises indentation (the originals mix tabs and spaces)
terraform validate # catches errors such as unsupported attributes
terraform plan -out=tfplan
terraform apply tfplan
terraform output
terraform destroy # remove the lab resources when finishedCode language: PHP (php)
With the default values, applying the corrected Azure example creates 8 resource groups. terraform output then prints:
resource_group = "hello1"
resource_group4 = "devopsschool-grp"Code language: JavaScript (javascript)
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
Unsupported attribute on an output | Referring to a variable through a resource, e.g. azurerm_resource_group.mapdemo1.grps | Use a real resource attribute (.name, .id) or var.grps["one"] directly |
InvalidGroup.NotFound or Invalid id for security groups | Group names passed to vpc_security_group_ids | Pass sg- IDs, or look them up with the aws_security_group data source |
InvalidAMIID.NotFound | AMI ID deregistered or from a different region | Use an aws_ami data source or update the map for the provider's region |
Plan stops and asks var.create_vm Enter a value: | Variable has no default and no value was supplied | Add a default, a tfvars entry, -var, or TF_VAR_create_vm |
Invalid index on var.users[2] | List has fewer elements than expected | Use for_each/count with length(), or validate the list length |
subscription_id is a required provider property | azurerm 4.x without a subscription ID | Set subscription_id in the provider or export ARM_SUBSCRIPTION_ID |
Best practices for variables
- Give every variable a
descriptionand an explicit type, such aslist(string)ormap(string). - Use
validationblocks to catch bad input at plan time. For related logic, see Terraform Conditional Expressions and Logic. - Mark secrets with
sensitive = true. Supply them through environment variables or a secrets manager instead of committing them in.tfvarsfiles. Sensitive values are still written in plain text to the state file, so protect the state as well. - Keep one tfvars file per environment (
dev.tfvars,prod.tfvars) and pass it with-var-file. - Run
terraform fmtandterraform validateautomatically. The pre-commit for Terraform guide shows how.
Frequently asked questions
What is the difference between a Terraform variable and a local value?
An input variable can be set from outside the module through tfvars files, -var or environment variables. A locals value is computed inside the module and can't be overridden. Use locals for derived values such as a chosen AMI ID or a name prefix.
Is terraform.tfvars loaded automatically?
Yes. Terraform automatically loads terraform.tfvars, terraform.tfvars.json and any *.auto.tfvars files in the working directory. Files with other names, such as prod.tfvars, are loaded only when you pass them with -var-file.
How do I pass a list or map variable on the command line?
Use HCL syntax inside single quotes so the shell doesn't interpret it, for example -var='users=["a","b"]' or -var='grps={one="x",two="y"}'. For anything longer, a tfvars file is easier to maintain.
Which value wins if a variable is set in several places?
-var and -var-file on the command line have the highest priority. Next come *.auto.tfvars, then terraform.tfvars.json, then terraform.tfvars, then TF_VAR_ environment variables. The default is used only when nothing else sets a value.
Should I use type = map or map(string)?
Use map(string) or another explicit element type. A bare map is accepted as map(any), but an explicit type documents your intent and gives clearer errors when someone passes the wrong value.
Related tutorials
- Terraform Loops and Iteration: Complete Guide to count, for_each, for Expressions, and Dynamic Blocks
- Terraform Conditional Expressions and Logic: Complete Guide with Examples
- How to Configure pre-commit for Terraform: Complete DevOps Guide with 15 Practical Use Cases, Commands, Security Checks, and Best Practices
- More Terraform tutorials
- More AWS tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals