0
votes

I'm trying to use an existing Lambda function as a data source and create an EC2 instance. This Lambda function essentially provides the latest AMI.

I'm looking at this doc:

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/lambda_invocation

Source Block:


data "aws_lambda_invocation" "example" {
  function_name = aws_lambda_function.resource_selector.ResourceSelector
  input = <<JSON
{
  "key1": "AMIRegexPattern"
  
  }
JSON
}

output "result_entry" {
  value = jsondecode(data.aws_lambda_invocation.example.result)["key1"]
}


It throws this error and I'm a little lost:


Error: Reference to undeclared resource

  on create-ec2.tf line 26, in data "aws_lambda_invocation" "example":
  26:   function_name = aws_lambda_function.resource_selector.ResourceSelector

A managed resource "aws_lambda_function" "resource_selector" has not been
declared in the root module.

Here is the function details:


Function Name - ResourceSelector
Function ARN : arn:aws:lambda:us-east-1:xx50:function:ResourceSelector

Any help on what I am missing? Also curious on this line esp and if this is correct:

function_name = aws_lambda_function.resource_selector.ResourceSelector

Thanks

1

1 Answers

0
votes

If the lambda is created outside terraform you have to hardcode or pass via parameter, like so:

function_name = "ResourceSelector"

aws_lambda_function.resource_selector doesn't exist, or you can manage the lambda defininng the aws_lambda_function resource.

Also if you just want to get the latest AMI you don't need a lambda. Terraform actually has a data source that can pull that for you: aws_ami

Example:

data "aws_ami" "example" {
  most_recent      = true
  owners           = ["self"]

  filter {
    name   = "name"
    values = ["myami-*"]
  }
}