Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure terraform code to get Lambda ARN after creation?

This was a previous question I asked: How to get AWS Lambda ARN using Terraform?

This question was answered but turns out didn't actually solve my problem so this is a follow up.

The terraform code I have written provisions a Lambda function:

Root module:

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
    }
  }
}

provider "aws" {
   region = var.region
   profile = var.aws_profile
}

module "aws_lambda_function" {
   source = "./modules/lambda_function"
}

Child module:

resource "aws_lambda_function" "lambda_function" {
   function_name = "lambda_function"
   handler = "lambda_function.lambda_handler"
   runtime = "python3.8"
   filename = "./task/dist/package.zip"
   role = aws_iam_role.lambda_exec.arn
}

resource "aws_iam_role" "lambda_exec" {
   name = "aws_iam_lambda"
   assume_role_policy = file("policy.json")
}

What I want the user to be able to do to get the Lambda ARN:

terraform output

The problem: I cannot seem to include the following code anywhere in my terraform code as it causes a "ResourceNotFOundException: Function not found..." error.

data "aws_lambda_function" "existing" {
  function_name = "lambda_function"
}

output "arn" {
  value = data.aws_lambda_function.existing.arn
}

Where or how do I need to include this to be able to get the ARN or is this possible?

like image 496
Cogito Ergo Sum Avatar asked Mar 31 '26 17:03

Cogito Ergo Sum


1 Answers

You can't lookup the data for a resource you are creating at the same time. You need to output the ARN from the module, and then output it again from the main terraform template.

In your Lambda module:

output "arn" {
  value = aws_lambda_function.lambda_function.arn
}

Then in your main file:

output "arn" {
  value = module.aws_lambda_function.arn
}
like image 189
Mark B Avatar answered Apr 02 '26 23:04

Mark B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!