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