0

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"
}
1
  • 1
    No, you would have to restructure your code in such a way that when you add a new value terraform just adds a new resource instead of replacing the current one. That means probably changing the variable to a list or a map plus count or for_each meta-argument. Commented Oct 13, 2022 at 13:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.