This repository has been archived by the owner on Apr 2, 2021. It is now read-only.
/
cleanup-vpc.sh
executable file
·98 lines (87 loc) · 2.5 KB
/
cleanup-vpc.sh
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
96
97
98
#!/bin/bash
#
# Remove leftover cloud resources from an AWS VPC.
#
function usage() {
{
echo "Usage $0 <vpc-id> <cluster-name>"
echo "You can also set the environment variables"
echo "VPC_ID and CLUSTER_NAME."
} >&2
exit 1
}
function check_prg() {
$1 --version || {
{
echo "Can't find $prg."
} >&2
exit 2
}
}
if [[ "$1" != "" ]]; then
VPC_ID="$1"
fi
if [[ -z "$VPC_ID" ]]; then
usage
fi
shift
if [[ "$1" != "" ]]; then
CLUSTER_NAME="$1"
fi
if [[ -z "$CLUSTER_NAME" ]]; then
usage
fi
shift
if [[ -n "$1" ]]; then
usage
fi
check_prg aws
check_prg jq
# Delete instances in VPC. Do this in a loop, since Milpa might be still
# creating new instances.
while true; do
instances=$(aws ec2 describe-instances | jq -r ".Reservations | .[] | .Instances | .[] | select(.State.Name!=\"shutting-down\") | select(.State.Name!=\"terminated\") | select(.VpcId==\"$VPC_ID\") | .InstanceId")
if [[ -n "$instances" ]]; then
echo "Terminating instances:"
echo "$instances"
aws ec2 terminate-instances --instance-ids $instances > /dev/null 2>&1
else
break
fi
done
# Delete LBs.
lbs=$(aws elb describe-load-balancers | jq -r ".LoadBalancerDescriptions | .[] | select(.VPCId==\"$VPC_ID\") | .LoadBalancerName")
if [[ -n "$lbs" ]]; then
echo "Removing LBs:"
echo "$lbs"
for lb in $lbs; do
aws elb delete-load-balancer --load-balancer-name $lb > /dev/null 2>&1
done
fi
v2lbs=$(aws elbv2 describe-load-balancers | jq -r ".LoadBalancers | .[] | select(.VpcId==\"$VPC_ID\") | .LoadBalancerArn")
if [[ -n "$v2lbs" ]]; then
echo "Removing v2 LBs:"
echo "$v2lbs"
for lb in $v2lbs; do
aws elbv2 delete-load-balancer --load-balancer-arn $lb > /dev/null 2>&1
done
fi
# Delete security groups in VPC.
sgs=$(aws ec2 describe-security-groups | jq -r ".SecurityGroups | .[] | select(.VpcId == \"$VPC_ID\") | .GroupId")
if [[ -n "$sgs" ]]; then
echo "Removing SGs:"
echo "$sgs"
for sg in $sgs; do
aws ec2 delete-security-group --group-id $sg > /dev/null 2>&1
done
fi
# Delete volumes created by this cluster.
vols=$(aws ec2 describe-volumes --filters "Name=tag:kubernetes.io/cluster/$CLUSTER_NAME,Values=owned" "Name=status,Values=creating,available" | jq -r ".Volumes | .[] | .VolumeId")
if [[ -n "$vols" ]]; then
echo "Removing volumes:"
echo "$vols"
for vol in $vols; do
aws ec2 delete-volume --volume-id $vol > /dev/null 2>&1
done
fi
exit 0