-
Notifications
You must be signed in to change notification settings - Fork 0
/
do-float-ip
executable file
·50 lines (41 loc) · 1.28 KB
/
do-float-ip
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
#!/bin/bash
set -euo pipefail
DO_API="https://api.digitalocean.com"
DO_TOKEN=
CURL="curl -LSsf"
DROPLET_ID=$($CURL "http://169.254.169.254/metadata/v1/id")
REGION=$($CURL "http://169.254.169.254/metadata/v1/region")
fatal() {
echo "Fatal: $@" >&2
exit 1
}
ocean() {
local action=$1
local path=$2
shift 2
args=$(echo "$@" | sed 's/\([^ ][^=]*\)=\([^ ]*\)/"\1": "\2",/g;s/,$//')
$CURL -X "$action" "$DO_API/$path" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $DO_TOKEN" \
-d "{ $args }" 2>&1 # If curl suceeds, output is only stdout. If fails, only stderr
}
main() {
[[ "$#" -lt 1 ]] && fatal "$0 floating-ip-or-name"
local ip=$1
DO_TOKEN=$(cat /secret/do.token 2>/dev/null) \
|| fatal "/secret/do.token missing or unreadable"
if [[ ! "$ip" =~ "^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$" ]]; then
ip="$(getent hosts "$ip" | sed 's/ .*$//')"
fi
while true; do
local assigned_to=$(ocean GET "v2/floating_ips/$ip" | jq -r .floating_ip.droplet.id)
if [[ "$assigned_to" != "$DROPLET_ID" ]]; then
echo "$ip assigned to $assigned_to, reassigning"
ocean POST v2/floating_ips/$ip/actions \
type=assign "droplet_id=$DROPLET_ID" \
|| fatal "Couldn't assign floating ip to myself"
fi
sleep 600
done
}
main "$@"