From 6ab4c2ebc9f8190dd366b3cb6b8543e9d6ead21f Mon Sep 17 00:00:00 2001 From: Artem Volkov Date: Fri, 26 Apr 2024 21:12:59 +0200 Subject: [PATCH] doc: remove confusion about count and for_each --- writing-terraform-configurations.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/writing-terraform-configurations.md b/writing-terraform-configurations.md index cce3060..9891d7d 100644 --- a/writing-terraform-configurations.md +++ b/writing-terraform-configurations.md @@ -40,3 +40,22 @@ website = { } ``` {% endcode %} + +## Use `for_each` and `count` for different purposes + +If you want to create multiple resources in a loop for each element in a list or map, always use `for_each`. It will save you if you want to remove some resources dependent on an element in the middle of a list. + +```hcl +resource "aws_instance" "this" { + for_each = toset(var.availability_zones) + availability_zone = each.value + // ... other attributes +} +``` +If you want to have resource only if a variable seted to true, use `count` +```hcl +resource "aws_instance" "vpn" { + count = var.use_vpn ? 1 : 0 + // ... other attributes +} +``` \ No newline at end of file