There isn’t really a looping construct, but there’s still a way to perform a type of a loop in terraform.

Btw – as a quick aside, the difference between a terraform.tfvars and a variables.tf file is simply one of providing default values (the tfvars is used to set all default values). If you set your default values within the .tf file itself, the tfvars is unnecessary.

Modified Looping in Terraform

Step 1 – Add an f5_app_count variable, which will contain the number of F5 instances.

Step 2 – The actual value is instantiated in step 2 in the terraform.tfvars file  – as such

f5_count = 3

Step 3 – In the google_compute_instance_template resource, add the count property (which is available for all resources and data Terraform blocks).

To further clarify resource names, the name of the compute_instance resource, we add the suffix with the current index of the count that we increment by 1.

resource "google_compute_instance_template" "f5-template" {
  count = var.f5_app_count   
  name         = "${var.environment}-f5-${count.index+1}"
  machine_type = "${var.instance_type}"
  ...
 }

Summary

That’s it. The count built in property in Terraform simplifies things. This is a common use case (spin up 3 of these resource types or 5 of those…).

Next Steps?

Need help with your Terraform or PowerShell or other automation effort? Set up a free consultation – Start the conversation today.  




Need an experienced Cloud Networking or a Cloud Data Protection Expert?  Anuj has successfully delivered over a dozen deployments on each of the public clouds (AWS/GCP/Azure) including several DevSecOps engagements. Set up a time with Anuj Varma.