AWS use EC2 Connect from Terminal without Specify SSH key

tanut aran
2 min readNov 26, 2023

--

Prerequisite: EC2 and SSH Key

Still, you MUST have SSH key associate with that EC2

The mechanism of EC2 Connect is sending SSH key to you. So you still need the SSH key.

Special case: If you are admin or have superior permission

If so, you are already have EC2InstanceConnect permission, you can skip the step 1, 2, 3.

You can directly start on step 4

Step 1: Setup Role

Go to AWS IAM console and choose role then create role. You pick AWS account role then you add EC2InstanceConnect permission.

Step 2: Make sure your user can assume role

2.1. If you don’t have permission to assume role, create this permission first.

2.2 Attach permission that this user can assume custom-* role you have created.

Step 3: Assume Role

Run the following command to get the token

aws sts assume-role
--role-arn <see_in_console>
--role-session-name <any_name_you_like>

Now you have to export the secret to console variable

export AWS_ACCESS_KEY_ID=... see in output
export AWS_SECRET_ACCESS_KEY=... see in output
export AWS_SESSION_TOKEN=... see in output

Step 4: Connect to EC2

By the aws command line run the following command.

Note that you can have problem connecting in case your user is not match the distro you use e.g., ubuntu for Ubuntu, ec2-user for RHEL. So you can specify this by --os-user

aws ec2-instance-connect ssh --instance-id i-12345 --os-user ubuntu   

Bonus: How to reverse assumed role

To reverse the assumed role, you can discard the exported console variable by unset the variable like below.

unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN

--

--

tanut aran
tanut aran

Written by tanut aran

Co-founder and Coder at work !

No responses yet