VPC 中的 AWS Lambda 初始化阶段超时

问题描述 投票:0回答:2

描述

我有一个 Lambda 函数(部署为 docker 映像),不在 VPC 中时可以正常工作。它做的第一件事是连接到 AWS Secret 管理器以获取凭证,然后使用它连接到外部 Web API 以获取一些数据。我需要将 Lambda 移动到 VPC 才能访问 MongoDB Atlas 数据库。我使用以下 Terraform 模块来创建我的 VPC:

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "vpc-mongodb-atlas"
  cidr = "10.0.0.0/16"

  azs             = ["eu-west-2a", "eu-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets = ["10.0.0.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
}

然后我将我的 Lambda 添加到此 VPC:

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

...

  image_uri = module.docker_image.image_uri
  package_type = "Image"

...

  vpc_subnet_ids         = module.vpc.private_subnets
  vpc_security_group_ids = [module.vpc.default_security_group_id]
  attach_network_policy              = true
}

问题

配置上述 Terraform 后,我的 Lambda 在

init
阶段开始超时,并显示以下日志:

INIT_REPORT Init Duration: 10007.38 ms Phase: init Status: timeout

我怀疑它无法连接到互联网,但是在浏览了所有可能的帖子和说明并尝试了一切之后,我无法真正理解此设置中有什么问题以及如何使其工作......任何帮助都会真的很感激。

来自 AWS Web 界面的更多信息

专有网络配置:

私有子网路由表(指向公有NAT网关): 公共子网路由表(指向 Internet 网关):

网络 ACL:

Lambda VPC 配置:

aws-lambda terraform-provider-aws amazon-vpc nat private-subnet
2个回答
0
投票

事实证明,如果您使用

terraform-aws-modules/vpc
配置VPC,默认情况下它会将默认安全组设置为没有入站和出站规则。通过添加以下设置允许所有出站流量后,我的 Lambda 函数能够连接到互联网:

原有VPC模块:

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "vpc-mongodb-atlas"
  cidr = "10.0.0.0/16"

  azs             = ["eu-west-2a", "eu-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets = ["10.0.0.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
}

更新了 VPC 模块(具有

default_security_group
设置):

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "vpc-mongodb-atlas"
  cidr = "10.0.0.0/16"

  azs             = ["eu-west-2a", "eu-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets = ["10.0.0.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true

  # NEW SETTINGS
  manage_default_security_group = true
  default_security_group_egress = [
    {
      rule_no    = 100
      action     = "allow"
      from_port  = 0
      to_port    = 0
      protocol   = "-1"
      cidr_blocks = "0.0.0.0/0"
    },
  ]
}

0
投票

在没有 vpc 的情况下我也得到了同样的结果,问题是如果您不使用保留或配置的并发,那么 init 阶段 timoout 默认为 10 秒。来自文档:

注意 10 秒超时不适用于使用预配置并发或 SnapStart 的函数。对于预配置的并发和 SnapStart 函数,您的初始化代码最多可以运行 15 分钟。时间限制为 130 秒或配置的功能超时(最长 900 秒),以较高者为准。

lambda 文档供参考

© www.soinside.com 2019 - 2024. All rights reserved.