This project aims to optimize cloud costs by identifying and deleting stale resources such as unused EBS snapshots. We'll use AWS Lambda, and CloudWatch to automate this process.
Cloud cost optimization is crucial to avoid unnecessary expenses. This project automates the identification and deletion of unused resources to reduce costs efficiently.
-
EC2 Instance and Snapshot:
- Creating an EC2 instance automatically creates a volume. If a snapshot of this volume is created and the EC2 instance is later deleted, the snapshot remains, incurring costs.
-
Forgotten S3 Buckets:
- An S3 bucket created for temporary use might be forgotten, leading to ongoing storage costs.
- Notifications: Use AWS SNS to notify users about unused resources.
- Automated Deletion: Use AWS Lambda to automatically delete stale resources.
In this project, we use 2 approaches to manage cloud costs:
- Sign in to the AWS Management Console.
- Navigate to the EC2 Dashboard.
- Click Launch Instance.
- Select an Amazon Machine Image (AMI) (e.g., Amazon Linux 2).
- Choose an Instance Type (e.g., t2.micro).
- Configure the Instance Details (default settings are usually sufficient).
- Add Storage (default settings create a root volume).
- Add Tags (optional).
- Configure Security Group:
- Add rules to allow SSH access (port 22).
- Review and Launch the instance.
- Select or create a key pair for SSH access and click Launch Instances.
- Navigate to the EC2 Dashboard.
- In the left-hand menu, click on Volumes under Elastic Block Store.
- Select the volume attached to your EC2 instance.
- Click Actions and choose Create Snapshot.
- Provide a Description (optional) and click Create Snapshot.
- Go to the AWS Lambda Console.
- Click Create function.
- Choose Author from scratch.
- Enter a Function name and choose a Runtime (e.g., Python 3.8).
- Click Create function.
- In the function code editor, replace the default code with the following:
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
# Get all EBS snapshots
response = ec2.describe_snapshots(OwnerIds=['self'])
# Get all active EC2 instance IDs
instances_response = ec2.describe_instances(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
active_instance_ids = set()
for reservation in instances_response['Reservations']:
for instance in reservation['Instances']:
active_instance_ids.add(instance['InstanceId'])
# Iterate through each snapshot and delete if it's not attached to any volume or the volume is not attached to a running instance
for snapshot in response['Snapshots']:
snapshot_id = snapshot['SnapshotId']
volume_id = snapshot.get('VolumeId')
if not volume_id:
# Delete the snapshot if it's not attached to any volume
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was not attached to any volume.")
else:
# Check if the volume still exists
try:
volume_response = ec2.describe_volumes(VolumeIds=[volume_id])
if not volume_response['Volumes'][0]['Attachments']:
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as it was taken from a volume not attached to any running instance.")
except ec2.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidVolume.NotFound':
# The volume associated with the snapshot is not found (it might have been deleted)
ec2.delete_snapshot(SnapshotId=snapshot_id)
print(f"Deleted EBS snapshot {snapshot_id} as its associated volume was not found.")- Click Deploy to save the function.
- Go to the Lambda function's Configuration tab.
- Under Execution role, click on the role name to open the IAM console.
- In the IAM role, click Add permissions and choose Attach policies.
- Search for and select the AmazonEC2FullAccess policy.
- Click Attach policy.
- Go back to the Lambda function.
- Click Test and configure a new test event (you can use the default settings).
- Click Create and then Test to execute the function.
- If the function fails due to a timeout, go to the Configuration tab and increase the timeout to 10 seconds.
- Ensure the function has the necessary permissions to delete snapshots and describe volumes.
- Go to the CloudWatch Console.
- In the left-hand menu, click on Rules under Events.
- Click Create rule.
- In the Event Source section, choose Event Source as Schedule and set the frequency (e.g., daily).
- In the Targets section, click Add target and select Lambda function.
- Choose the Lambda function you created.
- Click Configure details, provide a name and description, and click Create rule.
By following these steps, you can efficiently manage cloud costs by identifying and deleting stale resources using AWS Lambda, and CloudWatch. This automated approach ensures you only pay for the resources you actively use.