遍历Terraform 0.11的列表

时间:2020-04-09 00:28:00

标签: terraform terraform-provider-aws

我有一个terraform文件,该文件将资源和方法部署到AWS中的现有APIGW。目前,我的逻辑仅创建一个方法(POST)。我想在TF中更新我的逻辑,这样,如果用户想为其资源创建多个方法,就可以。

我在网上四处张望,不确定自己的逻辑是否正确,因为当我执行Terraform作业时,出现以下错误。

aws_api_gateway_integration.integration:找不到变量“ aws_api_gateway_method.newexecution.http_method”的资源“ aws_api_gateway_method.newexecution”

以下是我的Terraform Apply命令发送的内容:

地形计划-var = gatewayID = XXXX -var = parentID = XXXX -var = lambda_name = lambda -var = path_name =资源名称-var = awsAccount = 123456 -var = resource_method = [“ POST”,“ GET”] < / p>

下面是我的Terraform文件和variable.tf文件的方式。

resource "aws_api_gateway_resource" "NewResource" {
  rest_api_id = "${var.gatewayID}"
  parent_id   = "${var.parentID}"
  path_part   = "${var.path_name}"
}

resource "aws_api_gateway_method" "newexecution" {
  count = "${length(var.resource_method)}"
  rest_api_id   = "${var.gatewayID}"
  resource_id   = "${aws_api_gateway_resource.NewResource.id}"
  http_method   = "${var.resource_method[count.index]}"
  authorization = "NONE"
  depends_on    = ["aws_api_gateway_resource.NewResource"]
}



variable "region" {
  default = "us-east-1"
}

variable "lambda_name" {
  type = "string"
}

variable "path_name" {
  type = "string"
}

variable "awsAccount" {
  type = "string"
}

variable "gatewayID" {
  type = "string"
}

variable "parentID" {
  type = "string"
}

variable "resource_method" {
  type = "list"
}

关于如何解决此问题的任何建议,以便Terraform将创建新资源并向该资源添加POST和GET?这在Terraform 0.11(使用Terraform 0.11.7)中不可行

1 个答案:

答案 0 :(得分:1)

在Terraform版本11中具有循环

元素是功能 **使用**

http_method = "${element(var.resource_method, count.index)}"

您的代码将是

resource "aws_api_gateway_method" "newexecution" {
  count = "${length(var.resource_method)}"
  rest_api_id   = "${var.gatewayID}"
  resource_id   = "${aws_api_gateway_resource.NewResource.id}"
  http_method   = "${element(var.resource_method, count.index)}
  authorization = "NONE"
  depends_on    = ["aws_api_gateway_resource.NewResource"]
}
element(list, index)
element(["a", "b", "c"], 1)
b

element(["a", "b", "c"], 3)
a

该元素将从索引0开始,一旦索引超过列表的长度,它将再次从0开始。

例如:

element(["a", "b", "c"], 3)
a

element(["a", "b", "c"], 7)
b