该问题通常是由于 VPC 配置不正确或 Lambda 函数没有与正确的 VPC 子网和安全组关联所致。解决方法是在 VPC 中创建一个私有子网,并将 Lambda 函数与该私有子网和安全组关联起来。下面是一个示例 CloudFormation 模板,用于创建一个带有 Lambda 函数的 VPC:
{
"Resources": {
"VPC": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.0.0.0/16"
}
},
"Subnet": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": { "Ref": "VPC" },
"CidrBlock": "10.0.1.0/24",
"AvailabilityZone": "us-east-1a"
}
},
"SecurityGroup": {
"Type": "AWS::EC2::SecurityGroup",
"Properties": {
"VpcId": { "Ref": "VPC" },
"GroupDescription": "Allow SSH and HTTP traffic",
"SecurityGroupIngress": [
{
"IpProtocol": "tcp",
"FromPort": "22",
"ToPort": "22",
"CidrIp": "0.0.0.0/0"
},
{
"IpProtocol": "tcp",
"FromPort": "80",
"ToPort": "80",
"CidrIp": "0.0.0.0/0"
}
]
}
},
"LambdaFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"S3Bucket": { "Ref": "LambdaBucket" },
"S3Key": { "Fn::Join": [ "/", [ { "Ref": "LambdaVersion" }, "lambda.zip" ] ] }
},
"FunctionName": "MyFunction",
"Handler": "index.handler",
"Role": { "Fn::GetAtt": [ "LambdaExecutionRole", "Arn" ] },
"Runtime": "nodejs12.x",
"Timeout": 30,
"VpcConfig": {
"SecurityGroupIds": [ { "Fn::GetAtt": [ "SecurityGroup", "GroupId" ] } ],
"SubnetIds": [ { "Ref": "Subnet" } ]
}
}
},
"LambdaExecutionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
},
"Policies": [
{
"PolicyName": "lambda-policy",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
}
]
}
}
]
}
}
}
}