AWS EC2 Instance Connect

AWS EC2 Instance Connect

AWS EC2 Instance Connect is another way of connecting to EC2 but using this method we can push our own public key into the instance and establish a SSH connection. This writeup is a quick culmination of my tinkering with AWS EC2 Instance Connect. In this writeup, the following OS was used i.e

  • Ubuntu 20.04
  • Amazon Linux 2023


Cloud9 Setup

  1. In this example, Cloud9 ide is used as it comes preinstalled with aws cli and doesn't require any further setup. However, its best to set off AWS Settings -> AWS managed temporary credentials off.
  2. On the terminal run the following commands to setup cli credentials

export AWS_ACCESS_KEY_ID="accesskeyid" 
export AWS_SECRET_ACCESS_KEY="accesskey" 
export AWS_SESSION_TOKEN="token"        

Ec2 Instance Connect Configuration

  1. Run the following command on the terminal (of cloud9 IDE) to generate a new key-pair. We will be pushing this key to the instances in the later steps.

ssh-keygen -t rsa -f my_key        

  1. The command to send ssh key to instance.

aws ec2-instance-connect send-ssh-public-key     --region us-east-1     --availability-zone us-east-1d     --instance-id i-044fc8e855feaba47     --instance-os-user ec2-user     --ssh-public-key file://my_key.pub 
{
   "RequestId": "8a059493-2dcf-4374-96d0-89d02917e51d",
   "Success": true
}        

  1. Once the key has ben sent to the instance, you can issue ssh command such as below to connect to the instance :

ssh -o "IdentitiesOnly=yes" -i my_key ec2-user@172.31.47.27
ssh -o "IdentitiesOnly=yes" -i my_key ubuntu@172.31.6.234        

Note: Please whitelist the IP address of Cloud9 instance in the security group of instance that you are trying to ssh into e.g i-044fc8e855feaba47

  1. In addition to region the information of availability zone is required. Providing wrong AZ will result in the following error

An error occurred (EC2InstanceNotFoundException) when calling the SendSSHPublicKey operation: Instance not found in the specified Availability Zone.          

My verdict

This solution is useful perhaps in some use cases, however I would still prefer to use session manager as in AWS Session Manager

(i) access will be logged and can be audited

(ii) access can be controlled via iam policy which means we can set expiry condition (date)

(iii) no IP whitelisting is required


To view or add a comment, sign in

Others also viewed

Explore topics