Day 7 – Type Constraints in Terraform
Source: Dev.to
Primitive Types
Primitive types are the basic building blocks: string, number, and bool.
variable "name" {
type = string
default = "Terraform"
}
variable "age" {
type = number
default = 25
}
variable "is_enabled" {
type = bool
default = true
}
Complex Types
Complex types let you group multiple values.
List (ordered collection of same‑type values)
variable "instance_ids" {
type = list(string)
}
Set (unique values, order not significant)
variable "unique_tags" {
type = set(string)
}
Tuple (ordered collection of different types)
variable "my_tuple" {
type = tuple([string, number, bool])
}
Map (string keys with same‑type values)
variable "region_mapping" {
type = map(string)
}
Object (attributes with different types, similar to a struct)
variable "server_config" {
type = object({
name = string
cpu = number
prod = bool
})
}
Special Types
any (accepts any Terraform data type)
variable "input" {
type = any
}
null (represents the absence of a value, often used to trigger default behavior)
variable "instance_type" {
default = null
}
Practical Examples
Environment‑based naming
variable "environment" {
type = string
default = "dev"
}
resource "aws_s3_bucket" "example" {
bucket = "${var.environment}-app-data"
}
Changing environment updates all dependent resources.
Scalable instance count
variable "instance_count" {
type = number
default = 3
}
resource "aws_instance" "server" {
count = var.instance_count
ami = "ami-123"
instance_type = "t2.micro"
}
Increasing instance_count creates additional servers.
Toggle monitoring
variable "monitoring_enabled" {
type = bool
default = true
}
resource "aws_instance" "server" {
monitoring = var.monitoring_enabled
}
Turn monitoring on/off with a single variable.
Multi‑AZ subnets
variable "availability_zones" {
type = list(string)
default = ["us-east-1a", "us-east-1b"]
}
resource "aws_subnet" "subnet" {
count = length(var.availability_zones)
az = var.availability_zones[count.index]
cidr_block = "10.0.${count.index}.0/24"
}
Subnets are automatically created across the specified AZs.
Centralized tagging
variable "tags" {
type = map(string)
default = {
Environment = "dev"
Owner = "teamA"
}
}
resource "aws_vpc" "main" {
tags = var.tags
}
Manage all tags from a single place.
Composite configuration object
variable "config" {
type = object({
region = string
monitoring = bool
instance_count = number
})
default = {
region = "us-east-1"
monitoring = true
instance_count = 2
}
}
provider "aws" {
region = var.config.region
}
Further Reading
For more information, see the repository:
https://github.com/ankitgadling/terraformwithaws/tree/main/day_7