Skip to content

Commit

Permalink
Add provisioner to cleanup any available attached ENIs during subnet …
Browse files Browse the repository at this point in the history
…destroy (#336)

This is a workaround for the known VPC CNI addon's "leaked ENIs" issue:
See aws/amazon-vpc-cni-k8s#608

Co-authored-by: Rafael Mendes Pereira <[email protected]>
  • Loading branch information
rafael-mendes-pereira and Rafael Mendes Pereira committed Nov 14, 2024
1 parent 101212f commit e8eb223
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions modules/terraform/aws/virtual-network/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,32 @@ resource "aws_subnet" "subnets" {

# Ensure all secondary CIDR blocks are created before subnets in secondary CIDR blocks are created
depends_on = [aws_vpc_ipv4_cidr_block_association.secondary_ipv4_cidr_block]

provisioner "local-exec" {
/*
This command cleans up any not in use ENIs attached to this subnet, which were created outside the scope of the Terraform modules.
This is a workaround for the known VPC CNI addon's "leaked ENIs" issue: See https://github.com/aws/amazon-vpc-cni-k8s/issues/608
*/
when = destroy
command = <<-EOT
echo "Detaching Subnet: ${self.id} Network Interfaces"
# Get available (not in use) ENIs attached to this subnet
network_interfaces_attachment_ids=$(aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=${self.id} --query "NetworkInterfaces[?Status=='available' && Attachment.AttachIndex != '0'].Attachment.AttachmentId" --output text)
for network_interface_attachment_id in $network_interfaces_attachment_ids; do
echo "Detaching available Network Interface attachment id: $network_interface_attachment_id"
if ! aws ec2 detach-network-interface --attachment-id $network_interface_attachment_id; then
echo "##[warning] Failed to detach Network Interface attachment id: $network_interface_attachment_id"
fi
done
network_interfaces=$(aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=${self.id} --query "NetworkInterfaces[?Status=='available' && Attachment.AttachIndex != '0'].NetworkInterfaceId" --output text)
for network_interface in $network_interfaces; do
echo "Deleting available Network Interface: $network_interface"
if ! aws ec2 delete-network-interface --network-interface-id $network_interface; then
echo "##[warning] Failed to delete Network Interface: $network_interface"
fi
done
EOT
}
}

resource "aws_eip" "eips" {
Expand Down

0 comments on commit e8eb223

Please sign in to comment.