amazon-web-servicesaws-lambdaterraformterraform-aws-modules

Terraform AWS: Access Lambda's function URL inside the function itself


I have a Python API deployed on AWS Lambda. The API calls OAuth, which means that the API should send its own URL in the request; and lambda URLs are generated upon request.

I'm using Terraform and specifically the lambda module (for easier deployment as I don't have to package anything, it just takes the directory).

module "registration_api_tf" {
  source = "terraform-aws-modules/lambda/aws"

  function_name      = "registration_api_tf"
  handler            = "lambda_function.lambda_handler"
  runtime            = "python3.9"
  source_path        = "../src/registration/"
  attach_policy_json = true
  policy_json = # ...
  create_lambda_function_url    = true
  # ... other configs
  environment_variables = {
    client_id     = var.client_id
    client_secret = var.client_secret
    # own_url       = module.registration_api_tf.lambda_function_url
  }
}

As you can see, I was trying to set the own_url env variable, but terraform flags it as circular. I tried using self.lambda_function_url, but again terraform objected to using self.

I believe this is possible to do using a local_exec provisioner, but I'd rather not add more local dependencies (aws-cli) to the project.

Is there any workaround/module to solve this?


Solution

  • You could get the Lambda function to determine its own URL by itself, using the AWS API (boto3 docs here). To call that, you'll need the Lambda function name; this is available in the context object that your function is invoked with.

    So the process would look like