unused aws instace and vpcs cleanup #9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Daily AWS Cleanup Bot | |
# on: | |
# schedule: | |
# - cron: '0 8 * * *' | |
on: | |
pull_request: | |
types: | |
- opened | |
- synchronize | |
branches: | |
- awsresourcecleanup | |
push: | |
branches: | |
- awsresourcecleanup | |
jobs: | |
cleanup: | |
runs-on: linux-amd64-cpu4 | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v4 | |
- name: Set up AWS CLI | |
uses: aws-actions/configure-aws-credentials@v4 | |
with: | |
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} | |
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} | |
aws-region: us-west-1 | |
- name: Identify resources running longer than 4 hours | |
id: identify-resources | |
run: | | |
# Find EC2 instances with names ci* running longer than 4 hours | |
running_instances=$(aws ec2 describe-instances \ | |
--filters Name=instance-state-name,Values=running Name=tag:Name,Values=ci* \ | |
--query "Reservations[*].Instances[?LaunchTime<=\`$(date -u -d '4 hours ago' +%Y-%m-%dT%H:%M:%SZ)\`].InstanceId" \ | |
--output text | tr -d '\r' | tr '\n' ' ') | |
echo "Found instances: $running_instances" | |
echo "instances=$running_instances" >> $GITHUB_ENV | |
# Find vpcs with names ci* | |
# vpc does not have creation/launch time,try to delete all vpcs | |
# if there is any resource dependency it will not be deleted and only gives warning | |
vpcs=$(aws ec2 describe-vpcs \ | |
--filters "Name=tag:Name,Values=ci*" \ | |
--query "Vpcs[].VpcId" \ | |
--output text | tr -d '\r' | tr '\n' ' ') | |
echo "Found VPCs: $vpcs" | |
echo "vpcs=$vpcs" >> $GITHUB_ENV | |
- name: Terminate EC2 Instances | |
if: env.instances != '' | |
run: | | |
for instance in $instances; do | |
echo "Terminating instance: $instance" | |
aws ec2 terminate-instances --instance-ids "$instance" | |
done | |
- name: Clean up VPCs | |
if: env.vpcs != '' | |
run: | | |
for vpc in $vpcs; do | |
attempts=0 | |
# try 3 times with 5 minutes interval | |
while [ $attempts -lt 3 ]; do | |
echo "Attempting to delete VPC: $vpc (Attempt $((attempts+1)))" | |
if aws ec2 delete-vpc --vpc-id "$vpc"; then | |
echo "Successfully deleted VPC: $vpc" | |
break | |
else | |
attempts=$((attempts + 1)) | |
if [ $attempts -lt 3 ]; then | |
echo "Failed to delete VPC: $vpc. Retrying in 5 minutes..." | |
sleep 300 | |
fi | |
fi | |
done | |
if [ $attempts -eq 3 ]; then | |
echo "Failed to delete VPC: $vpc after 3 attempts. Skipping." | |
fi | |
done | |
- name: Post cleanup | |
run: | | |
echo "Cleanup completed." |