Last active
December 29, 2020 16:42
-
-
Save beattidp/984d18834ca1b4261ae87013f0d61701 to your computer and use it in GitHub Desktop.
Given the name of a CloudFormation stack, upload a local SSH public key and connect to its EC2 instance.
This file contains hidden or 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
# Note: requires 'jq' utility, https://stedolan.github.io/jq/ | |
# Download or install it locally with your package manager. | |
# your cloudformation stack name here | |
export STACK_NAME="eastern-sky-2020" | |
# your SSH key name here | |
export SSH_KEY_NAME="id_rsa_aws_ec2" | |
# filter by Tag named 'aws:cloudformation:stack-name' | |
aws ec2 describe-instances --filter Name=tag:aws:cloudformation:stack-name,Values=${STACK_NAME} \ | |
--query 'Reservations[*].Instances[?State.Name==`running`]' | tee /tmp/ec2i.txt \ | |
| jq -r '.[][] | { "INSTANCE_ID": (.InstanceId), "PUBLIC_IP": (.PublicIpAddress), "AVAIL_ZONE": (.Placement.AvailabilityZone) } | to_entries | .[] | "export " + .key + "=\"" + .value + "\""' \ | |
| tee /tmp/set-connect-params.sh | |
# Output should look something like this: | |
# export INSTANCE_ID="i-0ff4c959b60693129" | |
# export PUBLIC_IP="3.231.19.211" | |
# export AVAIL_ZONE="us-east-1a" | |
# Add these variables to the environment. | |
source /tmp/set-connect-params.sh | |
# Verify the variables are there. | |
env | grep -E "INSTANCE_ID|PUBLIC_IP|AVAIL_ZONE" | |
# Use the variables for arguments to temporarily push | |
# a custom SSH public key to the EC2 instance. | |
aws ec2-instance-connect send-ssh-public-key \ | |
--instance-id ${INSTANCE_ID} \ | |
--instance-os-user ec2-user \ | |
--availability-zone ${AVAIL_ZONE} \ | |
--ssh-public-key file://${HOME}/.ssh/${SSH_KEY_NAME}.pub | |
# Connect via SSH to the instance. | |
ssh -i ${HOME}/.ssh/${SSH_KEY_NAME} ec2-user@${PUBLIC_IP} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment