Skip to content

Instantly share code, notes, and snippets.

@Yapcheekian
Last active June 15, 2021 03:54
Show Gist options
  • Save Yapcheekian/5315d1c8c8cd89378d2ba9bca6dcab72 to your computer and use it in GitHub Desktop.
Save Yapcheekian/5315d1c8c8cd89378d2ba9bca6dcab72 to your computer and use it in GitHub Desktop.
ssh tunneling with ssm
set -eu
REGION_SEPARATOR='--'
ec2_instance_id="$1"
ssh_user="$2"
ssh_port="$3"
ssh_public_key_path="$4"
ssh_public_key="$(cat "${ssh_public_key_path}")"
ssh_public_key_timeout=60
if echo "${ec2_instance_id}" | grep -qe "${REGION_SEPARATOR}"
then
export AWS_DEFAULT_REGION="${ec2_instance_id##*${REGION_SEPARATOR}}"
ec2_instance_id="${ec2_instance_id%%${REGION_SEPARATOR}*}"
fi
>/dev/stderr echo "Add public key ${ssh_public_key_path} to instance ${ec2_instance_id} for 60 seconds"
aws ec2-instance-connect send-ssh-public-key \
--instance-id "$ec2_instance_id" \
--instance-os-user "$ssh_user" \
--ssh-public-key "file://$ssh_public_key_path" \
--availability-zone ap-northeast-1c \
--profile prodaccess \
--region ap-northeast-1
>/dev/stderr echo "Start ssm session to instance ${ec2_instance_id}"
aws ssm start-session \
--target "${ec2_instance_id}" \
--region ap-northeast-1 \
--profile prodaccess \
--document-name 'AWS-StartSSHSession' \
--parameters "portNumber=${ssh_port}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment