How to iterate multiple resources over the same li

2019-07-31 00:46发布

问题:

New to Terraform here. I'm trying to create multiple projects (in Google Cloud) using Terraform. The problem is I've to execute multiple resources to completely set up a project. I tried count, but how can I tie multiple resources sequentially using count? Here are the following resources I need to execute per project:

  1. Create project using resource "google_project"
  2. Enable API service using resource "google_project_service"
  3. Attach the service project to a host project using resource "google_compute_shared_vpc_service_project" (I'm using shared VPC)

This works if I want to create a single project. But, if I pass a list of projects as input, how can I execute all the above resources for each project in that list sequentially?

Eg.

Input

project_list=["proj-1","proj-2"]

Execute the following sequentially:

resource "google-project" for "proj-1"
resource "google_project_service" for "proj-1"
resource "google_compute_shared_vpc_service_project" for "proj-1"

resource "google-project" for "proj-2"
resource "google_project_service" for "proj-2"
resource "google_compute_shared_vpc_service_project" for "proj-2"

I'm using Terraform version 0.11 which does not support for loops

回答1:

In Terraform, you can accomplish this using count and the two interpolation functions, element() and length().

First, you'll give your module an input variable:

variable "project_list" {
  type = "list"
}

Then, you'll have something like:

resource "google_project" {
  count = "${length(var.project_list)}"
  name  = "${element(var.project_list, count.index)}"
}

resource "google_project_service" {
  count = "${length(var.project_list)}"
  name  = "${element(var.project_list, count.index)}"
}

resource "google_compute_shared_vpc_service_project" {
  count = "${length(var.project_list)}"
  name  = "${element(var.project_list, count.index)}"
}

And of course you'll have your other configuration in those resource declarations as well.

Note that this pattern is described in Terraform Up and Running, Chapter 5, and there are other examples of using count.index in the docs here.