Sub topic 7
EC2 Instance Connect and Temporary Keys
EC2 Instance Connect lets you log in over SSH without a long-lived key pair on the instance. You push a public key through an IAM-authorized API call, and the instance accepts it for about 60 seconds. This chapter covers how that works, what the instance and your IAM identity need, how to use it from the CLI, and where it fails.
It assumes you can already open an SSH connection to an instance (the previous chapters on network reachability, key pairs, and ssh). You also need the AWS CLI configured with credentials, and a basic grasp of IAM policies.
What Instance Connect changes and what it does not
Plain SSH uses a key pair you created at launch. The public half sits in ~/.ssh/authorized_keys on the instance until someone removes it. Anyone holding the private key can log in, and AWS has no record of who used it.
Instance Connect replaces that distribution step. You call the SendSSHPublicKey API, and AWS places your public key in the instance metadata. A small component on the instance reads it when you connect. You then use ordinary SSH with the matching private key.
Three things stay the same:
- The instance still needs a network path. Port 22 must be reachable from your client, so the security group and route table rules from earlier chapters still apply.
- You still use an SSH client and the correct login user for the AMI.
- The connection is standard SSH. Only the way the public key reaches the instance differs.
Two things change:
- Access is governed by IAM, not by whoever holds a key file. Each push is a CloudTrail event tied to an identity.
- The key expires in about 60 seconds, so a leaked public key has little value.
How it works inside the instance
The ec2-instance-connect package installs scripts and edits the SSH daemon's configuration. The key setting is AuthorizedKeysCommand, which tells sshd to run a program that returns extra authorized keys for the user logging in. The program reads the instance metadata and returns any key that was pushed recently. A dedicated unprivileged account, ec2-instance-connect, runs it.
The sequence looks like this:
Which AMIs include the package:
- Amazon Linux 2 and Amazon Linux 2023 include it.
- Ubuntu images published by Canonical include it, with
ubuntuas the login user. - Other distributions and custom AMIs may not. You can install the package yourself, but you should test it, because it takes over
AuthorizedKeysCommand.
To check an instance, look for the setting in its SSH configuration:
sudo grep -R "AuthorizedKeysCommand" /etc/ssh/If nothing from ec2-instance-connect appears, the instance will ignore pushed keys.
Static keys in ~/.ssh/authorized_keys keep working next to Instance Connect. Pushing a temporary key does not remove them. If you adopt Instance Connect to reduce key sprawl, you must also remove old static keys, or the benefit is partly lost.
Pushing a key and connecting
You need a key pair on your own machine. An existing one works, or you can generate one:
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519Then push the public key and connect right away:
aws ec2-instance-connect send-ssh-public-key \
--instance-id i-0123456789abcdef0 \
--instance-os-user ec2-user \
--ssh-public-key file://$HOME/.ssh/id_ed25519.pub
ssh -i ~/.ssh/id_ed25519 [email protected]Points to check in these commands:
--instance-os-usermust be the same Linux user you give tossh. A key pushed forec2-userdoes not work forubuntu.- The
file://prefix tells the CLI to read the file contents. Without it, the CLI treats the path as the key text. - The two commands should run back to back. The 60-second window starts at the push, not at your next keystroke.
- The window limits when you can authenticate. A session already open when the key expires is not closed.
A successful push returns a JSON response with "Success": true and a request ID. That only means AWS accepted the key. It does not mean the instance has the package, or that the network path is open.
The one-command form
AWS CLI version 2 also offers a wrapper that pushes the key and starts SSH in one step:
aws ec2-instance-connect ssh --instance-id i-0123456789abcdef0It uses your default SSH key unless you supply another, and it chooses the login user for you unless you pass one. Check aws ec2-instance-connect ssh help for the options in your CLI version. The wrapper is convenient interactively. In scripts, the explicit two-step form is easier to debug, because you can see which step failed.
IAM permissions
The permission you need is ec2-instance-connect:SendSSHPublicKey. Scope it to specific instances and to specific login users:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ec2-instance-connect:SendSSHPublicKey",
"Resource": "arn:aws:ec2:us-east-1:111122223333:instance/i-0123456789abcdef0",
"Condition": {
"StringEquals": {
"ec2:osuser": "ec2-user"
}
}
}
]
}The ec2:osuser condition limits the Linux account the caller can push a key for. Without it, a user who can reach an instance could push a key for root or any other account that accepts logins. You can also match on resource tags (for example, allow access only to instances tagged Environment=dev) by using the aws:ResourceTag/ condition keys in the same statement.
Browser-based connect and private instances
The EC2 console has a Connect button with an Instance Connect tab. It opens a terminal in your browser, pushes a key on your behalf, and connects. For it to work, port 22 on the instance must accept traffic from the AWS-published address range for the EC2_INSTANCE_CONNECT service in your Region. It is not your own IP address that must be allowed. Rather than copying ranges by hand, many teams reference the managed prefix list for the service in the security group rule.
For instances without a public IP, AWS offers EC2 Instance Connect Endpoint. It is a resource you create in a VPC subnet, and it forwards SSH to private instances without a bastion host or public address. Access to it is also governed by IAM. It is a separate feature from the key push described here. Session Manager, covered in later chapters, solves the same problem without any inbound port.
Failure modes
| Symptom | Likely cause | What to check |
|---|---|---|
| `Permission denied (publickey)` right after a successful push | More than 60 seconds elapsed, or the user name differs | Re-push and connect immediately. Match `--instance-os-user` to the `ssh` user. |
| `Permission denied (publickey)` every time | Package missing, or `sshd` not using `AuthorizedKeysCommand` | Run the `grep` above. Install or repair the `ec2-instance-connect` package. |
| `AccessDeniedException` on the push | IAM policy lacks the action, or the `ec2:osuser` condition does not match | Check the policy resource ARN and the user name you passed. |
| Connection timed out | Security group, network ACL, or route problem | Port 22 must be open from your source. Work through the earlier troubleshooting chapter. |
| Push fails with an error about the instance | Instance not running, or metadata service disabled | Confirm the instance state and that the metadata service is enabled. |
The most common trap is mixing up the two layers. A successful API call proves your IAM permission is fine. A failed SSH login after that is a problem on the instance or in the network.
Auditing
Every SendSSHPublicKey call appears in CloudTrail with the caller identity, the target instance, and the OS user. This gives you a record of who requested access to which instance and when. It does not record what the user did afterwards. For command-level audit, you need Session Manager logging, which a later chapter covers.
When Instance Connect fits
Use it when you want SSH, existing tooling, and IAM-based control without managing key distribution. It works well for small fleets and for AMIs that already ship the package. Its limits are that it still needs port 22 reachable, and that its audit trail stops at the connection. If you need no open inbound ports or full session logs, Session Manager is the better fit.
Exercise
A teammate runs aws ec2-instance-connect send-ssh-public-key for user ec2-user and sees "Success": true. They wait two minutes, then run ssh -i ~/.ssh/id_ed25519 [email protected] and get Permission denied (publickey). Name the likely cause and the fix. Then say what a Connection timed out would have meant instead.
Show answer
The pushed key expires after about 60 seconds, and the SSH attempt happened after that. The fix is to push the key again and run ssh immediately. A timeout would mean the SSH packets never reached sshd, which points to the security group, network ACL, route table, or public IP, not to the key.