A.I, Data and Software Engineering

Automate Nat gateway deletion with lambda


Since NAT gateway is not cheap, in some cases, we don’t need to keep NAT Gateway running all the time. It is a good practice to automate the removal of the NAT gateway after finishing your task. This article will show how to implement a lambda function to remove the NAT gateway and associated Elastic IPs.

What is aws lambda

AWS Lambda is a AWS serverless compute service. It lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes. With Lambda, you can run code for virtually any type of application or backend service – all with zero administration.

You can set up your code to automatically trigger from over 200 AWS services and SaaS applications. You can write Lambda functions in your favourite language (Node.js, Python, Go, Java, and more). Also, you can use serverless and container tools, such as Docker CLI, to build, test, and deploy your functions.

What is a NAT Gateway

A NAT gateway is a Network Address Translation (NAT) service. You can use a NAT gateway so that instances in a private subnet can connect to services outside your VPC but external services cannot initiate a connection with those instances.

Access the internet from a private subnet

If you choose to create a NAT gateway in your VPC, you are charged for each “NAT Gateway-hour” that your gateway is provisioned and available. Data processing charges apply for each gigabyte processed through the NAT gateway regardless of the traffic’s source or destination. Each partial NAT Gateway-hour consumed is billed as a full hour. You also incur standard AWS data transfer charges for all data transferred via the NAT gateway.

If you no longer wish to be charged for a NAT gateway, simply delete your NAT gateway using the AWS Management Console, command-line interface, or API.

Automate the deletion with an event

We will create a lambda function that deletes all NATs in the current region and associated elastic IPs (EIPs). Next, follow these steps:

  • All Nat to be deleted must have a tag which has a value of “temp”. The lambda function will fillter all NATs with the correct tag to delete.
  • The first step is to create a lambda function using python programming language
  • Set the time out to at least 60 seconds for lambda. As the removal of each NAT and EIP will take some time.
  • Copy and paste the following code to your newly created lambda function.
import json, boto3
import time
import threading

def lambda_handler(event, context):
    """This function will delete all NAT GWs
        Requirements: Lambda timeout 60+ secs
        NAT GW must have a tag with value contain temp
    client = boto3.client("ec2")
    response = client.describe_nat_gateways()

    #Filter NAT Instance with tag= temp to delete
    natIDs = {nat['NatGatewayId']: nat["NatGatewayAddresses"][0]["AllocationId"] 
        for nat in response['NatGateways'] 
        for tag in nat['Tags'] 
        if 'temp' in tag.values() and 'available' == nat['State']}
    thrs = []
    for nat, eip in natIDs.items():
            th = threading.Thread(target=releaseEIP,args=(client, eip))
            print('There is a problem.')
    for th in thrs:
    return {
        'statusCode': 200,
        'body': json.dumps('All Temp NAT GW Deleted')

def releaseEIP(client, eip):
        print('There is a problem.')
  • Make sure you test the function before using it
  • If the function runs without any issue, you can trigger the lamdba with any event as needed.

Add comment


A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.