Skip to content

Instantly share code, notes, and snippets.

@urjitbhatia
Last active February 7, 2020 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urjitbhatia/2d79d14526bc6a32ad01fcaaad4249b0 to your computer and use it in GitHub Desktop.
Save urjitbhatia/2d79d14526bc6a32ad01fcaaad4249b0 to your computer and use it in GitHub Desktop.
Consul Lock/Unlock with timeout
#!/bin/bash
set -e
export CONSUL_HTTP_ADDR="https://my-consul-address"
VALUE=$(consul kv get <key>)
if [ "$VALUE" != "locked" ]; then
# Unlocked, check the timeout
TIMEOUT=$(echo $VALUE | jq 'reduce .[] as $num (0; .+$num)')
if [ $TIMEOUT -lt $(date +%Y%m%d%M) ]; then
echo "Timeout has expired. Locking security group"
aws ec2 revoke-security-group-ingress --protocol tcp --port 443 --group-id <my-security-group> --cidr 0.0.0.0/0
consul kv put <key> "locked"
echo "Locked"
else
echo "Timeout still pending. Keeping it unlocked"
exit 0
fi
fi
# Assert lock - this will fail with non-0 code if 443 is still found in the ingress permissions list
if aws ec2 describe-security-groups --group-id <my-security-group> \
| jq -e '.SecurityGroups[0].IpPermissions[] | select(.FromPort==443)'; then
echo "The security group is still unlocked! Unable to lock somehow. Failing..."
exit 1
else
echo "The security group is locked"
fi
#!/bin/bash
set -e
export CONSUL_HTTP_ADDR="https://my-consul-addr"
# put current timestamp (in minutes granularity)
consul kv put <key> "{\"current\":$(date +"%Y%m%d%M"), \"timeout\":$LockTimeoutMinutes}"
aws ec2 authorize-security-group-ingress --protocol tcp --port 443 --group-id <my-security-group> --cidr 0.0.0.0/0
echo "Will auto-lock in $LockTimeoutMinutes minutes"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment