Skip to content

Commit c5175f1

Browse files
committed
unused aws instace and vpcs cleanup
Signed-off-by: shiva kumar <[email protected]>
1 parent d3280cd commit c5175f1

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

.github/workflows/awscleanup.yaml

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
name: Daily AWS Cleanup Bot
2+
3+
# on:
4+
# schedule:
5+
# - cron: '0 8 * * *'
6+
7+
on:
8+
pull_request:
9+
types:
10+
- opened
11+
- synchronize
12+
branches:
13+
- awsresourcecleanup
14+
push:
15+
branches:
16+
- awsresourcecleanup
17+
18+
jobs:
19+
cleanup:
20+
runs-on: linux-amd64-cpu4
21+
22+
steps:
23+
- name: Checkout repository
24+
uses: actions/checkout@v4
25+
26+
- name: Set up AWS CLI
27+
uses: aws-actions/configure-aws-credentials@v4
28+
with:
29+
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
30+
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
31+
aws-region: us-west-1
32+
33+
- name: Identify resources running longer than 4 hours
34+
id: identify-resources
35+
run: |
36+
# Find EC2 instances with names ci* running longer than 4 hours
37+
running_instances=$(aws ec2 describe-instances \
38+
--filters Name=instance-state-name,Values=running Name=tag:Name,Values=ci* \
39+
--query "Reservations[*].Instances[?LaunchTime<=\`$(date -u -d '4 hours ago' +%Y-%m-%dT%H:%M:%SZ)\`].InstanceId" \
40+
--output text | tr -d '\r' | tr '\n' ' ')
41+
echo "Found instances: $running_instances"
42+
echo "instances=$running_instances" >> $GITHUB_ENV
43+
44+
# Find vpcs with names ci*
45+
# vpc does not have creation/launch time,try to delete all vpcs
46+
# if there is any resource dependency it will not be deleted and only gives warning
47+
vpcs=$(aws ec2 describe-vpcs \
48+
--filters "Name=tag:Name,Values=ci*" \
49+
--query "Vpcs[].VpcId" \
50+
--output text | tr -d '\r' | tr '\n' ' ')
51+
52+
echo "Found VPCs: $vpcs"
53+
echo "vpcs=$vpcs" >> $GITHUB_ENV
54+
55+
- name: Terminate EC2 Instances
56+
if: env.instances != ''
57+
run: |
58+
for instance in $instances; do
59+
echo "Terminating instance: $instance"
60+
aws ec2 terminate-instances --instance-ids "$instance"
61+
done
62+
63+
- name: Clean up VPCs
64+
if: env.vpcs != ''
65+
run: |
66+
for vpc in $vpcs; do
67+
attempts=0
68+
# try 3 times with 5 minutes interval
69+
while [ $attempts -lt 3 ]; do
70+
echo "Attempting to delete VPC: $vpc (Attempt $((attempts+1)))"
71+
if aws ec2 delete-vpc --vpc-id "$vpc"; then
72+
echo "Successfully deleted VPC: $vpc"
73+
break
74+
else
75+
attempts=$((attempts + 1))
76+
if [ $attempts -lt 3 ]; then
77+
echo "Failed to delete VPC: $vpc. Retrying in 5 minutes..."
78+
sleep 300
79+
fi
80+
fi
81+
done
82+
83+
if [ $attempts -eq 3 ]; then
84+
echo "Failed to delete VPC: $vpc after 3 attempts. Skipping."
85+
fi
86+
done
87+
88+
- name: Post cleanup
89+
run: |
90+
echo "Cleanup completed."

0 commit comments

Comments
 (0)