-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
teleport-lock
executable file
·38 lines (32 loc) · 1.41 KB
/
teleport-lock
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
#!/bin/bash
# Locking service makes sure that there is only one auth server performing certain action,
# for example renewing or getting letsencrypt certificates
set -e
if [[ "${DEBUG:-false}" == "true" ]]; then
set -x
fi
# Source variables from user-data
. /etc/teleport.d/conf
if [ ! -f /etc/teleport.d/role.auth ]; then
echo "Not running 'auth' role, exiting with success"
exit 0
fi
IMDS_TOKEN=$(curl -sS -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
NOW=$(date +%s)
TTL=$((NOW+3660))
PROCESS=$(curl -sS -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" http://169.254.169.254/latest/meta-data/local-hostname)
echo Locking $PROCESS for $TTL.
# Either renew the lease if agent still holds it, or grab the lease if it's expired
aws dynamodb put-item \
--region ${EC2_REGION} \
--table-name ${TELEPORT_LOCKS_TABLE_NAME} \
--item "{\"Lock\": {\"S\": \"/auth/servers\"}, \"Expires\": {\"S\": \"$TTL\"}, \"Process\": {\"S\": \"$PROCESS\"}}" \
--condition-expression="(attribute_not_exists(Expires) OR Expires <= :timestamp) OR Process = :process"\
--expression-attribute-values "{\":timestamp\":{\"S\":\"$NOW\"}, \":process\":{\"S\":\"$PROCESS\"}}"
# shellcheck disable=SC2181
if [ $? -eq 0 ]; then
echo "Renewed or locked the lease for $PROCESS until $(date -d @$TTL)"
else
echo "Could not get renew lease, locked by other process"
exit 255
fi