DEV Community

Cover image for Variables and Outputs in Terraform Day 3
Avesh
Avesh

Posted on

Variables and Outputs in Terraform Day 3

Terraform, an Infrastructure as Code (IaC) tool, allows you to manage and provision infrastructure resources using declarative configuration files. Two critical concepts in Terraform—variables and outputs—help in parameterizing configurations and extracting useful information about the managed infrastructure. This article covers variable types, variable declaration and definition, output values, local values, and variable validation in Terraform, supplemented by examples and hands-on exercises.

Variable Types

Terraform variables enable dynamic configuration by parameterizing values. They support the following types:

  1. String: Represents plain text.
   variable "region" {
     type = string
     default = "us-east-1"
   }
Enter fullscreen mode Exit fullscreen mode
  1. Number: Represents numeric values, including integers and floats.
   variable "instance_count" {
     type = number
     default = 2
   }
Enter fullscreen mode Exit fullscreen mode
  1. Bool: Represents a boolean value (true or false).
   variable "enable_feature" {
     type = bool
     default = true
   }
Enter fullscreen mode Exit fullscreen mode
  1. List: Represents a collection of values of the same type.
   variable "availability_zones" {
     type = list(string)
     default = ["us-east-1a", "us-east-1b"]
   }
Enter fullscreen mode Exit fullscreen mode
  1. Map: Represents a collection of key-value pairs.
   variable "tags" {
     type = map(string)
     default = {
       environment = "production"
       team        = "devops"
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Object: Represents structured data with named attributes.
   variable "instance_config" {
     type = object({
       instance_type = string
       ami_id        = string
       key_name      = string
     })
     default = {
       instance_type = "t2.micro"
       ami_id        = "ami-0c55b159cbfafe1f0"
       key_name      = "default"
     }
   }
Enter fullscreen mode Exit fullscreen mode
  1. Tuple: Represents a collection of values of different types.
   variable "example_tuple" {
     type = tuple([string, number, bool])
     default = ["example", 123, true]
   }
Enter fullscreen mode Exit fullscreen mode

Variable Declaration and Definition

Declaration

Variables are declared in a Terraform configuration file, typically variables.tf, using the variable block:

variable "example_variable" {
  type    = string
  default = "default_value"
}
Enter fullscreen mode Exit fullscreen mode

Definition

The values for variables can be defined in multiple ways:

  1. Inline Definition: Using -var flag during terraform apply:
   terraform apply -var "region=us-west-2"
Enter fullscreen mode Exit fullscreen mode
  1. Variable Definition Files: Using .tfvars files:
    • Create a file named terraform.tfvars or example.tfvars.
   region = "us-west-2"
Enter fullscreen mode Exit fullscreen mode
  • Apply the configuration:
   terraform apply -var-file="example.tfvars"
Enter fullscreen mode Exit fullscreen mode
  1. Environment Variables: Prefix variable names with TF_VAR_:
   export TF_VAR_region=us-west-2
Enter fullscreen mode Exit fullscreen mode
  1. Interactive Input: Terraform prompts for values if no default is provided.

Example: Dynamic AWS Instance Configuration

variables.tf:

variable "instance_type" {
  type    = string
  default = "t2.micro"
}

variable "region" {
  type = string
}
Enter fullscreen mode Exit fullscreen mode

main.tf:

provider "aws" {
  region = var.region
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = var.instance_type
}
Enter fullscreen mode Exit fullscreen mode

Command:

terraform apply -var "region=us-east-1"
Enter fullscreen mode Exit fullscreen mode

Output Values

Output values allow you to extract information about your resources after deployment. These can be displayed in the terminal, used by other configurations, or exported for automation.

Syntax

output "output_name" {
  value = resource.attribute
}
Enter fullscreen mode Exit fullscreen mode

Example: Displaying AWS Instance Public IP

outputs.tf:

output "instance_ip" {
  value = aws_instance.example.public_ip
}
Enter fullscreen mode Exit fullscreen mode

Command to View Outputs

terraform output
Enter fullscreen mode Exit fullscreen mode

Local Values

Local values help define intermediate values that simplify configurations. They are defined using the locals block.

Example: Defining Derived Values

main.tf:

locals {
  environment = "production"
  instance_tags = {
    Name        = "example-instance"
    Environment = local.environment
  }
}

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = local.instance_tags
}
Enter fullscreen mode Exit fullscreen mode

Variable Validation

Variable validation ensures that inputs meet specific criteria. It is defined using the validation block inside a variable block.

Example: Validating Instance Count

variables.tf:

variable "instance_count" {
  type = number

  validation {
    condition     = var.instance_count > 0 && var.instance_count <= 10
    error_message = "The instance count must be between 1 and 10."
  }
}
Enter fullscreen mode Exit fullscreen mode

Hands-On Validation

terraform apply -var "instance_count=15"
Enter fullscreen mode Exit fullscreen mode

Output:

Error: The instance count must be between 1 and 10.
Enter fullscreen mode Exit fullscreen mode

Conclusion

Variables and outputs in Terraform provide powerful mechanisms for creating modular, reusable, and parameterized infrastructure configurations. By using variable types, declaration methods, output values, local values, and variable validation, you can create robust Terraform scripts tailored to your needs. Start with small examples and gradually incorporate advanced features into your workflows.

Top comments (0)