# HCL: the Terraform language

Read and write HCL with confidence: blocks, arguments and references, the value types, and expressions such as conditionals, for loops and functions, tried live in terraform console.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 2. About 25 minutes, beginner. Source: https://devops.rajeev.pro/courses/terraform/02-hcl

## What you will learn

- Name the parts of a block and write a resource from memory
- Refer to another resource's attribute and explain why that creates a dependency
- Use the value types string, number, bool, list, map and object correctly
- Write conditionals, for expressions and function calls, and test them in terraform console

> **Lab status.** **Verified lab:** every terraform console expression and the apply order shown. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** none. <br />**Cloud lab:** none; nothing here needs a cloud account.

Every Terraform file is written in **HCL**, the HashiCorp Configuration Language. It's
deliberately small: a few kinds of blocks, values and expressions. Once you can read it, every
Terraform project in the world looks familiar. This lesson covers the grammar; you'll test
expressions live in `terraform console`.

> **Video.** [Introduction to HashiCorp Terraform with Armon Dadgar](https://www.youtube.com/watch?v=h970ZBgKINg) (HashiCorp)

## Syntax

A Terraform project is a folder of files ending in `.tf`. Terraform reads **all** of them
together, in no particular order, so splitting code into `main.tf`, `variables.tf` and
`outputs.tf` is purely for people. A few rules cover almost everything:

- **Blocks** hold configuration: `resource "..." "..." { ... }`.
- **Arguments** set a value inside a block: `filename = "out.txt"`.
- **Comments** use `#` (preferred), `//`, or `/* ... */` for several lines.
- **Strings** go in double quotes, and `${...}` inside a string inserts a value: `"web-${var.env}"`.
- **Multi-line strings** use a heredoc: `<<-EOT ... EOT` (the `-` strips leading indentation).
- **Order doesn't matter.** Terraform works out what to do first from references, not from the
  order you wrote things.

## Blocks and arguments

> **Figure.** A resource block annotated. resource is the block type, local_file is the resource type, inventory is the local name. Inside the braces, filename and content are arguments set with expressions, and lifecycle is a nested block with prevent_destroy set to true. The resource is referred to elsewhere as local_file.inventory.filename. On the right, the value types string, number, bool, list, map, object and null, each with an example, and the kinds of expressions.
>
> Block type, labels, arguments and a nested block. Everything in Terraform follows this shape.

This is the configuration used through the course:

```hcl
# main.tf
resource "random_pet" "server" {
  length = 2
}

resource "local_file" "inventory" {
  filename = "${path.module}/out/inventory.txt"
  content  = "server: ${random_pet.server.id}\n"
}
```

Read the second block part by part:

1. **`resource`** is the block type. Others you'll meet: `terraform`, `provider`, `variable`,
   `output`, `locals`, `data` and `module`.
2. **`"local_file"`** is the resource type. The part before the underscore names the provider
   (`local`), the rest names the thing (`file`).
3. **`"inventory"`** is your local name. Together they form the **address** `local_file.inventory`,
   unique within the folder.
4. **`filename = ...`** and **`content = ...`** are arguments. Which arguments exist, and which are
   required, is defined by the provider; its page on the Terraform Registry lists them.
5. **`path.module`** is a built-in value: the folder this file is in.

### References build the order

`content` uses `random_pet.server.id`, an attribute of another resource. That one reference tells
Terraform two things: it needs the pet name to write the file, so it must create `random_pet.server`
**first**. The apply output from the lab shows exactly that order:

```text
random_pet.server: Creating...
random_pet.server: Creation complete after 0s [id=model-kiwi]
local_file.inventory: Creating...
local_file.inventory: Creation complete after 0s [id=e041d7cb3c1d1c469796feb23dcb0459b375560d]
```

Anything you can read on a resource after it's created, such as an `id`, an IP address or an ARN,
is an **attribute**, and the provider docs list them under "Attribute Reference".

## Types and expressions

### Value types

| Type            | Example                                   | Use for                                       |
| --------------- | ----------------------------------------- | --------------------------------------------- |
| `string`        | `"ap-south-1"`                            | Names, IDs, regions                           |
| `number`        | `8080`, `0.5`                             | Ports, counts, sizes                          |
| `bool`          | `true`                                    | Feature switches                              |
| `list(...)`     | `["web", "api"]`                          | Ordered values                                |
| `map(...)`      | `{ dev = "t3.micro", prod = "t3.large" }` | Lookups by key                                |
| `set(...)`      | `toset(["a", "b"])`                       | Unique, unordered values (used by `for_each`) |
| `object({...})` | `{ name = "web", port = 8080 }`           | A record with named, typed fields             |

`null` means "leave this argument unset", as if you hadn't written it.

### terraform console

`terraform console` evaluates expressions interactively, using your project's variables and state.
It's the fastest way to learn HCL. Everything below ran on Terraform 1.17.1:

```text
> 1 + 2 * 3
7

> "web-${1 + 1}"
"web-2"

> upper("ap-south-1")
"AP-SOUTH-1"

> length(["web", "api", "db"])
3

> type({ name = "web", port = 8080 })
object({
    name: string,
    port: number,
})
```

Terraform worked out the type of that object literal itself: an `object` with a string and a number.

### Conditionals

```text
> true ? "yes" : "no"
"yes"

> contains(["t3.micro", "t3.small"], "t3.large")
false
```

The form is `condition ? value_if_true : value_if_false`, for example
`instance_type = var.env == "prod" ? "t3.large" : "t3.micro"`. Both results must have the same type.

### for expressions

A `for` expression transforms a collection. Square brackets build a list, curly braces build a map:

```text
> [for s in ["web", "api", "db"] : "${s}-prod"]
[
  "web-prod",
  "api-prod",
  "db-prod",
]

> { for s in ["web", "api"] : s => length(s) }
{
  "api" = 3
  "web" = 3
}
```

Add `if` to filter: `[for s in var.names : s if s != "test"]`.

### Functions

Terraform has over a hundred built-in functions, and you can't write your own. The ones you'll use
weekly:

```text
> merge({ team = "shop" }, { env = "prod" })
{
  "env" = "prod"
  "team" = "shop"
}

> lookup({ dev = "t3.micro", prod = "t3.large" }, "prod", "t3.nano")
"t3.large"

> cidrsubnet("10.0.0.0/16", 8, 2)
"10.0.2.0/24"

> join(",", ["10.0.1.0/24", "10.0.2.0/24"])
"10.0.1.0/24,10.0.2.0/24"

> jsonencode({ port = 8080, tls = true })
"{\"port\":8080,\"tls\":true}"
```

`cidrsubnet("10.0.0.0/16", 8, 2)` means "add 8 bits to the prefix (so /24) and take subnet number
2", which is how VPC modules carve subnets without hand-typed CIDRs. `merge` is the usual way to
combine a set of common tags with resource-specific ones.

> **Two more shortcuts.** A **splat** `aws_instance.web[*].id` collects one attribute from every instance of a resource made with `count`. A **dynamic block** generates repeated nested blocks (such as many `ingress` rules) from a list. Use dynamic blocks sparingly: they make code harder to read.

## Mission: Answer five questions with terraform console

In any initialised folder, use terraform console to work out: the region name in upper case, a list of prod server names from ['web', 'api', 'db'], a map of each name to its length, the fourth /24 subnet of 10.0.0.0/16, and the instance type for prod from a map with a default. Save each expression and its answer.

- You need: terraform console
- You'll have: ~/hcl-answers.txt

```sh
$ for e in 'upper("ap-south-1")' '[for s in ["web","api","db"] : "${s}-prod"]' \
    '{ for s in ["web","api","db"] : s => length(s) }' 'cidrsubnet("10.0.0.0/16", 8, 3)' \
    'lookup({ dev = "t3.micro", prod = "t3.large" }, "prod", "t3.nano")'; do
    echo "> $e"; echo "$e" | terraform console; done > ~/hcl-answers.txt
$ cat ~/hcl-answers.txt
```

The subnet answer should be `"10.0.3.0/24"` (subnet numbers start at 0). If console complains about
a missing provider, run `terraform init` in that folder first.

## Try it

- Run `terraform console` in any initialised folder and evaluate `upper("ap-south-1")`.
- Turn `["web", "api", "db"]` into `["web-prod", "api-prod", "db-prod"]` with a for expression.
- Find the third /24 subnet of 10.0.0.0/16 with `cidrsubnet`.
- Ask `type({ name = "web", port = 8080 })` and read the answer.
- Do the mini mission and keep `~/hcl-answers.txt`.

## Quiz

1. In `resource "local_file" "inventory" { ... }`, what is "inventory"?
   - The resource type
   - **The local name you choose, used in the address local_file.inventory** (answer)
   - The provider name
   Why: The first label is the resource type, defined by the provider. The second is your name for this resource, unique within the module.

2. What happens when one resource refers to `random_pet.server.id`?
   - Nothing special
   - **Terraform knows it must create random_pet.server first, because it needs that value** (answer)
   - Terraform copies the resource
   Why: References are how Terraform builds its dependency graph. You rarely need depends_on because references already order the work.

3. What does `[for s in ["web", "api"] : "${s}-prod"]` return?
   - **["web-prod", "api-prod"]** (answer)
   - { web = "prod", api = "prod" }
   - An error
   Why: A for expression in square brackets builds a list by evaluating the expression after the colon for each element.

4. Which line is a nested block, not an argument?
   - filename = "out.txt"
   - **lifecycle { prevent_destroy = true }** (answer)
   - count = 2
   Why: Arguments use name = value. Nested blocks have a type and braces, with no equals sign.

## Resources

- [Terraform language overview](https://developer.hashicorp.com/terraform/language) (HashiCorp)
- [Types and values](https://developer.hashicorp.com/terraform/language/expressions/types) (HashiCorp)
- [for expressions](https://developer.hashicorp.com/terraform/language/expressions/for) (HashiCorp)
- [Built-in functions](https://developer.hashicorp.com/terraform/language/functions) (HashiCorp)
- [terraform console command](https://developer.hashicorp.com/terraform/cli/commands/console) (HashiCorp)
