HCL (HashiCorp Configuration Language) Fundamentals
7 min read
Welcome to the language of clouds! ☁️
If you’ve ever looked at a JSON file and thought, "Why are there so many curly braces?" or looked at YAML and panicked because you pressed the spacebar one too many times—you are going to love HCL.
HCL is designed to be human-readable first, and machine-friendly second. It is the language we use to talk to Terraform.
In this guide, we aren't just writing code; we are defining the blueprint of our digital reality. We will cover the basic grammar (Syntax), the translators (Providers), the building blocks (Resources), and the information gatherers (Data Sources).
1. Blocks, Arguments, and Expressions: The Syntax of HCL
🧐 The Problem
Imagine trying to describe a house to an architect.
- XML would be like describing every single brick's chemical composition.
- JSON is like writing a strict legal contract where if you miss a comma, the architect quits.
- YAML is efficient, but if you pause for breath (indentation) at the wrong time, the architect builds the roof in the basement.
We needed a way to describe infrastructure that looks like a config file but acts like a programming language.
💡 The Solution: HCL Structure
HCL (HashiCorp Configuration Language) creates a structured hierarchy. It is declarative, meaning you describe the castle you want, and Terraform figures out how to stack the stones.
The Anatomy of a Block
The fundamental unit of HCL is the Block. It is a container for other content.
<BLOCK TYPE> "<BLOCK LABEL>" "<BLOCK LABEL>" {
# Block Body
<IDENTIFIER> = <EXPRESSION>
}Let's look at a real example of a block used to create a file on your local machine:
resource "local_file" "my_pet" {
filename = "/root/pet_name.txt"
content = "My pet is a robotic dog."
}Breaking it down (Alphabets before Words):
- Block Type (
resource): This tells Terraform what kind of object we are defining. Are we building something? fetching data? configuring settings? - Block Labels (
"local_file","my_pet"):- The first label is usually fixed by the provider (e.g.,
local_fileis a specific type of resource). - The second label is the Local Name. This is for you (and Terraform) to reference this block internally. It doesn't affect the actual file name on the disk.
- The first label is usually fixed by the provider (e.g.,
- The Body (
{ ... }): Everything inside the curly braces belongs to this block. - Arguments (
key = value):filename: The identifier (argument name)."/root/pet_name.txt": The expression (argument value).
🥸 Industry Standard Tip
Snake Case Everywhere: In HCL, we prefer
snake_case(words separated by underscores) for identifiers and names.
- ✅
my_web_server- ❌
myWebServerormy-web-server
2. Providers: Connecting Terraform to the Cloud
🧐 The Problem
Terraform is a binary executable. It is smart, but it is actually quite "dumb" about specific APIs. Out of the box, Terraform doesn't know what "AWS" is, or what "Azure" is, or even how to talk to Docker.
If you tell Terraform "Create an AWS Server," it stares at you blankly. It needs a translator.
💡 The Solution: Providers
Providers are plugins (small binaries) that Terraform downloads. They understand the API interactions for specific services. They translate your HCL code into API calls (like POST /ec2/instance).
The required_providers Block
In the professional world, we don't just say "use AWS." We say "Use AWS, but specifically version 5.0," to prevent updates from breaking our code.
We define this in a terraform block (usually in a file named versions.tf or at the top of main.tf).
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
# Configuring the provider
provider "aws" {
region = "us-east-1"
}What is happening here?
source: We are telling Terraform where to download the plugin.hashicorp/awsis the official registry shorthand.version:~> 5.0is a pessimistic constraint operator. It means "Any version from 5.0 up to (but not including) 6.0." This is a massive safety feature in production.provider "aws"block: This configures the plugin. Here, we tell it to operate in theus-east-1(N. Virginia) region.
⚡ Fun Fact
There are over 3,000 providers in the Terraform Registry! You can use Terraform to order pizza (Domino's provider), configure your Spotify playlist, or manage your GitHub repositories. It's not just for servers!
3. Resources: Building Your Infrastructure Blocks
🧐 The Problem
We have the syntax, and we have the provider (the translator). Now, how do we actually create something? We need a way to define the lifecycle of a specific infrastructure object.
💡 The Solution: The resource Block
A Resource describes one or more infrastructure objects (like an EC2 instance, a DNS record, or a VPC).
When you declare a resource, you are telling Terraform: "Ensure this object exists with these exact settings."
Example: Creating an AWS EC2 Instance
resource "aws_instance" "app_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "Production-Web-Server"
Environment = "Prod"
}
}Deep Dive into the Components
- The Resource Type (
aws_instance): This is defined by the Provider. You cannot make this up. You must look at the documentation to know that AWS instances are calledaws_instanceand notaws_server. - The Local Name (
app_server): This is how you refer to this specific instance inside your code.- Reference format:
<RESOURCE TYPE>.<LOCAL NAME> - Example:
aws_instance.app_server
- Reference format:
- Arguments:
ami: The Amazon Machine Image ID (the OS).instance_type: How big is the CPU/RAM?tags: Metadata labels.
🧪 Simulation: The State File
When you run this code, Terraform creates the server on AWS. But it also writes a file called terraform.tfstate on your computer.
- Real Life: The server running in Virginia.
- HCL: Your blueprint.
- State File: The receipt that links your blueprint to the real server ID (e.g.,
i-123456789).
Warning: Never edit the state file manually. It is like doing brain surgery on yourself while looking in a mirror. You will break something.
4. Data Sources: Fetching Existing Infrastructure Data
🧐 The Problem
In the example above, we hardcoded the AMI ID (ami-0c55b159cbfafe1f0).
This is bad practice.
Why? Because IDs change. If AWS updates the Ubuntu image, your code breaks. Or, what if you want to deploy a server into a VPC that another team built? You don't manage that VPC, so you can't create a resource for it, but you need its ID.
💡 The Solution: Data Sources
A Data Source allows Terraform to read information from the cloud provider without creating anything. It’s like a "Search Query."
Example: Dynamic AMI Lookup
Instead of hardcoding the ID, let's ask AWS for the latest Ubuntu image.
# 1. Define the Data Source (The Query)
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
}
filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical (Official Ubuntu Owner ID)
}
# 2. Use the Data Source in a Resource
resource "aws_instance" "web" {
# Reference the data source here!
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
}How to Reference Data
The syntax to use the data you found is:data.<TYPE>.<LOCAL_NAME>.<ATTRIBUTE>
In our example: data.aws_ami.ubuntu.id
- data: We are looking at a data block.
- aws_ami: The type of lookup.
- ubuntu: The local name we gave the query.
- id: The specific attribute we want (the actual AMI ID string).
🥸 Industry Standard Tip
Hardcoding vs. Data Sources:
- Junior Dev: Hardcodes the VPC ID (
vpc_id = "vpc-123"). Code breaks when deployed to a new region.- Senior Dev: Uses a
datasource to find the VPC named "default" or looks it up by tag. Code works everywhere.
📚 Summary Checklist
- Block: The container
{ ... }. - Argument: The setting
key = value. - Provider: The plugin that talks to the API (always version lock it!).
- Resource: Something we want to create/manage.
- Data Source: Something we want to read/query.
You have now mastered the alphabet of HCL. You can read, query, and define the cloud. Next, you'll learn how to make this dynamic using Variables!
🔗 References & Further Reading
- Official HCL Syntax Docs: HashiCorp HCL Documentation
- Provider Registry: Terraform Registry
- AWS Provider Docs: AWS Provider on Registry
- Style Guide: Terraform Community Style Guide
Challenge
Your task is to write a complete HCL configuration for Terraform to provision a single AWS EC2 instance. The configuration must adhere to the following specifications:
Terraform and Provider Configuration:
- Define a
terraformblock that requires thehashicorp/awsprovider with a pessimistic version constraint for version5.0(e.g.,~> 5.0). - Configure the AWS provider to operate in the
us-east-1region.
- Define a
Dynamic AMI Lookup:
- Create a data source to look up the latest Amazon Machine Image (AMI) for Amazon Linux 2.
- The data source block should be of type
aws_amiwith the local nameamazon_linux. - It must be filtered to find the most recent image (
most_recent = true). - The filter should specify the AMI name pattern as
amzn2-ami-hvm-*-x86_64-gp2and the owner asamazon.
EC2 Instance Resource:
- Define a resource of type
aws_instancewith the local nameweb_server. - This resource must use the ID of the AMI found by the
amazon_linuxdata source. - Set the instance type to
t2.micro. - Add a
tagsargument with a single tag:Nameset toWebServerInstance.
- Define a resource of type
Expected result
The output should be a single, valid HCL configuration file containing four distinct blocks: terraform, provider, data, and resource.
- The
terraformblock must contain arequired_providersblock, which in turn specifies theawsprovider withsource = "hashicorp/aws"andversion = "~> 5.0". - The
providerblock forawsmust have a single argument:region = "us-east-1". - A
datablock of typeaws_amiwith the local nameamazon_linuxmust be present. It should containmost_recent = true, anownersargument set to["amazon"], and afilterblock. Thefilterblock must have two arguments:name = "name"withvalues = ["amzn2-ami-hvm-*-x86_64-gp2"]. - A
resourceblock of typeaws_instancewith the local nameweb_servermust exist. It needs anamiargument that references the data source output (data.aws_ami.amazon_linux.id), aninstance_typeargument set to"t2.micro", and atagsblock containingName = "WebServerInstance".