Skip to main content

Module 2, HCL Syntax From Scratch

What is HCL​

HCL stands for HashiCorp Configuration Language. It is designed to be human-readable and machine-friendly.

The Four Building Blocks​

1, Blocks​

Everything in Terraform is a block. A block has a type, optional labels, and a body:

block_type "label_one" "label_two" {
argument = value
}

Real example:

resource "aws_s3_bucket" "my_bucket" {
bucket = "my-company-data"
}
  • resource, block type
  • "aws_s3_bucket", resource type (label 1)
  • "my_bucket", local name (label 2)
  • bucket = "my-company-data", argument

2, Arguments​

name = "finpay" # string
port = 3000 # number
enabled = true # boolean
availability_zones = ["us-east-1a", "us-east-1b"] # list
tags = {
Environment = "production"
Team = "platform"
}

3, Expressions​

# Reference another resource
subnet_id = aws_subnet.public.id

# String interpolation
name = "finpay-${var.environment}"

# Conditional (ternary)
instance_type = var.environment == "production" ? "t3.small" : "t3.micro"

# Function call
bucket_name = lower("MyBucket")

4, Comments​

# Single line comment

/*
Multi-line comment
Useful for explaining complex resources
*/

Data Types​

region = "us-east-1" # string
port = 5432 # number
multi_az = false # bool
subnets = ["subnet-abc", "subnet-def"] # list(string)
tags = { Name = "finpay-db" } # map(string)

# object
database = {
engine = "postgres"
version = "15"
port = 5432
}

Lab 1, Your First HCL File​

mkdir terraform-lab-01
cd terraform-lab-01
touch main.tf

Write this in main.tf:

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}

provider "aws" {
region = "us-east-1"
}

resource "aws_s3_bucket" "first_bucket" {
bucket = "my-terraform-learning-bucket-12345"

tags = {
Name = "My First Terraform Bucket"
Environment = "learning"
}
}

Then run:

terraform init # downloads the AWS provider
terraform plan # shows what will happen
terraform apply # creates the bucket
terraform destroy # deletes the bucket
warning

Observe each output carefully. terraform plan is the most important command you will ever run.

Knowledge Check​

  1. What are the four main components of an HCL block?
  2. What is the difference between a string and a number in HCL?
  3. Write an HCL expression that creates a name using string interpolation with a variable called app_name.
  4. What is the difference between a list and a map?
  5. Why does terraform init need to run before terraform plan?
Exam Mapping
  • HashiCorp Associate Obj 3: Understand Terraform basics
  • HashiCorp Associate Obj 6: Navigate Terraform workflow