Skip to content

Commit ac2b2ca

Browse files
committed
chore(ci): clean up stale ec2 instances
1 parent 438c36b commit ac2b2ca

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
name: Cleanup Stale EC2 Instances
2+
3+
on:
4+
schedule:
5+
# Run daily at 06:00 UTC
6+
- cron: "0 6 * * *"
7+
workflow_dispatch:
8+
9+
jobs:
10+
cleanup:
11+
name: Delete stale supadevci EC2 instances
12+
runs-on: ubuntu-latest
13+
strategy:
14+
matrix:
15+
region: [ap-southeast-1, us-east-1]
16+
17+
permissions:
18+
id-token: write
19+
contents: read
20+
21+
steps:
22+
- name: Configure AWS credentials
23+
uses: aws-actions/configure-aws-credentials@v4
24+
with:
25+
role-to-assume: ${{ secrets.SUPADEV_AWS_ROLE }}
26+
aws-region: ${{ matrix.region }}
27+
28+
- name: Find and terminate stale instances
29+
env:
30+
AWS_MAX_ATTEMPTS: 6
31+
run: |
32+
cutoff=$(date -u -d '24 hours ago' '+%Y-%m-%dT%H:%M:%SZ')
33+
34+
echo "Looking for running packer builder instances launched before ${cutoff}..."
35+
36+
instance_ids=$(aws ec2 describe-instances \
37+
--filters \
38+
"Name=tag:appType,Values=postgres" \
39+
"Name=tag:creator,Values=packer" \
40+
"Name=instance-state-name,Values=running" \
41+
--query "Reservations[].Instances[?LaunchTime<'${cutoff}'][].InstanceId" \
42+
--output text)
43+
44+
if [ -z "$instance_ids" ]; then
45+
echo "No stale instances found."
46+
exit 0
47+
fi
48+
49+
read -r -a instance_id_arr <<< "$instance_ids"
50+
echo "Terminating instances: ${instance_id_arr[*]}"
51+
aws ec2 terminate-instances --instance-ids "${instance_id_arr[@]}"
52+
echo "Done."

0 commit comments

Comments
 (0)