How to iterate multiple resources over the same list?

情到浓时终转凉″ 提交于 2019-12-24 07:51:06

问题


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.



来源:https://stackoverflow.com/questions/56137102/how-to-iterate-multiple-resources-over-the-same-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!