Skip to content

Instantly share code, notes, and snippets.

@rcbop
Created July 5, 2018 17:47
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 rcbop/633029a9e28d8f39498657ae9fb2e618 to your computer and use it in GitHub Desktop.
Save rcbop/633029a9e28d8f39498657ae9fb2e618 to your computer and use it in GitHub Desktop.
authorize ssh port 22 in aws ec2's security group before performing ansible deployment - requires jq, aws cli, ansible ec2.py dynamic inventory
#!/bin/bash
STEP=0
bump_step(){
STEP=$(($STEP+1))
log "${BLU}[INFO] ($STEP) $1${NC}"
}
log() { echo -e "${BWHT}["$(date "+%Y%m%d${NC}T${BWHT}%H%M%S")"]${NC} $*"; }
separator() { SEP=$(printf '%*s' 105 | tr ' ' '#') && log "${GRN}[INFO] $SEP${NC}"; }
info() { log "${GRN}[INFO] $1${NC}"; }
warning() { log "${YEL}[WARN] $1${NC}"; }
error() { log "${RED}[ERROR] $1${NC}"; }
fatal() { log "${MAG}[FATAL] $1${NC}"; exit 1 ; }
debug() { if [ "${DEBUG}" == "true" ]; then log "${CYN}[DEBUG] :: ${FUNCNAME[1]} :: $1 ${NC}"; fi }
json_escape () {
printf '%s' $1 | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}
multi_debug() {
if [ "${DEBUG}" == "true" ]; then
IFS=$'\n'
for line in $1
do
log "${CYN}[DEBUG] :: ${FUNCNAME[1]} :: $line${NC}"
done
fi
}
multi_info() {
IFS=$'\n'
for line in $1
do
log "${GRN}[INFO] :: $line${NC}"
done
}
is_no_colors(){
debug
[ ! -z "${NO_COLORS}" ] && [ "$NO_COLORS" == "true" ]
}
set_colors(){
debug
export RED="\033[0;31m" BLU="\033[0;34m" GRN="\033[0;32m" YEL="\033[33;m"
export CYN="\033[0;36m" MAG="\033[35m" BWHT="\033[1m" NC="\033[0m"
debug "Colors ON"
}
unset_colors(){
debug
export RED='' BLU='' YEL='' CYN='' GRN='' MAG=''
export NC='' BWHT=''
}
#!/bin/bash
#/ Description:
#/ opens ssh port in security group
#/ Usage:
#/
#/ --------------------------------------------------------------------------------
#/ Author: Rogério Peixoto (rcbpeixoto@gmail.com)
#/ --------------------------------------------------------------------------------
usage() { grep '^#/' "$0" | cut -c4- ; exit 0 ; }
expr "$*" : ".*--help" > /dev/null && usage
BASEDIR=$(dirname "$0")
# shellcheck source=./colors.sh
source "${BASEDIR}"/colors.sh
AWS_PROFILE=${AWS_PROFILE:-'admin'}
export AWS_KEY_ID=${AWS_KEY_ID:="$(aws configure get aws_access_key_id --profile "${AWS_PROFILE}")"}
export AWS_SECRET_KEY=${AWS_SECRET_KEY:="$(aws configure get aws_secret_access_key --profile "${AWS_PROFILE}")"}
EC2_INVENTORY_NAME_QUERY=${EC2_INVENTORY_NAME_QUERY:-"tag_Name_myproject"}
get_security_group_id(){
aws ec2 describe-instances \
--filters "Name=ip-address,Values=${EC2_IP}" \
--query 'Reservations[*][].Instances[*][].SecurityGroups[*].GroupId' --output text
}
get_ip_from_dynamic_inventory(){
./"${BASEDIR}"/ec2.py --list \
--profile "${AWS_PROFILE}" \
| jq -r "to_entries[] | select(.key | contains(\"${EC2_INVENTORY_NAME_QUERY}\")) | .value[]" \
| head -n1 \
| awk '{$1=$1;print}'
}
authorize_ssh(){
debug
info "Getting my ip..."
MYIP=$(dig +short myip.opendns.com @resolver1.opendns.com) || echo 'Error retrieving ip with dig'
[ -z "$MYIP" ] && MYIP=$(curl -s checkip.amazonaws.com | awk '{print $0}')
warning "found... ${MYIP}"
info "Getting ec2 ip..."
EC2_IP=$(get_ip_from_dynamic_inventory)
[ -z "$EC2_IP" ] && fatal "Unable to find ec2 ip"
warning "found... ${EC2_IP}"
info "Getting ec2 group id..."
SECURITY_GROUP_ID=$(get_security_group_id)
[ -z "$SECURITY_GROUP_ID" ] && fatal "Unable to find sec-group id"
warning "found... ${SECURITY_GROUP_ID}"
warning "Authorizing port 22 in group id ${SECURITY_GROUP_ID} for ip ${EC2_IP}"
aws ec2 authorize-security-group-ingress \
--protocol tcp --port 22 \
--cidr "$MYIP/32" \
--group-id "${SECURITY_GROUP_ID}" \
--profile "${AWS_PROFILE}"
}
deny_ssh(){
debug
aws ec2 revoke-security-group-ingress \
--protocol tcp --port 22 \
--cidr "$MYIP/32" \
--group-id "${SECURITY_GROUP_ID}" \
--profile "${AWS_PROFILE}"
}
# should close port after?
SHOULD_CLOSE=${$1:-false}
close_and_exit(){
debug
set -e
if [ "$SHOULD_CLOSE" == "true" ]; then
separator
bump_step "CLOSING SSH PORT"
deny_ssh
fi
separator
info "FINISHED ANSIBLE PLAYBOOK"
ELAPSED="Elapsed: $((SECONDS / 3600))hrs $(((SECONDS / 60) % 60))min $((SECONDS % 60))sec"
info "TOTAL $ELAPSED"
}
if [[ "${BASH_SOURCE[0]}" = "$0" ]]; then
echo "$SHELL"
set -e
SECONDS=0
trap 'close_and_exit' EXIT
if is_no_colors; then
unset_colors
else
set_colors
fi
separator
bump_step "OPENING SSH PORT FOR MY IP"
[ "$DEBUG" == "true" ] && set -x
authorize_ssh
[ "$DEBUG" == "true" ] && set +x
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment