44 lines
1.5 KiB
Fish
44 lines
1.5 KiB
Fish
function ssm_tunnel --description 'access private AWS ressources via Bastion Host'
|
|
|
|
if test (count $argv) -lt 2
|
|
echo "Provide an Host:Port Mapping & an Local Port"
|
|
return
|
|
end
|
|
|
|
if [ "$env" != "ops" ]
|
|
echo "Switch to OPS ENV first"
|
|
return
|
|
end
|
|
|
|
# Get bastion host ID using it's name
|
|
set INSTANCE_ID (aws ec2 describe-instances \
|
|
--filter 'Name=tag:Name,Values=ops-infrastructure-bastion'\
|
|
--query "Reservations[].Instances[?State.Name == 'running'].InstanceId[]"\
|
|
--output text)
|
|
|
|
# AWS Remote host i.e elastic.aws.com:80
|
|
set REMOTE_HOST $argv[1]
|
|
|
|
# Ports to bind for forwarding
|
|
set LOCAL_PORT $argv[2]
|
|
set REM_PORT (math (random) % 65535 + 2000)
|
|
set TIMEOUT 21600 #seconds until forwarding session times out (48h max)
|
|
|
|
# make sure jq is installed
|
|
# Start socat on the remote server
|
|
set CMD "'sudo socat TCP4-LISTEN:$REM_PORT,reuseaddr,fork TCP4:$REMOTE_HOST'"
|
|
set CMD_INVOC_ID (aws ssm send-command --instance-ids $INSTANCE_ID \
|
|
--document-name 'AWS-RunShellScript' \
|
|
--parameters "commands=$CMD,executionTimeout=$TIMEOUT" --output json | jq -r '.Command.CommandId')
|
|
|
|
# Start tunnel session
|
|
echo "Starting Tunnel"
|
|
aws ssm start-session --target $INSTANCE_ID \
|
|
--document-name "AWS-StartPortForwardingSession" \
|
|
--parameters "portNumber=$REM_PORT,localPortNumber=$LOCAL_PORT"
|
|
|
|
# stop socat on the bastion
|
|
aws ssm cancel-command --command-id $CMD_INVOC_ID
|
|
echo "Command Cancelled Successfully."
|
|
end
|