在 Lambda 函数的 VPC 配置中,必须为它提供足够的权限,使其能够在 VPC 中访问与特定函数关联的 AWS 服务。为此,可以创建一个位于 VPC 中的 NAT 网关,并将相应的路由表和安全组配置更新为允许出站流量。这可以通过以下代码示例实现:
Resources:
LambdaFunction:
Type: "AWS::Lambda::Function"
Properties:
VpcConfig:
SecurityGroupIds:
- sg-xxxxxx
SubnetIds:
- subnet-xxxxxx
Role: !GetAtt [ LambdaExecutionRole, Arn]
Handler: index.handler
Runtime: nodejs14.x
Code:
S3Bucket: s3-bucket-name
S3Key: s3-key-name
S3ObjectVersion: s3-object-version
ZipFile: Some zip contents
# 创建 NAT 网关和路由表
NatGateway:
Type: "AWS::EC2::NatGateway"
Properties:
AllocationId: !ImportValue NatGatewayAllocationId
SubnetId: !Select [ 0, !Ref PublicSubnets ]
NatRouteTable:
Type: "AWS::EC2::RouteTable"
Properties:
VpcId: !Ref Vpc
NatRoute:
Type: "AWS::EC2::Route"
DependsOn: NatGateway
Properties:
RouteTableId: !Ref NatRouteTable
DestinationCidrBlock: "0.0.0.0/0"
NatGatewayId: !Ref NatGateway
LambdaRouteTableAssoc:
Type: "AWS::EC2::SubnetRouteTableAssociation"
Properties:
RouteTableId: !Ref NatRouteTable
SubnetId: !Select [ 0, !Ref PrivateSubnets ]
# 更新安全组配置以允许 Lambda 访问所需的 AWS 服务
LambdaSecurityGroup:
Type: "AWS::EC2::SecurityGroup"
Properties:
VpcId