You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform部署的AWS Lambda函数内获取自身Function URL?

解决Terraform部署Lambda时Function URL循环依赖的问题

方案1:拆分Lambda与Function URL资源

弃用模块自带的create_lambda_function_url配置,单独用aws_lambda_function_url资源创建Function URL,先完成Lambda部署,再生成URL并回写到Lambda环境变量,彻底规避循环依赖。

修改后的Terraform配置示例:

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 = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "lambda:GetFunctionUrlConfig",
      "Resource": "${module.registration_api_tf.lambda_arn}"
    }
  ]
}
EOF
  # 关闭模块自带的Function URL创建
  create_lambda_function_url = false
  environment_variables = {
    client_id     = var.client_id
    client_secret = var.client_secret
    own_url       = ""
  }
}

# 单独创建Function URL
resource "aws_lambda_function_url" "registration_api" {
  function_name      = module.registration_api_tf.lambda_function_name
  authorization_type = "NONE" # 根据实际授权需求调整
}

# 更新Lambda环境变量,注入生成的Function URL
resource "aws_lambda_function" "update_env" {
  function_name        = module.registration_api_tf.lambda_function_name
  handler              = module.registration_api_tf.lambda_handler
  runtime              = module.registration_api_tf.lambda_runtime
  filename             = module.registration_api_tf.lambda_filename
  source_code_hash     = module.registration_api_tf.lambda_source_code_hash

  environment {
    variables = merge(
      module.registration_api_tf.environment_variables,
      { own_url = aws_lambda_function_url.registration_api.function_url }
    )
  }

  # 明确依赖顺序,确保先创建Function URL再更新环境变量
  depends_on = [aws_lambda_function_url.registration_api]
}

方案2:Lambda运行时动态获取Function URL

不在Terraform中传递URL,而是在Python代码里通过AWS SDK(boto3)主动获取自身的Function URL,完全绕开Terraform的依赖问题。

Python代码示例:

import boto3
import os

lambda_client = boto3.client('lambda')

def get_own_function_url():
    function_name = os.environ['AWS_LAMBDA_FUNCTION_NAME']
    response = lambda_client.get_function_url_config(FunctionName=function_name)
    return response['FunctionUrl']

# 在需要使用URL的逻辑中调用
own_url = get_own_function_url()

注意:需给Lambda配置lambda:GetFunctionUrlConfig权限(参考方案1中的policy_json),确保代码能正常调用API。

内容的提问来源于stack exchange,提问作者Mohamed Yasser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 15:16:06