如何使用 javascript 将 AWS Lambda 添加到 VPC

问题描述 投票:0回答:2

我需要将 lambda 函数添加到 VPC,但使用 javascript 代码 - 不需要从 aws 控制台添加。

我正在 AWS CDK 堆栈中创建我的 lambda,如下所示:

const myLambda = new lambda.Function(this, lambda-id, {
    code: code,
    handler: handler,
    runtime: runtime,
    ...
    **vpc**: 
})

我想我需要将 VPC 作为参数传递给这个函数。有什么方法可以通过其 id 获取此 VPC,然后将其作为参数传递给此函数吗?

amazon-web-services aws-lambda amazon-vpc aws-cdk
2个回答
1
投票

您可以通过 ID 导入现有 VPC 并将其作为 lambda 上的属性提供,例如:

const vpc = ec2.Vpc.fromLookup(this, 'VPC', {
  vpcId: 'your vpc id'
})

const myLambda = new lambda.Function(this, 'your-lambda', {
  code,
  handler,
  runtime,
  ...,
  vpc
})

0
投票

从“aws-cdk-lib”导入*作为cdk; 进口 { aws_lambda 作为 lambda, aws_events 作为事件, aws_events_targets 作为目标, aws_ec2 作为 ec2, aws_iam 作为 iam, aws_lex 作为 lex, aws_logs 作为日志, aws_ssm 作为 ssm, aws_s3 作为 s3, aws_logs_destinations 作为logs_destinations, 自定义资源为 cr, 来自“aws-cdk-lib”; 从“构造”导入{构造};

//#region Get Existing VPC and Subnets
const vpc = ec2.Vpc.fromLookup(this, "VPC", {
  vpcId: process.env.VPC_ID!,
});

// Subnets (private subnets linked with the VPC)
const subnetsArray = process.env.SUBNET_IDS!.split(",");
const privateSubnets = subnetsArray.map((subnetId) =>
  ec2.Subnet.fromSubnetId(this, `subnet-${subnetId}`, subnetId)
);
const yourLambda = new lambda.Function(
  this,
  "Unique Stack Id",
  {
    functionName: "your lambda function anme",
    .
    .
    .
    // Add any other parameters u want.
    vpc: vpc,
    vpcSubnets: { subnets: privateSubnets },
    role: stackIAMRole,
  },
);
© www.soinside.com 2019 - 2024. All rights reserved.