Skip to content

Lesson 5 of 6

Use variables for reusable settings

Replace hard-coded values such as region and instance type with variables and a variable definitions file.

5 minInfrastructure

After this lesson, you will be able to replace hard-coded values in your Terraform configuration with variables, set their values in a separate file, and change a setting without editing the main code.

Why use variables

So far, your configuration has values written directly in the resource blocks, such as the region us-east-1 and the instance type t2.micro. If you want to deploy the same web server in another region or with a different instance type, you would have to edit the configuration files. Variables let you keep those values in one place and change them without touching the resource definitions.

Terraform variables are declared in a variables.tf file. Each variable has a name, an optional type, an optional default value, and a short description. You then reference a variable in your configuration with the var prefix, like var.region.

Declare variables

Create a new file named variables.tf in your web-server directory. In it, declare three variables: region, instance_type, and ami_id.

variable "region" {
  description = "AWS region where resources are created"
  type        = string
  default     = "us-east-1"
}

variable "instance_type" {
  description = "EC2 instance type for the web server"
  type        = string
  default     = "t2.micro"
}

variable "ami_id" {
  description = "AMI ID for the web server"
  type        = string
  default     = "ami-0c55b159cbfafe1f0"
}

The default value is used if you do not provide a value another way. That means your existing configuration will still work after you replace the hard-coded values with variable references.

Use variables in the configuration

Open your main.tf file, which contains the provider and resource blocks. Replace the region in the provider block with var.region. Replace the ami and instance_type in the aws_instance.web resource with var.ami_id and var.instance_type.

The whole main.tf file becomes:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.region
}

resource "aws_security_group" "web" {
  name        = "web-server-sg"
  description = "Allow inbound HTTP traffic on port 80"

  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    description = "Allow all outbound traffic"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
    #!/bin/bash
    apt-get update
    apt-get install -y apache2
    echo "Hello from Terraform" > /var/www/html/index.html
    systemctl start apache2
    systemctl enable apache2
  EOF

  tags = {
    Name = "web-server"
  }
}

output "instance_ip" {
  description = "Public IP address of the web server"
  value       = aws_instance.web.public_ip
}

The security group resource does not need any changes because it does not use region, AMI, or instance type.

Create a variable definitions file

You can set variable values in a file named terraform.tfvars. Terraform automatically loads this file when you run commands. Create terraform.tfvars with the same values as the defaults, so your deployment stays the same.

region        = "us-east-1"
instance_type = "t2.micro"
ami_id        = "ami-0c55b159cbfafe1f0"

Now run terraform fmt to format the files, and terraform validate to check the syntax.

terraform fmt
terraform validate

You should see a message that the configuration is valid.

Test a variable change

To see variables in action, change the instance_type in terraform.tfvars to t3.micro. Then run terraform plan.

terraform plan

The plan will show a change to the aws_instance.web resource because the instance type is different. Do not apply this change. Change the value back to t2.micro in terraform.tfvars and run terraform plan again. The plan should show no changes.

Understand variable precedence

Terraform reads variable values from several places. If the same variable is set in more than one place, a value in a terraform.tfvars file overrides a default in the variable declaration. A value passed on the command line with -var overrides both. This order lets you keep common defaults in the declaration, set project-specific values in terraform.tfvars, and make temporary changes on the command line without editing files.

For example, you can run terraform plan -var="instance_type=t3.micro" to see the same change you tested earlier, without touching terraform.tfvars. The command line value is used only for that run. After the command, your files still have the original value. This is useful when you want to try a different setting without changing your saved configuration.

Key takeaways

  • Variables let you change settings without editing resource blocks.
  • Declare variables in variables.tf with a name, type, description, and optional default.
  • Reference variables in configuration with var.<name>.
  • Set values in terraform.tfvars, which Terraform loads automatically.
  • Run terraform fmt and terraform validate after changing configuration.

Try it

Change the region variable in terraform.tfvars to eu-west-1. Run terraform plan. Terraform will try to manage the resources in the new region, so the plan shows that it will create two resources: the security group and the instance. This is not a replacement because the existing resources are in us-east-1. Then change the region back to us-east-1 and run terraform plan again. The plan should show no changes. A good result is that the plan shows two resources to add when the region is changed, and no changes when it is restored.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.