当 AWS Lambda 函数在自定义 VPC 中时,因为该 VPC 未启用 InternetGateway,所以 Lambda 函数默认不会获得互联网访问权限。为解决该问题,可通过以下 Python 代码实现在自定义 VPC 中给Lambda函数创建一个 NAT Gateway,以连接VPC和互联网之间的通信。
''' import boto3
def create_nat_gateway(client, allocation_id, subnet_id): return client.create_nat_gateway(AllocationId=allocation_id, SubnetId=subnet_id)
def lambda_handler(event, context): client = boto3.client('ec2') allocation_id = "nat-allocation-id" subnet_id = "subnet-id" create_nat_gateway(client, allocation_id, subnet_id) return { 'statusCode': 200, 'body': json.dumps('NAT Gateway created successfully!') } '''
代码实现中,需替换 "nat-allocation-id" 为 NAT Gateway 分配ID,"subnet-id" 为 Lambda 函数和NAT网关所在的子网的ID。
另外,还需在VPC 的路由表中添加一条路由规则,将互联网流量路由到 NAT Gateway 上,如下所示:
Destination | Target |
---|---|
0.0.0.0/0 | nat-gateway-id |
替换 "nat-gateway-id" 为 NAT Gateway 的 ID。
通过以上操作,即可在自定义 VPC 中让 Lambda 函数获取互联网访问权限。