MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform Variable Example: Azure & AWS

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.

TypeExample declarationHow it is referenced
numbertype = numbercount = var.instance_count
stringtype = stringname = var.grpname
booltype = boolcount = var.create_vm ? 1 : 0
listtype = list(string)var.users[0] (index starts at 0)
maptype = 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: the terraform block with required_providers, plus the provider block.
  • variables.tf: every variable block, each with a description.
  • main.tf: resources and data sources.
  • outputs.tf: output blocks.
  • 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 validation block 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.index to the Name tag gives each instance a unique name, instead of several identical tags.
  • aws_instance.example[*].id is 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:

  1. The default in the variable block
  2. TF_VAR_<name> environment variables
  3. terraform.tfvars
  4. terraform.tfvars.json
  5. *.auto.tfvars and *.auto.tfvars.json, in lexical filename order
  6. -var and -var-file options, 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

ErrorCauseFix
Unsupported attribute on an outputReferring to a variable through a resource, e.g. azurerm_resource_group.mapdemo1.grpsUse a real resource attribute (.name, .id) or var.grps["one"] directly
InvalidGroup.NotFound or Invalid id for security groupsGroup names passed to vpc_security_group_idsPass sg- IDs, or look them up with the aws_security_group data source
InvalidAMIID.NotFoundAMI ID deregistered or from a different regionUse 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 suppliedAdd a default, a tfvars entry, -var, or TF_VAR_create_vm
Invalid index on var.users[2]List has fewer elements than expectedUse for_each/count with length(), or validate the list length
subscription_id is a required provider propertyazurerm 4.x without a subscription IDSet subscription_id in the provider or export ARM_SUBSCRIPTION_ID

Best practices for variables

  • Give every variable a description and an explicit type, such as list(string) or map(string).
  • Use validation blocks 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 .tfvars files. 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 fmt and terraform validate automatically. 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals

Related Posts

Terraform Tutorial with Google Cloud – Create Single VM & Network

This tutorial uses Terraform to create a Google Compute Engine VM on Google Cloud, either in a new auto-mode VPC network or in the project's default network….

Read More

Terraform Tutorial with Google Cloud – Create Single VM

This tutorial shows how to create a single Google Compute Engine VM with Terraform, using the google_compute_instance resource above as the starting point. The snippet above only…

Read More

Terraform dynamaic block details explaination with example

A Terraform dynamic block generates repeated nested blocks inside a resource, data source, provider or provisioner, such as ingress rules in a security group or rule blocks…

Read More

Terraform Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x