Loops


Figure 1091. An implicit loop creating three servers using count Slide presentation
# main.tf
resource "hcloud_server" "mySrv" {
  count     = 2
  name      = "www-${count.index}"
  ...
}
# outputs.tf
output "servers" {
  value = join(", ",
    [
      for srv in hcloud_server.mySrv :
         "(${srv.name}|${srv.ipv4_address})"     
    ])
}
terraform apply
...
Plan: 5 to add, 0 to change, 0 to destroy.

Outputs:                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                     
servers = "(www-0|46.62.254.219), (www-1|204.168.245.188)"     

exercise No. 16

Creating a set of servers

Q:

As a prerequisite read the set documentation.

Then start from Using configuration variables and follow Figure 1091, “An implicit loop creating three servers using count ” to create multiple servers. But instead of using count define a variable containing a set of server names:

# config.auto.tfvars
serverNames = ["www", "mail"]

Then use the for_each meta argument in favour of count. On execution you shall see:

terraform apply
...
Outputs:                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                     
servers = "(mail|204.168.245.188), (www|46.62.254.219)"