【问题标题】:How to pass a list of values into Lambda environment variables with Terraform如何使用 Terraform 将值列表传递给 Lambda 环境变量
【发布时间】:2022-02-08 19:12:31
【问题描述】:

我有一个 Python 脚本,可以向多个收件人发送电子邮件。我想使用 Terraform 设置我的收件人并将它们作为环境变量传递到我的 Lambda 函数中。我已将 SES 设置为单独的模块。

Lambda 函数:

def lambda_handler(event, context):
    email_to = os.environ["EMAIL"]
    # script that sends an email is here

Lambda 模块 main.tf:

resource "aws_lambda_function" "test_lambda" {
  filename      = var.filename
  function_name = "test_name"
  role          = "arn:aws:iam::123:role/lambda_role"
  handler       = var.handler

  source_code_hash = var.source_code_hash
  runtime = var.runtime
  timeout = var.timeout
  kms_key_arn = var.kms_key_arn
  memory_size = var.memory

  dynamic "environment" {
    for_each = var.env_variables != null ? var.env_variables[*] : []
    content {
      variables = environment.value
    }
  }

}

SES 模块 main.tf:

resource "aws_ses_email_identity" "email" {
    email = var.email
}

SES 模块输出.tf:

 output "email" {
    description = "Emails."
    value       = aws_ses_email_identity.email.email
    }

main.tf

module "lambda_zip" {
    source                = "../modules/lambda_zip"
    handler               = "lambda_function.lambda_handler"
    runtime               = "python3.8"
    filename              = "setup.zip"

    env_variables = {
     EMAIL = module.ses[*].email
   }
}

module "ses" {
    source      = "../modules/ses"
    for_each    = toset(["email1@example.com", "email2@example.com"])
    email       = each.value
}

output "email" {  
value = module.ses.email 
}

使用当前设置,我收到此错误:

│ Error: Unsupported attribute
│
│   on main.tf line 24, in module "lambda_zip":
│   24:    EMAIL = jsonencode(module.ses[*].email)
│
│ This object does not have an attribute named "email".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 40, in output "email":
│   40:   value = module.ses.email
│     ├────────────────
│     │ module.ses is object with 2 attributes
│
│ This object does not have an attribute named "email".

如何使用 SES 注册新电子邮件并将其传递给 Python 函数?

【问题讨论】:

    标签: python amazon-web-services aws-lambda terraform amazon-ses


    【解决方案1】:

    如果您想一次传递所有电子邮件,应该是:

        env_variables = {
         EMAIL = jsonencode(values(module.ses)[*].email)
       }
    

    然后,在您的函数中,您必须将 EMAIL 处理为 json 数据结构。

    【讨论】:

    • 这给了我This object does not have an attribute named "email".
    • @Omega 那么如何输出来自module.ses 的电子邮件?你必须明确定义一个output
    • 我的 output.tf 仍然一无所获,看起来像这样 output "email" {description = "Emails."value= aws_ses_email_identity.email.email}
    • @Omega 我更新了答案。如果仍然无法正常工作,您必须提供相关模块的完整代码。
    • 欧米茄你能用jsonencode(values(module.ses)[*].email)试试吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2019-05-20
    • 2019-12-26
    • 2020-03-08
    • 2019-04-01
    • 2019-03-04
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多