HCL syntax: blocks, arguments and expressions

Beginner · 13 min

Read any Terraform file by knowing three things: blocks have a type and labels, arguments assign values, and expressions compute those values from references.

Before thisInit, validate, plan, apply and destroy in practice

Cloud Champ · 19 min · from 1:32

HCL syntax: blocks, arguments and expressions

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Cloud ChampReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A Terraform file is built from blocks. A block has a type, zero or more labels in quotes, and a body in braces.
  • Inside a body, `name = value` is an argument. A nested `name { ... }` with no equals sign is a block.
  • Values are expressions: literals, references such as `var.region` or `aws_vpc.main.id`, operators, function calls and string templates.
  • Order in the file never matters. References create the order.

A language for describing, not running

Most configuration formats start as data files, then grow conditions and loops until they are secretly programming languages, with none of the tooling. JSON could describe infrastructure, but a thousand-line JSON file has no comments and no way to say “this value comes from that resource”. HashiCorp wrote HCL to sit in between: readable like a config file, with just enough expression power to wire things together.

You do not run HCL top to bottom. You declare facts about what should exist, and Terraform works out the order. If you remember only that, most of the syntax stops being surprising.

Blocks

Everything is a block. Here is one from the earlier lessons, plus a nested one. This is a made-up example in the shape the AWS provider docs describe, and I did not run it:

resource "aws_security_group" "web" {
  name   = "web"
  vpc_id = aws_vpc.main.id

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

A block has:

  • a type, here resource, which says what kind of thing it is. The top-level types you will use are terraform, provider, resource, data, variable, output, locals and module.
  • labels, in quotes. resource takes two: the resource type and your local name. variable takes one. locals takes none.
  • a body in braces.

Inside a body you find arguments and further blocks. name = "web" is an argument: a name, an equals sign and an expression. ingress { ... } has no equals sign, so it is a nested block, and you can repeat it to get several rules. That distinction is the single most common beginner stumble. When the provider docs list something as a “block”, use braces. When they list an “argument”, use =. A later lesson on dynamic blocks covers generating repeated blocks.

Expressions

The right side of every argument is an expression. The kinds you meet in the first week:

  • Literals: "text", 42, true, ["a", "b"], and objects such as { env = "dev" }.
  • References: var.region for an input, local.name for a local, aws_vpc.main.id for a resource attribute, data.aws_ami.al2023.id for a data source. The shape is always <type>.<name>.<attribute>.
  • Operators: +, ==, &&, and the conditional condition ? a : b.
  • Function calls: lower("ABC"), merge(a, b), cidrsubnet(var.cidr, 8, 1).
  • String templates: "${var.env}-api" inserts a value into text. Use a bare reference (var.env) when you want the value itself rather than a string.

Comments are # or // for a line and /* ... */ for a span.

References make the order

A reference does two jobs. It supplies a value, and it tells Terraform “this block needs that one first”. In the security group above, aws_vpc.main.id means the group waits for the VPC. Nothing in the text says “create the VPC first”. The next lesson shows the graph this builds. It also explains why you can reorder blocks, or spread them across files, without changing a plan.

What real files look like

Before writing more of my own, I looked at one that people actually depend on. I downloaded main.tf from the terraform-aws-modules/vpc module, a very widely used AWS network module (236 million registry downloads), and counted:

$ curl -sL https://raw.githubusercontent.com/terraform-aws-modules/terraform-aws-vpc/master/main.tf -o main.tf
$ wc -l main.tf
1549 main.tf
$ grep -c '^resource' main.tf
74
$ grep -c 'count *= .*? 1 : 0' main.tf
27
$ grep -c ' ? ' main.tf
131

1,549 lines and 74 resources, and 27 of those resources start with count = ... ? 1 : 0. That is the conditional operator used as an on/off switch, a pattern you will read constantly. The file is mostly arguments and references, with a handful of loops. The language is small, and most of the skill is in recognising these few patterns. (Those counts are plain grep, so a comment containing the same text would be counted.)

JSON and other forms

Terraform also accepts a JSON form, files ending .tf.json, meant for generated configuration. You rarely write it by hand. OpenTofu additionally reads files ending .tofu and prefers one over a .tf of the same name, per its docs. Both use the same grammar.

Formatting is part of the syntax culture

terraform fmt rewrites files to the standard style: two-space indent, aligned equals signs within a group. Run it before every commit. It never changes meaning, and it means diffs show real changes only. Formatting and linting get their own lesson in the testing group.

About the video

The embed is Cloud Champ’s “Day 2: Master HCL syntax and Learn how to write Terraform Code”, July 2023, from “How to write Comments in HCL” to just before the summary (1:32 to 14:27). Its chapters cover comments, blocks and their types, attributes, data types, conditionals, functions and resource dependency, which matches this lesson’s outline. I judged it from those chapter titles and did not check every statement. The presenter’s examples lean on AWS. English was judged from title, channel and English auto-captions. It is two to three years older than the newest videos in this roadmap, and the HCL basics it teaches have not changed.

Where this fits

You can now read a block. Next, learn to read what Terraform says it will do with it, and the graph behind the scenes: reading a plan and the dependency graph.

Check yourself

  1. 01How can you tell an argument from a nested block at a glance?

    An argument has an equals sign: `ami = "ami-123"`. A nested block does not: `ebs_block_device { ... }`. Some attributes take a list of objects and look similar, so the provider docs say which one is which.

  2. 02What is the address of `resource "aws_vpc" "main"`, and what does `aws_vpc.main.id` do in another block?

    The address is `aws_vpc.main`, type then local name. `aws_vpc.main.id` reads the `id` attribute and also tells Terraform the other block depends on the VPC.

  3. 03You move a `resource` block from the top of `main.tf` to the bottom. What changes in the plan?

    Nothing. Terraform builds order from references, not from position in a file.

  4. 04What does `"${var.env}-api"` do, and what is `var.env` on its own?

    The first is a string template that inserts the variable into text. The second is a plain reference whose value keeps its own type, such as a number or list.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark