本文介绍了如何在同一个列表上迭代多个资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是 Terraform 的新手.我正在尝试使用 Terraform 创建多个项目(在 Google Cloud 中).问题是我必须执行多个资源才能完全建立一个项目.我尝试了 count,但如何使用 count 顺序绑定多个资源?以下是我需要为每个项目执行的以下资源:

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. 使用 resource "google_project"
  2. 创建项目
  3. 使用 resource "google_project_service"
  4. 启用 API 服务
  5. 使用 resource "google_compute_shared_vpc_service_project" 将服务项目附加到宿主项目(我使用的是共享 VPC)
  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?

例如.

输入

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

依次执行以下:

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"

我正在使用不支持 for 循环的 Terraform 0.11 版

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

推荐答案

在 Terraform 中,您可以使用 count 和两个插值函数 element()length().

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.

请注意,此模式在 Terraform Up and Running 第 5 章中进行了描述,还有其他示例使用文档中的 count.index 这里.

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.

这篇关于如何在同一个列表上迭代多个资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:32
查看更多