Loop through resource output and pass it to Data source

Hi, I have a Terraform module that takes Lambda code zip files as input and create as many lambdas as the code zip files. I need to extend this and pass the arn of the created lambdas to a template_file data source which basically updates a JSON file with the lambda arn’s.
This is my Lambda code

`resource "aws_lambda_function" "lambda_function" {
  for_each      = local.code_zip_files
  function_name = each.value
  role          = aws_iam_role.lambda_role.arn
  s3_bucket     = data.aws_s3_objects.lambda_zip_files.id
  s3_key        = each.key
  handler       = var.lambda_handler
  runtime       = var.lambda_runtime

I need to pass the output of the above resource as below, lambdaarn${index} is the variable name in JSON file that needs to be replaced

data "template_file" "state_machine_definition" {
  template = file("DocumentsInterfaceStepFunction.asl.json")
  vars = {for index, item in aws_lambda_function.lambda_function.*: "lambdaarn${index}" => item[*]}

I’m running into issues looping through the lambda resource output and pass it to the data source. Can someone please guide me? Thanks

Hi @mondevops03,

You don’t need the .* when referring to the lambda_function in the for each, aws_lambda_function.lambda_function is already an object you can iterate over. Using the .* operator is adding all the instances as a single object to a list.

Can you explain what item[*] is supposed to represent?

thanks @jbardin without the * I’m not able to get the index of the for loop. And I’m trying to read Lambda arn like item.arn but it was giving an error “There is no attribute arn”

The * is changing the data structure you are iterating over, so the index you are getting is not really useful in any way. It’s hard to describe what to do when we don’t know what you want to achieve.

Can you show what the data type of local.code_zip_files is so we can see how the aws_lambda_function is expanded, and what exactly you want to assign to the vars attribute?

I wanted to get the index, so used *. Basically I’m trying to build a key/value map, and use that to pass values to variables in JSON file. I’m able to do that with the below

data "template_file" "state_machine_definition" {
  template = file("DocumentsInterfaceStepFunction.asl.json")
  vars = {for item in aws_lambda_function.lambda_function: item.function_name => item.arn}

This topic was automatically closed 62 days after the last reply. New replies are no longer allowed.