Created
November 7, 2024 17:49
-
-
Save shawnz/4e945d11b10c2066b7769dc46d36a2ff 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 | |
set -Eeufo pipefail | |
# ec2-proxy-command | |
# ================== | |
# | |
# Use this script with the ssh ProxyCommand option to automatically | |
# start an EC2 instance and then connect to its public DNS name. | |
# | |
# For example, consider the following stanza in ~/.ssh/config: | |
# | |
# Host my-ec2-instance i-0123456789abcdef0 | |
# HostName my-ec2-instance | |
# ProxyCommand ~/.local/bin/ec2-proxy-command i-0123456789abcdef0 | |
# User ec2-user | |
# ForwardAgent no | |
# | |
# With this stanza in place, and this script saved with the filename | |
# ~/.local/bin/ec2-proxy-command, you can then execute "ssh my-ec2-instance" | |
# to automatically start and connect to the EC2 instance with id | |
# i-0123456789abcdef0. | |
PROGRAM_NAME="$(basename $0)" | |
show_help() { | |
echo "Usage: $PROGRAM_NAME [-p profile] [-r region] <instance id>" | |
echo "Use this script with the ssh ProxyCommand option to automatically" | |
echo "start an EC2 instance and then connect to its public DNS name." | |
echo "" | |
echo " -p profile the name of the AWS CLI profile to use" | |
echo " -r region the AWS region where the instance exists" | |
} | |
while getopts ":hp:r:" opt; do | |
case "$opt" in | |
h) show_help; exit 0;; | |
p) export AWS_PROFILE="$OPTARG";; | |
r) export AWS_REGION="$OPTARG";; | |
:) | |
echo "$PROGRAM_NAME: Missing argument: -$OPTARG" >&2 | |
show_help >&2 | |
exit 1;; | |
\?) | |
echo "$PROGRAM_NAME: Invalid option: -$OPTARG" >&2 | |
show_help >&2 | |
exit 1;; | |
esac | |
done | |
shift "$((OPTIND-1))" | |
if [ "$#" -eq 0 ]; then | |
echo "$PROGRAM_NAME: No instance ID specified." >&2 | |
show_help >&2 | |
exit 1 | |
elif [ "$#" -gt 1 ]; then | |
echo "$PROGRAM_NAME: Too many arguments specified." >&2 | |
show_help >&2 | |
exit 1 | |
fi | |
INSTANCE_ID="$1" | |
echo "Starting instance $INSTANCE_ID..." >&2 | |
aws ec2 start-instances --instance-ids "$INSTANCE_ID" > /dev/null | |
echo "Waiting for instance to be ready..." >&2 | |
aws ec2 wait instance-status-ok --instance-ids "$INSTANCE_ID" | |
INSTANCE_PUBLIC_DNS_NAME="$(aws ec2 describe-instances \ | |
--instance-ids "$INSTANCE_ID" \ | |
--query "Reservations[0].Instances[0].PublicDnsName" \ | |
--output text)" | |
echo "Connecting to public DNS name $INSTANCE_PUBLIC_DNS_NAME..." >&2 | |
socat stdio "tcp:$INSTANCE_PUBLIC_DNS_NAME:22" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment