API网关可以通过集成VPC链接来访问位于私有VPC中的Lambda函数。下面是使用AWS CDK和Node.js创建VPC连接和Lambda函数的示例代码:
import * as cdk from 'aws-cdk-lib';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
const app = new cdk.App();
// create a VPC for the Lambda function
const vpc = new ec2.Vpc(stack, 'MyVPC', {
cidr: '10.0.0.0/16',
natGateways: 1,
});
// create an API Gateway REST API
const api = new apigateway.RestApi(stack, 'MyApi', {
restApiName: 'my-api',
});
// create a Lambda function that will be located in a private subnet of the VPC
const myFn = new lambda.Function(stack, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset('path/to/code'),
handler: 'index.handler',
vpc,
vpcSubnets: {
subnetType: ec2.SubnetType.PRIVATE,
},
});
// create a VPC link for the API Gateway to access the Lambda function
const vpcLink = new apigateway.VpcLink(stack, 'MyVpcLink', {
targets: [vpc],
});
// create an integration that will use the VPC link to access the Lambda function
const integration = new apigateway.AwsIntegration({
service: 'lambda',
action: 'Invoke',
integrationHttpMethod: 'POST',
options: {
credentialsRole: lambdaFn.role,
passthroughBehavior: apigateway.PassthroughBehavior.WHEN_NO_MATCH,
integrationResponses: [
{
statusCode: '200',
},
],
vpcLink,
},
});
// create a resource and method to invoke the Lambda function through the API Gateway
const resource = api.root.addResource('my-resource');
resource.addMethod('POST', integration