如何在同一列表上迭代多个资源? [英] How to iterate multiple resources over the same list?
问题描述
此处是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:
- 使用
resource "google_project"
创建项目
- 使用
resource "google_project_service"
启用API服务
- 使用
resource "google_compute_shared_vpc_service_project"
将服务项目附加到宿主项目(我正在使用共享的VPC)
- Create project using
resource "google_project"
- Enable API service using
resource "google_project_service"
- 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.
请注意,在平台启动和运行的第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.
这篇关于如何在同一列表上迭代多个资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!