Releasing Idle Elastic IPs on AWS to Save Costs

axeldlv

Axel

Posted on November 14, 2024

Releasing Idle Elastic IPs on AWS to Save Costs

To automatically disable or shut down idle IPs on AWS, you can use AWS Lambda and Amazon EventBridge in combination. Here’s a guide on how to set up a solution that will periodically check for idle Elastic IPs and release them if they’re not in use.

Step 1: Define "Idle" IP Criteria

Define what "idle" means for your IPs. Typically, an Elastic IP (EIP) is considered "idle" if it's not associated with an active EC2 instance. AWS charges for idle EIPs, so releasing these IPs can save costs.

Step 2: Create an AWS Lambda Function

AWS Lambda will check for idle IPs and release them if they meet your criteria.

  1. Go to the AWS Lambda console.
  2. Create a new Lambda function:

    • Name: release-idle-eip
    • Runtime: Python 3.x
  3. Add the following code to the Lambda function:

    import boto3
    
    def lambda_handler(event, context):
        ec2 = boto3.client('ec2')
        # Retrieves all Elastic IPs
        addresses = ec2.describe_addresses()
    
        for address in addresses['Addresses']:
            # Check if the EIP is not associated with any instance or network interface
            if 'InstanceId' not in address and 'NetworkInterfaceId' not in address:
                try:
                    # Release the idle EIP
                    ec2.release_address(AllocationId=address['AllocationId'])
                    print(f"Released idle Elastic IP: {address['PublicIp']}")
                except Exception as e:
                    print(f"Failed to release Elastic IP {address['PublicIp']}: {e}")
    
        return {
            'statusCode': 200,
            'body': 'Idle Elastic IPs released if found.'
        }
    
    
  4. Save the function.

Step 3: Set Up Permissions

To add custom permissions (like ec2:DescribeAddresses and ec2:ReleaseAddress) to your Lambda execution role, follow these steps:

Find or Create the Lambda Execution Role

  1. Go to the IAM Console in AWS.
  2. In the left menu, select Roles.
  3. Find the existing Lambda execution role (e.g. release-idle-eip-role-49zlj0sl).

Add a Custom Inline Policy to the Role

  1. Select the role name (release-idle-eip-role-49zlj0sl) to open its details page.
  2. On the role’s details page, go to the Permissions tab.
  3. Click Add permissions, and then select Create inline policy.

Add EC2 Permissions in the Policy Editor

  1. In the Create policy editor, switch to the JSON tab.
  2. Delete any default text in the editor and paste the following JSON policy, which includes permissions for DescribeAddresses and ReleaseAddress:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "ec2:DescribeAddresses",
            "ec2:ReleaseAddress"
          ],
          "Resource": "*"
        }
      ]
    }
    
    
  3. Click Review policy.

Name and Save the Inline Policy

  1. Give the policy a name, such as EC2DescribeAndRelease.
  2. Click Create policy to save it.

Verify Permissions

Once saved, the policy will be attached to your Lambda execution role. The Lambda function now has permission to:

  • List all Elastic IP addresses (DescribeAddresses).
  • Release any Elastic IP address (ReleaseAddress).

With these permissions, your Lambda function should now be able to detect and release idle Elastic IPs automatically.

Step 4: Schedule the Lambda Function with Amazon EventBridge (CloudWatch Events)

To run the Lambda function on a schedule, use Amazon EventBridge.

  1. Go to the Amazon EventBridge console.
  2. In the left menu, Select Schedules.
  3. Choose Create schedule.
  4. Add a schedule name and choose Recurring schedule
  5. To schedule each hour you can add a cron like 0 * ? * * * and choose "Off" for the Flexible time window.
  6. Select the Lambda function and select your lambda function release-idle-eip.
  7. Save the schedule.

Step 5: Testing and Monitoring

  • Test the Lambda function to make sure it releases idle IPs as expected.
  • Monitor CloudWatch logs to confirm that the function runs without issues and successfully releases idle IPs.

Additional Tips

  • Tagging and Filtering: If you have some EIPs that you want to keep idle, use tags to filter them out in your Lambda function.
  • Notification: Consider setting up an SNS topic to notify you whenever an idle IP is released.
💖 💪 🙅 🚩
axeldlv
Axel

Posted on November 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related