1
votes

I have a terraform file which deploys a resource and method to an existing APIGW in AWS. Currently my logic only creates a single method (POST). I'd like to update my logic within TF so that if a user wants to create more than one method for their resource they can.

I've looked around the web and not sure if I have my logic right as when I run my terraform job I get the below error.

aws_api_gateway_integration.integration: Resource 'aws_api_gateway_method.newexecution' not found for variable 'aws_api_gateway_method.newexecution.http_method'

Below is what is sent in my terraform apply command:

terraform plan -var=gatewayID=XXXX -var=parentID=XXXX -var=lambda_name=lambda -var=path_name=resourcename -var=awsAccount=123456 -var=resource_method=["POST", "GET"]

Below is how I have my terraform file and my variable.tf file.

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"
}

Any suggestions on how I can fix this so Terraform will create a new resource and add a POST and GET to that resource? Is this not doable in Terraform 0.11 (using terraform 0.11.7)

1
Can you try this http_method = "${element(var.resource_method, count.index)}" ?mohit

1 Answers

1
votes

For having loops in terraform version 11

element is the function ** USE **

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

your code will be

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

the element will start from index 0 and once the index goes above the length of the list it will start from 0 again.

For example:

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

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