Fryger
Fryger

Reputation: 1

Reference terraform resource by variable

I created tf file that takes input from cli and then use this as name for aws lambda, and api gateway.

Currently inputing different name just replace name in currently working one.

My goal is that every time i input new name new lambda and gateway should be created. Is it possible?

variable "repo_name" {
 type = string
}

resource "aws_lambda_function" "lambda" {
 function_name = var.repo_name
 handler       = "lambda_function.lambda_handler"
 runtime       = "python3.9"
 role          = ""
 filename      = "python.zip"
}

Upvotes: 0

Views: 231

Answers (1)

Marko E
Marko E

Reputation: 18108

This can be done in a couple of different ways, but the easiest one would be creating a local variable and just add additional names to it whenever you need a new function and API Gateway. That would look something like this:

locals {
  repo_names = ["one", "two", "three"]
}

Now, the second part can be solved with count [1] or for_each [2] meta-arguments. It's usually a matter of preference, but I would suggest using for_each:

resource "aws_lambda_function" "lambda" {
 for_each      = toset(local.repo_names)
 function_name = each.value
 handler       = "lambda_function.lambda_handler"
 runtime       = "python3.9"
 role          = ""
 filename      = "python.zip"
}

You would then follow a similar approach for creating different API Gateway resources. Note that for_each has to be used with sets or maps, hence the toset built-in function [3] usage. Also, make sure you understand how each object works [4]. In case of a set, the each.key and each.value are the same which is not the case when using maps.


[1] https://developer.hashicorp.com/terraform/language/meta-arguments/count

[2] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each

[3] https://developer.hashicorp.com/terraform/language/functions/toset

[4] https://developer.hashicorp.com/terraform/language/meta-arguments/for_each#the-each-object

Upvotes: 3

Related Questions