-
Notifications
You must be signed in to change notification settings - Fork 6
95 lines (83 loc) · 3.11 KB
/
awscleanup.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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*
vpcs=$(aws ec2 describe-vpcs \
--filters "Name=tag:Name,Values=ci*" \
--query "Vpcs[].VpcId" \
--output text | tr -d '\r' | tr '\n' ' ')
# Check if the VPC has a main route table
old_vpcs=""
for vpc in $vpcs; do
main_route_table=$(aws ec2 describe-route-tables \
--filters Name=vpc-id,Values=$vpc \
--query "RouteTables[?Associations[?Main==true]].RouteTableId" \
--output text)
if [ -n "$main_route_table" ]; then
echo "VPC: $vpc is associated with a main route table ($main_route_table). Skipping."
continue
fi
echo "VPC: $vpc is valid for processing."
old_vpcs="$old_vpcs $vpc"
done
echo "Old VPCs: $old_vpcs"
echo "vpcs=$old_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
# Check for EC2 instances attached to VPC
instances_in_vpc=$(aws ec2 describe-instances \
--filters "Name=vpc-id,Values=$vpc" \
--query "Reservations[*].Instances[*].InstanceId" \
--output text)
# if no instance attached delete it
if [ -z "$instances_in_vpc" ]; then
scripts/awsvpcscleanup.sh $vpc
else
echo "EC2 instances are still attached to VPC: $vpc. Skipping deletion."
fi
done
- name: Post cleanup
run: |
echo "Cleanup completed."