Course outlines for learning terraform.
count
or for_each
?expected time | requirements |
---|---|
45 minutes | A computer with Terraform installed, terraform knowledge. |
Goal: Understand when to use count
and when for_each
.
Most programming languages have some way to loop
. An example in bash
:
for item in a b c ; do
echo "${item}"
done
Will show:
a
b
c
Typically you write a loop to prevent repetition. It makes code shorter and more readable, plus mistakes are also not repeated.
parameter | count | for_each |
---|---|---|
terraform version | very early | 0.12.6 |
input | number | map or list |
situation | multiple similar resources | multiple related resources |
count
exampleresource "azurerm_resource_group" "example" {
count = 3
name = "example-${count.index}"
location = "West Europe"
}
In the example above, 3 resources are created, the only variable you can use is a number, stored under count.index
.
for_each
exampleThere are two ways to use for_each
:
This is the simples form; you simply pass a list of strings (actually a set) and you can reuse that one of the strings from the list in your Terraform codel.
resource "azurerm_resource_group" "example" {
for_each = toset( ["westeurope", "easteurope"] )
name = "my_rg-${each.value}"
location = each.value
}
Here you can pass both a key
and value
for that key to your Terraform code.
resource "azurerm_resource_group" "example" {
for_each = {
my_rg_one = "westeurope"
my_rd_two = "easteurope"
}
name = each.key
location = each.value
}
In the example above, both the key
(left from =
) and the value
(right from =
are used.)
This is a little more complex, so use it with caution; newcomers to Terraform may be confused.
Both with count
and for_each
, you can make a resource “conditional”, meaning: Maybe make the resource.
variable "feature_enabled" {
description = "Enable some feature."
type = bool
default = true
}
resource "x" "default" {
count = var.feature_enabled ? 1 : 0
...
}
variable "feature_enabled" {
description = "Enable some feature."
type = bool
default = true
}
variable "my_map" {
description = "Some map."
type = map
default = {
x = "y"
y = "z"
}
}
resource "y" "default" {
for_each = var.feature_enabled ? my_map : {}
...
}
Here is a trick to spread machines over GCP availability zones.
Have a look at some example counting and for-each-ing.
count.
for_each
with a list.for_each
with a map.count
(scroll up a little), what are the names of resource groups that will be created?count
or for_each
?