Last active
December 22, 2022 19:18
-
-
Save bbuechler/7aedb84794bf361114a8d9920375a824 to your computer and use it in GitHub Desktop.
Deploy a SSM-Bastion with magic key pulling
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
| # Upload your key to NGAP Bastion Self-serve bucket | |
| # https://wiki.earthdata.nasa.gov/display/ESKB/SSH+Bastion+Key+Upload+-+Self-Service | |
| export key_bucket=$(aws s3 ls | xargs -n1 echo | grep ngap-bastion-authorized-public-keys) | |
| export my_ssh_key="/path/to/.ssh/<your_private_key>" | |
| aws s3 cp $my_ssh_key.pub s3://$key_bucket/ | |
| # Optional Params with Reasonable Defaults that you may want to change | |
| export bastion_name="SSM Bastion" | |
| export instance_type="t2.micro" | |
| # Account Specific Params | |
| export key_name=$(aws ec2 describe-key-pairs | jq -r .KeyPairs[0].KeyName ) | |
| export subnet_id=$(aws ec2 describe-subnets --query "Subnets[*].{ID:SubnetId}[0]" --filters "Name=tag:Name,Values=Private*" --output=text) | |
| # Deploy The STack | |
| aws cloudformation create-stack \ | |
| --stack-name "SSM-Bastion" \ | |
| --capabilities CAPABILITY_IAM \ | |
| --template-url https://s3.amazonaws.com/asf.public.code/ssm-bastion/build-a-bastion-workshop.yaml \ | |
| --parameters ParameterKey=BastionAmi,ParameterValue=image_id_amz2 \ | |
| ParameterKey=BastionName,ParameterValue="$bastion_name" \ | |
| ParameterKey=InstanceType,ParameterValue=$instance_type \ | |
| ParameterKey=SSHKeyName,ParameterValue="$key_name" \ | |
| ParameterKey=Subnet,ParameterValue=$subnet_id | |
| # Run runs every 10 minutes to pull the SSH key from the bucket.... So give it 15! | |
| # Look up the Bastion Instance id | |
| export ssm_bastion=$(aws ec2 describe-instances --filters Name=tag:Name,Values="$bastion_name" Name=instance-state-name,Values=running --query "Reservations[].Instances[].InstanceId" --output=text) | |
| # SSH to your instance using SSH keys. | |
| ssh -o ProxyCommand="sh -c 'aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=22'" -i $my_ssh_key ec2-user@$ssm_bastion | |
| # Create a persistent SSH Tunnel for connection proxying | |
| ssh -o ProxyCommand="sh -c 'aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=22'" -i $my_ssh_key -fN -D 127.0.0.1:8001 ec2-user@$ssm_bastion | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment