October 30, 2019
VS Code’s SSH Remote Development extension is great. It lets you SSH into any remote server and visually see, edit, and transfer file. It’s a wonderful experience and makes debugging so much nicer, particularly when the resources needed by what you’re working on can’t be accessed locally (RDS databases, for instance.)
EC2 Instance Connect is also awesome. EC2 Instance Connect lets you auth with remote machines without SSH keys, just AWS Access Keys. It lets you securely connect to EC2 instances via browser, which is super handy for quick debugging sessions. It also has a little CLI,
mssh which lets you connect to EC2 instances just by typing
“But,” one might ask, “what if I want to use these tools together… after all, doesn’t VS Code Remote Development require SSH keys?”
It’s true that it does. Also true is that you can actually push a custom SSH key via the AWS CLI before connecting and use that to connect to your instance via traditional SSH tooling. However, after 60 seconds, the key is deleted. So you have to run the terminal command first, then real quickly open VS Code, connect, open the folder…
I got annoyed by this, and it turns out, there is actually a way to specify an alternative SSH command to run while SSHing (trippy) called the “ProxyCommand” directive. Briefly, in
~/.ssh/config (or when configuring VS Code remote hosts), simply add:
Host $your_instance ProxyCommand sh -c "aws ec2-instance-connect send-ssh-public-key --region $your_region --availability-zone $your_az --instance-id $your_instance_id --instance-os-user ubuntu --ssh-public-key file://~/.ssh/$your_private_key.pub; /usr/bin/nc %h %p" HostName $your_host_name User ubuntu IdentityFile ~/.ssh/$your_private_key
This will first push the key, then use it to connect. Tada!
Depending on your local configuration,
--availability-zone may be unnecessary.
This also allows one to simply run
ssh $your_instance to connect to the instance.
Thanks to this StackOverflow question for the tip!