Wednesday, July 05, 2017

CloudFormation Won't Delete Lambda

I am noticing that AWS CloudFormation has difficulties deleting my particular Lambda function.

If you are having this problem the trick is to use the CLI to first forcibly detach the ENI, then delete it.

In my case I created a generic script that parses a file for a value from a query using the AWS CLI. It's using some funky bash script so if you wanted you could re-write this in your favorite language that's more readable.

Also note I am still *testing* this code. Make sure it does not delete the wrong ENIs. There is no good way to get a handle on the ENI specific to a Lambda function either unfortunately.

filename=$1;key=$2; var=""
var="$(cat $filename | grep "\"$key\""  | cut -d ':' -f 2- | sed -e 's/^[ \t]*//' -e 's/"//' -e 's/"//' -e 's/,//')"
var="$(echo "${var}" | tr -d '[:space:]')"
echo "$var"

A series of commands use the above function to query for the Attachment ID and Network Interface ID. These two values are used to force detachment and delete the end. Use the name of the Lambda Function to find the correct ENI to delete which is at the end of the Requester ID field.

#get our lambda ENI as we need to force a detachment
aws ec2 describe-network-interfaces --filter Name="requester-id",Values="*ConfigureFirebox" > lambda-eni.txt  2>&1
attachmentid=$(./execute/ lambda-eni.txt "AttachmentId")
if [ "$attachmentid" != "" ]; then
    echo "aws ec2 detach-network-interface --attachment-id $attachmentid --force"
    aws ec2 detach-network-interface --attachment-id $attachmentid --force

    #I don't see a good way to wait for the network interface to detach.
    #Pausing a few here and hope that works.
    SLEEP 5

    networkinterfaceid=$(./execute/ lambda-eni.txt "NetworkInterfaceId")
    echo "aws ec2 delete-network-interface --network-interface-id $networkinterfaceid"
    output=$(aws ec2 delete-network-interface --network-interface-id $networkinterfaceid)
    if [ "$output" != "" ]; then
        echo "If an error occurs deleting the network interface run the script again. Contacting AWS for a better solution..."

This code lives in the following file:

Once the above code completes, the Lambda function can delete successfully.

The full code I am testing is found here: