Opscraft
Terraform · Lesson 2 of 12 · 4 min read

HCL: the language

Blocks, arguments and types

resource "aws_s3_bucket" "logs" {          # block type, resource type, local name
  bucket = "acme-prod-logs-ap-south-1"     # argument
  tags = {                                  # map
    Environment = "prod"
  }
}

A resource's address is aws_s3_bucket.logs; its attributes are referenced as aws_s3_bucket.logs.arn.

Types: string, number, bool, list(type), set(type), map(type), object({...}), tuple([...]), and any.

Variables, locals and outputs

Enlarge diagramInputsvariables, set by .tfvars,-var or TF_VAR_ envConfigurationlocals: derived values ·resources · datasourcesOutputsIDs, endpoints: printedor read by other stacks
Figure 1. A configuration as a function: variables are the inputs, locals are working values, outputs are what it hands back to people or other stacks.
Swipe sideways to see all of it, or tap to open it full screen.
variable "environment" {
  description = "Deployment environment"
  type        = string
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod."
  }
}

variable "subnets" {
  type = map(object({
    cidr = string
    az   = string
  }))
}

variable "db_password" {
  type      = string
  sensitive = true          # redacted in plan/apply output (still stored in state!)
}

locals {
  name_prefix = "acme-${var.environment}"
  common_tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
    Repo        = "acme/platform-infra"
  }
}

output "vpc_id" {
  description = "ID of the VPC"
  value       = aws_vpc.main.id
}

Setting variable values (later sources win): defaults → terraform.tfvars / *.auto.tfvars → -var-file=prod.tfvars → -var 'environment=prod'; environment variables TF_VAR_environment=prod sit below files in precedence. Undefined required variables are prompted for interactively (or fail in CI with -input=false).

  • locals — named expressions computed once inside a module (avoid repetition).
  • outputs — expose values from a module to its caller, or from the root module to the CLI/remote state readers.

Expressions and functions

name      = "${local.name_prefix}-web"                        # interpolation
instance  = var.environment == "prod" ? "m6i.large" : "t3.medium"   # conditional
azs       = slice(data.aws_availability_zones.available.names, 0, 3)
cidrs     = [for i, az in local.azs : cidrsubnet(var.vpc_cidr, 4, i)]   # for expression → list
by_name   = { for s in var.services : s.name => s }            # for expression → map
prod_only = [for s in var.services : s.name if s.critical]     # with filter
arns      = aws_iam_role.app[*].arn                            # splat
merged    = merge(local.common_tags, { Name = "web" })
json      = jsonencode({ Version = "2012-10-17", Statement = [] })
file_body = templatefile("${path.module}/user_data.sh.tftpl", { cluster = var.cluster_name })
value     = try(var.config.optional_field, "default")
length(var.subnets); lookup(var.amis, var.region, null); coalesce(var.a, var.b)

Useful functions: cidrsubnet (subnet maths — remember the IP topic), merge, concat, flatten, keys/values, zipmap, toset, contains, format, join/split, replace, lower, jsonencode/yamlencode, file, templatefile, base64encode, try, can, timestamp (avoid in resources — causes perpetual diffs). Explore them in terraform console.

Data sources

data "aws_availability_zones" "available" { state = "available" }

data "aws_ami" "al2023" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

data "aws_caller_identity" "current" {}
data "aws_iam_policy_document" "assume_ec2" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

aws_iam_policy_document is the idiomatic way to write IAM JSON in Terraform — validated and composable.

Dynamic blocks

Generate repeated nested blocks:

resource "aws_security_group" "web" {
  name   = "${local.name_prefix}-web"
  vpc_id = aws_vpc.main.id

  dynamic "ingress" {
    for_each = var.ingress_ports            # e.g. [80, 443]
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

Use sparingly — overused dynamic blocks make modules hard to read.