Move lambda to a new vpc in stack update

Viewed 334

I have a stack that I can make multiple copies of by using an identifier and a second one that interfaces with it by a lambda if that is given an identifier.

If I attempt to update the interfacing stack to a new identifier which would involve the lambda moving to a new VPC, subnet and security group it fails. Deleting the stack and redeploying works fine however, so I know the code is doing what it is meant to on a fresh deploy.

const appVpc = Vpc.fromVpcAttributes(this, "appVpc", {
      vpcId: StringParameter.valueForStringParameter(
        this,
        `/${props.productionVPCName}/vpc-id`,
      ),
      availabilityZones: [`${cdk.Aws.REGION}a`, `${cdk.Aws.REGION}b`],
    });
    
const dmzA = Subnet.fromSubnetAttributes(this, "dmza", {
      subnetId: StringParameter.valueForStringParameter(
        this,
        `/${props.productionVPCName}/dmz-subnet-A`,
      ),
      availabilityZone: `${cdk.Aws.REGION}a`,
    });
    
const dmzB = Subnet.fromSubnetAttributes(this, "dmzb", {
      subnetId: StringParameter.valueForStringParameter(
        this,
        `/${props.productionVPCName}/dmz-subnet-B`,
      ),
      availabilityZone: `${cdk.Aws.REGION}b`,
    });
    
const lambdaSecurityGroup = SecurityGroup.fromSecurityGroupId(
      this,
      "lambdaSecurityGroupsID",
      StringParameter.fromStringParameterName(
        this,
        "secGroupParam",
        `/${props.productionVPCName}/Mattermost-Security-Group`,
      ).stringValue,
    );
    
const Lambda = new Function(this, "Lambda", {
      description:
        "A Lambda Function",
      functionName: `function-${props.productionVPCName}`,
      runtime: Runtime.NODEJS_12_X,
      environment: {},
      handler: "main.handler",
      code: Code.fromAsset("dist/"),
      events: [new SnsEventSource(MessagingTopic)],
      role: LambdaRole,
      vpc: appVpc,
      vpcSubnets: {
        subnets: [dmzA, dmzB],
      },
      securityGroups: [lambdaSecurityGroup],
      tracing: Tracing.ACTIVE,
      timeout: Duration.seconds(20),
    });

When props.productionVPCName is changed the error i'm getting is

Subnets and Security Groups must belong to the same VPC. (Service: AWSLambdaInternal; Status Code: 400; Error Code: InvalidParameterValueException; Request ID:12345-6789...; Proxy: null)

I have tried to add a dependency on the lambda for the vpc, subnets, and security groups as I thought it could be a race condition but this did not solve the problem.

0 Answers
Related