Variables and Outputs: Making Configurations Dynamic
6 min read
Course: Terraform
Topic: Variables and Outputs: Making Configurations Dynamic
Welcome back, Infrastructure Artist! 🎨
Up until now, we've likely been writing Terraform code that looks like a grocery list carved into stone. If you wanted an AWS instance, you hardcoded "t2.micro". If you wanted to change the region, you had to find-and-replace every mention of "us-east-1".
That is called Hardcoding. In the world of DevOps, hardcoding is the enemy. It makes code brittle, hard to reuse, and painful to read.
Today, we are going to learn how to make your Terraform code flexible, reusable, and chatty. We are going to turn that stone tablet into a dynamic vending machine. 🏗️
1. Input Variables: Parameterizing Your Code
Definition & The Problem
The Problem: Imagine you wrote a perfect Terraform file to deploy a web server. Your colleague, Dave, wants to use it, but he needs a bigger server size. If you hardcoded t2.micro, Dave has to edit your source code. If 50 people use it, you have 50 modified copies of the same file. Chaos.
The Solution: Input Variables. These act like function arguments in programming. They are placeholders that wait for values to be injected at runtime.
How it works
You declare a variable, and then you reference it in your resources using var.variable_name.
The Syntax
In industry standard practice, we keep variable declarations in a separate file named variables.tf.
variables.tf
variable "aws_region" {
description = "The AWS region to deploy resources into"
type = string
default = "us-east-1"
}
variable "instance_type" {
description = "EC2 instance type"
type = string
# No default? Then Terraform will force you to provide one at runtime!
}main.tf
provider "aws" {
# Referencing the variable
region = var.aws_region
}
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
# Referencing the variable
instance_type = var.instance_type
}How to Assign Values (The Hierarchy)
Terraform looks for values in a specific order. Here is the industry standard way to do it:
terraform.tfvarsfile: This is the most common method. Create a file namedterraform.tfvarsand Terraform automatically loads it.hclaws_region = "us-west-2" instance_type = "t3.micro"- Environment Variables: Great for CI/CD pipelines. Prefix with
TF_VAR_.bashexport TF_VAR_instance_type="t3.small" - CLI Flags: Good for quick testing, bad for history.bash
terraform apply -var="instance_type=t3.medium"
🔥 Pro Tip: Never, ever commit a
terraform.tfvarsfile containing secrets (passwords, keys) to Git. Add*.tfvarsto your.gitignoreif it contains sensitive info.
2. Variable Types and Validation
Definition & The Problem
The Problem: If you ask a user for a "Server Count" and they type "Banana", Terraform might not crash until it actually tries to talk to AWS API, which wastes time. Or worse, they pass a list when you expected a string.
The Solution: Type Constraints and Custom Validation. This is the bouncer at the club checking IDs before letting data in.
Types
Terraform supports simple and complex types.
- Primitive:
string,number,bool. - Collection:
list(<type>),map(<type>),set(<type>). - Structural:
object({ attribute = type }),tuple([...]).
Industry Standard: The object type is powerful because it allows you to group related configuration settings together.
variables.tf
variable "server_config" {
description = "Configuration settings for the server"
type = object({
name = string
port = number
enabled = bool
tags = map(string)
})
default = {
name = "my-app"
port = 8080
enabled = true
tags = {
Environment = "Dev"
}
}
}Validation (Stop errors early)
You can write custom rules to reject bad data immediately.
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
# condition must return true if the value is valid
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}If a user tries to pass "ubuntu-20.04", Terraform stops them instantly with your error message.
3. Local Values: Keeping Code DRY
Definition & The Problem
The Problem: You are tagging every resource with a name like project-environment-appname. You find yourself typing "${var.project}-${var.env}-${var.app}" inside every single resource block. If you decide to change the naming convention, you have to edit 20 places.
The Solution: Local Values (locals). Think of these as "internal variables" or "constants" used only within the Terraform code. They are not asked of the user; they are calculated by you.
How it works
Locals allow you to assign a name to an expression. You can combine input variables to create new values.
main.tf
locals {
# Standardize naming convention
service_name = "payment-api"
common_tags = {
Service = local.service_name
Owner = "DevOps-Team"
ManagedBy = "Terraform"
}
# Logic: If environment is prod, use large instance, else micro
instance_size = var.environment == "prod" ? "t3.large" : "t3.micro"
}
resource "aws_instance" "app" {
instance_type = local.instance_size # Calculated internally
tags = local.common_tags # Reused everywhere
}
resource "aws_s3_bucket" "logs" {
bucket = "${local.service_name}-logs"
tags = local.common_tags
}🧠 Concept Check:
- Variables: Inputs from the user (Ingredients you buy).
- Locals: Intermediate calculations inside the code (The chopped onions you prepped in the kitchen).
4. Output Values: Extracting Data
Definition & The Problem
The Problem: You successfully ran terraform apply and created a web server. Great! ...Wait. What is its IP address? Do you really want to log into the AWS Console, click EC2, search for the instance, and copy-paste the IP? No.
The Solution: Output Values. This tells Terraform to print specific data to the console at the end of the run. It is also how you pass data from one Terraform module to another.
Syntax
Usually stored in outputs.tf.
outputs.tf
output "web_server_ip" {
description = "Public IP address of the web server"
value = aws_instance.web.public_ip
}
output "web_server_url" {
description = "The full URL"
value = "http://${aws_instance.web.public_dns}:8080"
}Handling Secrets
If you output a database password or a private key, Terraform will print it in plain text in your CLI logs. Your security team will not be amused. 👮
Use sensitive = true to mask it in the CLI (though it is still stored in the state file!).
output "db_password" {
value = aws_db_instance.default.password
sensitive = true
}Result in CLI: db_password = <sensitive>
🧪 Hands-On Summary
- Define
variables.tfto accept inputs (Region, Size). - Create
terraform.tfvarsto set those inputs. - Use
localsinmain.tfto combine inputs into useful tags or naming conventions. - Define
outputs.tfto show you the result (IPs, URLs) after deployment.
📚 References & Further Reading
- Official Docs: Input Variables
- Official Docs: Output Values
- Official Docs: Local Values
- Variable Validation Rules
Now go forth and parameterize! Don't let your code be a statue; make it a gymnast. 🤸♂️
Challenge
You are tasked with creating a flexible and reusable Terraform configuration for deploying a web server on an AWS EC2 instance. Your goal is to use input variables for customization, local values for standardization, and output values to expose important resource attributes.
Your task is to write the complete HCL code across four conceptual files: variables.tf, locals.tf, main.tf, and outputs.tf.
Requirements:
1. In variables.tf, define the following input variables:
aws_region: A string variable for the AWS region. It should have adescriptionand adefaultvalue of"us-east-1".instance_type: A string variable for the EC2 instance type. It must have a custom validation rule that only allows the values"t3.micro","t3.small", or"t3.medium". Provide a helpfulerror_message.ami_id: A required string variable for the Amazon Machine Image ID. It should have adescriptionbut nodefaultvalue.environment_tags: An object variable used for tagging. It should expect keysproject(string) andenvironment(string).
2. In locals.tf, define the following local values:
instance_name: A standardized name for the instance, constructed by concatenating theprojectandenvironmenttags from theenvironment_tagsvariable (e.g.,"web-server-project_name-environment_name").common_tags: A map of tags that merges theenvironment_tagsvariable with a static tag"ManagedBy" = "Terraform".
3. In main.tf, define a resource:
- Create a single
aws_instanceresource block namedweb_server. - This resource should use the input variables and local values you defined to set its
ami,instance_type, andtagsarguments.
4. In outputs.tf, define the following output values:
instance_id: Outputs the ID of theweb_serverinstance.instance_public_ip: Outputs the public IP address of theweb_serverinstance.instance_arn: Outputs the Amazon Resource Name (ARN) of theweb_serverinstance. This output must be marked as sensitive.
Expected result
Your final code should be structured as follows, with four distinct blocks corresponding to the conceptual files.
variables.tf
variable "aws_region" {
type = string
description = "The AWS region to deploy resources in."
default = "us-east-1"
}
variable "instance_type" {
type = string
description = "The EC2 instance type."
validation {
condition = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
error_message = "Allowed values for instance_type are t3.micro, t3.small, or t3.medium."
}
}
variable "ami_id" {
type = string
description = "The AMI ID for the EC2 instance."
}
variable "environment_tags" {
type = object({
project = string
environment = string
})
description = "Tags to apply to the instance for project and environment identification."
}locals.tf
locals {
instance_name = "web-server-${var.environment_tags.project}-${var.environment_tags.environment}"
common_tags = merge(
{
Name = local.instance_name
ManagedBy = "Terraform"
},
var.environment_tags
)
}main.tf
resource "aws_instance" "web_server" {
ami = var.ami_id
instance_type = var.instance_type
tags = local.common_tags
}outputs.tf
output "instance_id" {
description = "The ID of the EC2 instance."
value = aws_instance.web_server.id
}
output "instance_public_ip" {
description = "The public IP address of the EC2 instance."
value = aws_instance.web_server.public_ip
}
output "instance_arn" {
description = "The ARN of the EC2 instance."
value = aws_instance.web_server.arn
sensitive = true
}