aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code
https://aws.amazon.com/cdk
Apache License 2.0
11.54k stars 3.86k forks source link

Lambda stack with imported vpc fails to delete #6701

Open claabs opened 4 years ago

claabs commented 4 years ago

Deleting a Cloudformation stack containing a VPC Lambda will fail with a dependency error on each Lambda's security group.

This is similar to this issue: https://aws.amazon.com/blogs/compute/update-issue-affecting-hashicorp-terraform-resource-deletions-after-the-vpc-improvements-to-aws-lambda/

Reproduction Steps

Error Log

resource sg-<id> has a dependent object (Service: AmazonEC2; Status Code: 400; Error Code: DependencyViolation; ...)

Environment

Other

I was able to solve this using the recommended solution in the AWS blog post. The fix for CDK was tricky, so here's my solution:

const fixVpcDeletion = (handler: lambda.IFunction): void => {
  handler.connections.securityGroups.forEach(sg => {
    if (handler.role) {
      handler.role.node.children.forEach(child => {
        if (
          child.node.defaultChild &&
          (child.node.defaultChild as iam.CfnPolicy).cfnResourceType === 'AWS::IAM::Policy'
        ) {
          sg.node.addDependency(child);
        }
      });
    }
  });
};

fixVpcDeletion(getHandler);

Edit: updated the function since instanceof didn't always seem to work.


This is :bug: Bug Report

nija-at commented 4 years ago

Thanks for reporting this @charlocharlie and providing a potential solution.

gigi888 commented 4 years ago

what is the equivalent cloudformation template change to get around this? I have been banging my head against wall for this :(

rmill040 commented 2 years ago

Is there any update on this issue? I tried the CDK fix with the fixVpcDeletion defined above, but still get the dependent error on the SG as described above

moltar commented 1 year ago

Another useful tidbit, add the following at the top of the function, if you are applying this en masse to your functions:

  // Only VPC-associated Lambda Functions have security groups to manage.
  if (!handler.isBoundToVpc) {
    return
  }