This tutorial explains variable types in Terraform.

Variables are used to store the value. Declare it once, use it in multiple files, and provides dynamics.

What variables are required?

Let’s define a provider for AWS

provider "aws"{
    region ="us-north-1"

access_key,secret_key, and region are hard-coded values. These can be used in multiple places for different resources.

There is a duplicate If you hardcoded in multiple places. and some properties are secret details that are not exposed. Variables solved for the above problems.

How to declare a variable in Terraform

variables provides terraform configuraiton dynamic

Here is a syntax

variable "variable_name"{
    type = "datatype"
    description = "variable description"
    default = "default value"
  • name: Name of a variable
  • type: can be one of string, list, map and boolean
  • default: Default value to a variable
  • description: Variable description
  • validation: validation rules applied
  • sensitive: true for masking the value for sensitivity

Here is a example

variable "access_key"{
    type = "string"
    description = "aws access_key"

variable "region"{
    type = "string"
    description = "aws region"

variable "secret_key"{
    type = "string"
    description = "aws secret_key"

Once the variable is declared, you need to assign the values. terraform.tfvars contains variables with values


access_key="test access key"
secret_key="test secret key"
region="test region"

Once variables are assigned with values, You can access the variables as given below in multiple files

variables are accessed using ${var.variablename} syntax.

provider "aws"{
    region ="${var.region}"

Difference between terraform.tfvars and is a terraform configuration file, contains used to declare a variable with an optional default value.

For example

variable "region" {
    default = "us-west-1"
    description = "Region of Azure VPC"

terraform.tfvars contains used to assign the values for an variable.



Naming conventions for variables

  • Variables are identifier names that contain alphanumeric characters and underscores (_), and hyphens (-)
  • The first character is not a digit, but a character.
  • It contains a valid name to depict the meaningful to the user

What are variable types in Terraform?

There are multiple variable types in Terraform

  • Input Variable:

    Input variables are values supplied to infrastructure that can be used in many files.

  • Output Variable: These variables hold the information from infrastructure code result

  • Local Variable:

Local variables are declared using the locals keyword. These scopes are limited to the declared modules block only

locals {

These can be accessed using local.variablename

resources "aws_instance"{

How many ways variables create and assign values in Terraform?

Variables can be created using three ways

  • variable block
  • CLI prompt
  • using -var command line arguments