# Expressions and Functions — Terraform

Source: https://www.skillbyai.com/en/terraform/l-expr

> Compute values inside configuration.

## Interpolation, for expressions, built-in functions

HCL supports string templates (`"${var.env}-db"`), conditionals (`var.env == "prod" ? 3 : 1`), **for expressions** to transform lists and maps, and many built-in **functions**: string (`upper`, `join`, `format`), collection (`merge`, `lookup`, `flatten`), networking (`cidrsubnet`), encoding (`jsonencode`, `yamlencode`) and file functions. `terraform console` is an interactive place to try them.

## Trying functions in terraform console, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. Each expression is evaluated by terraform console: string helpers, cidrsubnet carving the third /24 out of a /16, merging maps, a lookup with a default, and a for expression.

```bash
for e in 'upper("shop")' 'join(",", ["web", "api"])' 'cidrsubnet("10.0.0.0/16", 8, 2)' 'merge({a = 1}, {b = 2})' 'lookup({dev = "t3.small", prod = "m7i.large"}, "prod", "t3.micro")' '[for s in ["web", "api"] : "${s}-svc"]'; do
  printf "%s\n  => " "$e"; echo "$e" | terraform console | tr -s "\n " " "; echo
done
```

Output:

```
upper("shop")
  => "SHOP" 
join(",", ["web", "api"])
  => "web,api" 
cidrsubnet("10.0.0.0/16", 8, 2)
  => "10.0.2.0/24" 
merge({a = 1}, {b = 2})
  => { "a" = 1 "b" = 2 } 
lookup({dev = "t3.small", prod = "m7i.large"}, "prod", "t3.micro")
  => "m7i.large" 
[for s in ["web", "api"] : "${s}-svc"]
  => [ "web-svc", "api-svc", ]
```

## Prototype in the console

Test tricky expressions (cidrsubnet, for expressions over maps) in terraform console before putting them in code.

**Quiz:** What does cidrsubnet("10.0.0.0/16", 8, 2) return?

- [x] "10.0.2.0/24"
- [ ] "10.0.0.0/8"
- [ ] "10.2.0.0/16"
- [ ] "10.0.0.2/32"

*Answer:* "10.0.2.0/24". Adds 8 bits to the prefix and picks network number 2.
