Created
September 28, 2017 03:40
-
-
Save eqyiel/984fb55078fefae726afbb0374c13276 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# http://docs.aws.amazon.com/cli/latest/reference/ec2/authorize-security-group-ingress.html | |
# http://docs.aws.amazon.com/cli/latest/reference/ec2/revoke-security-group-ingress.html | |
set -euo pipefail | |
fatal() { | |
echo '** ERROR:' "$@" >&2 | |
exit 1 | |
} | |
if [ "${#}" -lt 1 ]; then | |
fatal "missing arguments." | |
fi | |
CMD="${1}"; shift | |
authorize_security_group_ingress() { | |
aws \ | |
--region="${AWS_REGION}" \ | |
ec2 \ | |
authorize-security-group-ingress \ | |
--group-id "${INGRESS_EC2_SECURITY_GROUP_ID}" \ | |
--protocol tcp \ | |
--port "${INGRESS_PORT}" \ | |
--cidr "${IP_ADDRESS}/32" \ | |
> /dev/null 2>&1 # redirect stdout to /dev/null but keep stderr | |
} | |
revoke_security_group_ingress() { | |
aws \ | |
--region="${AWS_REGION}" \ | |
ec2 \ | |
revoke-security-group-ingress \ | |
--group-id "${INGRESS_EC2_SECURITY_GROUP_ID}" \ | |
--protocol tcp \ | |
--port "${INGRESS_PORT}" \ | |
--cidr "${IP_ADDRESS}/32" \ | |
> /dev/null 2>&1 # redirect stdout to /dev/null but keep stderr | |
} | |
trap 'revoke_security_group_ingress' EXIT | |
echo "Getting container/machine IP address..." | |
IP_ADDRESS="$(curl -s icanhazip.com)" | |
if [ -z "${IP_ADDRESS}" ]; then | |
IP_ADDRESS="$(curl -s ifconfig.me)" | |
if [ -z "${IP_ADDRESS}" ]; then | |
fatal "Failed to get public IP address." | |
fi | |
else | |
echo "Got IP address of ${IP_ADDRESS}" | |
fi | |
echo "Opening port ${INGRESS_PORT} on security group ${INGRESS_EC2_SECURITY_GROUP_ID} for ${IP_ADDRESS}" | |
authorize_security_group_ingress | |
"${CMD}" "$@" | |
echo "Closing port ${INGRESS_PORT} on security group ${INGRESS_EC2_SECURITY_GROUP_ID} for ${IP_ADDRESS}" | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment