跨账号VPC内Lambda访问S3超时:需NAT网关还是VPC端点?
账号A下有一个S3存储桶,账号B下有一个Lambda函数,需要让这个Lambda读取存储桶的内容。已为IAM角色配置合适权限并添加到存储桶信任策略中。Lambda不在VPC内时运行正常,但加入账号B的VPC后出现超时,推测是连通性问题。
之前为另一个Lambda使用VPC端点访问Secrets Manager是正常的,但此次用VPC端点连接S3未能解决问题。部分资料显示Lambda需NAT/Internet网关才能访问跨账号存储桶,但AWS官方说明:
By default, Lambda functions have access to the public internet. This is not the case after they have been configured with access to one of your VPCs. If you continue to need access to resources on the internet, set up a NAT instance or Amazon NAT Gateway. Alternatively, you can also use VPC endpoints to enable private communications between your VPC and supported AWS services.
因此想咨询:Lambda访问该跨账号存储桶是否需要NAT/Internet网关,还是仅用VPC端点即可?
补充信息:VPC端点的Terraform配置
resource "aws_vpc_endpoint" "s3" { vpc_id = aws_vpc.main.id service_name = "com.amazonaws.eu-west-1.s3" vpc_endpoint_type = "Interface" security_group_ids = [ aws_security_group.lambda.id, ] subnet_ids = [aws_subnet.subnet_1a.id] tags = { Name = "vpc-endpoint-s3" Environment = var.aws_profile Terraform = true } } resource "aws_vpc_endpoint_security_group_association" "s3" { vpc_endpoint_id = aws_vpc_endpoint.s3.id security_group_id = aws_security_group.lambda.id }
Lambda访问跨账号S3存储桶仅用VPC端点即可,不需要NAT/Internet网关,但你的配置存在关键问题:
你创建的是Interface类型的VPC端点,但S3的VPC端点应该使用Gateway类型。Interface端点适用于Secrets Manager这类服务,而S3是AWS少数仅支持(或推荐使用)Gateway端点的核心服务之一。
修正后的Terraform配置示例
resource "aws_vpc_endpoint" "s3" { vpc_id = aws_vpc.main.id service_name = "com.amazonaws.eu-west-1.s3" vpc_endpoint_type = "Gateway" # 关联Lambda所在子网对应的路由表ID route_table_ids = [ aws_route_table.private_subnet_1a.id, ] tags = { Name = "vpc-endpoint-s3-gateway" Environment = var.aws_profile Terraform = true } }
额外注意事项
- 路由表配置:Gateway端点必须关联到Lambda所在子网的路由表,确保S3的地址前缀(可配置为
0.0.0.0/0或具体存储桶的前缀路由)指向该端点。 - 存储桶策略检查:除IAM角色权限外,需确认存储桶策略未添加限制公网访问的条件(比如
aws:SourceIp),且明确允许账号B的Lambda角色访问。 - 安全组清理:Gateway端点不需要配置安全组,你之前的
aws_vpc_endpoint_security_group_association资源可以直接删除。
若使用Gateway端点后仍有问题,排查方向:
- 路由表是否正确关联S3端点,且路由条目优先级高于默认路由(如有)
- 存储桶区域是否与VPC端点区域一致(S3端点为区域级资源)
- Lambda所在子网是否为私有子网(无直接公网访问),且路由表中无指向NAT网关的默认路由干扰S3私有访问路径
内容的提问来源于stack exchange,提问作者sobmortin

