Skip to content

Commit

Permalink
Add Terraform "for_each patterns" note
Browse files Browse the repository at this point in the history
  • Loading branch information
kencx committed Dec 7, 2024
1 parent 526268b commit 5a24a85
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ build:
hugo --buildDrafts --buildFuture --gc --minify --enableGitInfo

serve:
hugo serve --buildDrafts --buildFuture --gc --enableGitInfo --ignoreCache --debug --disableFastRender
hugo serve --buildDrafts --buildFuture --gc --enableGitInfo --ignoreCache --disableFastRender

clean:
rm -rf public/
2 changes: 1 addition & 1 deletion content/til/arch/custom-repository.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: "Custom Repository"
title: "Hosting Custom Repository in S3"
date: 2023-07-07
lastmod: 2023-07-07
draft: false
Expand Down
3 changes: 3 additions & 0 deletions content/til/terraform/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
title: "Terraform"
---
81 changes: 81 additions & 0 deletions content/til/terraform/for_each.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
---
title: "for_each Patterns"
date: 2024-12-08
lastmod: 2024-12-08
draft: true
toc: true
---

## List of strings

```hcl
locals {
servers = [
"vm-1",
"vm-2",
"vm-3"
]
}
resource "example" "this" {
for_each = toset(local.servers)
name = each.key
}
```

## List of objects

```hcl
locals {
servers = [
{
name = "vm-1"
ip = "10.0.0.5"
}
]
}
resource "example" "this" {
for_each = {
for i, vm in local.servers : vm.name => vm
}
name = each.value.name
ip_address = each.value.ip
}
```

## Cartesian product of two lists

```hcl
locals {
domains = [
"https://google.com",
"https://example.com"
]
paths = [
"/foo",
"/bar",
"/bax"
]
}
resource "example" "this" {
urls = [for url in setproduct(locals.domains, locals.paths) : join("", url)]
}
```

## Conditional

```hcl
resource "example" "this" {
for_each = var.create_example ? [] : [1]
name = ...
ip_address = ...
}
```

## References
- [How to for_each through list of objects in
Terraform](https://stackoverflow.com/questions/58594506/how-to-for-each-through-a-listobjects-in-terraform-0-12)

0 comments on commit 5a24a85

Please sign in to comment.