# EC2 Instance Connect setup and troubleshooting in the AWS console

> Check EC2 Instance Connect setup, network prerequisites and IAM permissions, and troubleshoot 'Failed to connect to your instance' in the AWS console.

BlowStack blog, published 2022-09-18, updated 2026-11-08, 8 min read. Page: https://blowstack.com/blog/how-to-set-up-ec2-instance-connect

## **Open an EC2 shell from the AWS console using a public IPv4 address**

EC2 Instance Connect is one of three dedicated AWS services that enable command line access to an EC2 instance without the need for a traditional SSH key; the other two are Session Manager and EC2 Serial Console. EC2 Instance Connect does, however, use its own short-lived SSH keys internally, but these are managed automatically, so you are not required to handle them manually.

Once connected to an EC2 instance, you gain access to a **Bash interactive console** that offers the same functionality as available through a traditional SSH client.

A notable feature of EC2 Instance Connect is the authentication method. AWS Identity and Access Management (IAM) authorizes publishing an SSH public key; it does not replace SSH authentication. EC2 Instance Connect makes the public key available through instance metadata for 60 seconds, and the instance's SSH daemon (sshd) uses it to authenticate the OS user by verifying that the client holds the corresponding private key. This window does not limit the duration of an established session. Automatic key handling depends on the client workflow: the browser-based console handles keys automatically, while a manual SSH workflow requires you to supply a key. IAM access can come through roles or federation, not just IAM users, simplifying access management without replacing the instance's own authentication and authorization controls.

Additionally, EC2 Instance Connect is a free service, incurring **no additional costs for its use.**

### EC2 instance connect from the AWS console

The EC2 Instance Connect service can be accessed through the 'Connect' menu in the AWS Management Console. There are several ways to reach it. One common method is by navigating to the [list of EC2 instances](https://console.aws.amazon.com/ec2/). From there, you can simply click on the 'Connect' button associated with the specific instance you wish to access

![](https://blowstack.com/images/blog/posts/how-to-setup-ec2-instance-connect/instances-list-connect-options-button.jpg)

Instances list connect options button.

On the new page, EC2 Instance Connect is often presented as the first option by default. However, its availability depends on the operating system of the EC2 instance. Supported options include **Amazon Linux 2**, **Amazon Linux 2023** and **Ubuntu** 22.04 LTS. Package availability does not mean that EC2 Instance Connect is preinstalled on every AMI; check your specific image and install the package if needed. For the current supported-OS and AMI requirements, consult the official AWS setup documentation linked below rather than assuming that every later Ubuntu release is supported. Use Ubuntu 22.04 LTS for this walkthrough instead of the older Ubuntu releases mentioned below.

If your instance runs on an unsupported operating system, EC2 Instance Connect will not be available as an option.

## **EC2 instance connect basic requirements and setup**

If you are able to connect successfully, you can skip the following sections titled 'Task'. However, it's common to encounter an error on your first attempt to connect, typically related to one of four specific 'Tasks'.

This issue arises because there are certain prerequisites that must be met to use EC2 Instance Connect effectively. There are **four main tasks** to complete (or three, if you choose to use the AWS console exclusively and avoid the CLI).

This post primarily addresses the standard use case where users connect to their EC2 instance using public IP addresses, presented in a simplified and concise format. For those who need more detailed guidance on fulfilling these prerequisites, or for those who wish to connect using private IP addresses, it is advisable to consult [the official AWS documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-set-up.html#ec2-instance-connect-setup-security-group).

### Task 1 - set up network access (public IP)

If Task 1 is not completed successfully, then when you attempt to connect to your EC2 instance, you will encounter an error message like the following (or similar):

```plaintext
Failed to connect to your instance
We were unable to connect to your instance. Make sure that your instance network settings are configured correctly for EC2 Instance Connect. For more information, check Task 1 under the Set up EC2 Instance Connect AWS documentation.
```

To effectively use EC2 Instance Connect, it is essential to have properly configured network access that facilitates the connection between the service and the EC2 instance. This setup is somewhat similar to connecting via a direct SSH client, where you must specify the host, user, and ensure appropriate firewall rules are in place.

A key difference with EC2 Instance Connect is that it eliminates the need for managing SSH keys. First, let's focus on configuring the host.

#### **Host**

First, verify whether a public IP address is already associated with your EC2 instance. You can do this by checking the EC2 instance list or the details page of the specific EC2 instance in the AWS Management Console. If you did not explicitly disable the 'Auto-assign Public IP' feature during the creation of the EC2 instance, then your instance should already have a public IP address, and you can proceed to the next requirement.

![](https://blowstack.com/images/blog/posts/how-to-setup-ec2-instance-connect/ec2-explicitly-disable-auto-public-ip.jpg)

Default EC2 instance settings.

If a public IP address was not automatically assigned to your EC2 instance at launch, and you need one, there are several options to consider. However, automatically assigning a public IPv6 address to an already launched EC2 instance is only possible if both the VPC and the subnet have an IPv6 CIDR block assigned, which is not the default configuration. For detailed instructions on assigning an IPv6 address to an instance post-launch, refer to [the official AWS documentation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#assign-ipv6-address).

Another alternative is to create an image of your EC2 instance and then launch a new instance from this image, ensuring you enable the 'Auto-assign Public IP' option during the process.

If neither of these options is suitable, a viable alternative is to allocate an Elastic IP address and associate it with your instance. This can be done by attaching the Elastic IP to the network interface of the EC2 instance, which is accessible through the 'Manage IP Addresses' option in the context menu of the 'Networking' tab on the EC2 instance detail page.

It's important to note that since February 2024, AWS generally charges $0.005 per public IPv4 address-hour, including auto-assigned addresses and Elastic IPs attached to running instances, subject to applicable credits or allowances. EC2 Instance Connect itself has no additional service fee, but EC2, public IPv4, and data-transfer costs still apply.

#### **Security group (firewall rules)**

The next step is to configure your security group to allow connections to EC2 instances using the SSH protocol. Allow inbound TCP port 22 from the EC2 Instance Connect service ranges for your instance's region when using the browser client, or from your client's public source IP when connecting directly through the CLI. 'Anywhere-IPv4' exposes SSH to the entire internet and is not recommended; it does not guarantee that EC2 Instance Connect will work. For public IPv4 connections, verify that the instance has a public IPv4 address: auto-assignment depends on both subnet and launch settings, so do not assume it was enabled. The subnet's route table must also have a route to an attached internet gateway, typically 0.0.0.0/0. Check that network ACLs allow inbound TCP port 22 from the appropriate source and outbound return traffic to the client's ephemeral ports, that the SSH server (sshd) is running and listening on port 22, and that the host firewall permits this traffic. Alternatively, EC2 Instance Connect Endpoint supports connections to the instance's private IP with appropriate endpoint permissions and network rules, without requiring a public IP or rebuilding the instance.

A more secure approach is to specifically allow IP addresses used by the EC2 Instance Connect service. To find these IP ranges, visit [the AWS IP ranges page](https://ip-ranges.amazonaws.com/ip-ranges.json) and use the search function (Ctrl+F) to find entries with 'EC2\_INSTANCE\_CONNECT' as the service name. When adding these IP ranges to your security group rules, ensure that you select the ranges corresponding to the 'network\_border\_group' that matches the region of your EC2 instance's network interface.

For instance, if your instance is in the 'eu-west-1c' availability zone, look for entries with 'eu-west-1' in their network\_border\_group. An example entry for 'eu-west-1' would look like this:

```plaintext
    {
      "ip_prefix": "18.202.216.48/29",
      "region": "eu-west-1",
      "service": "EC2_INSTANCE_CONNECT",
      "network_border_group": "eu-west-1"
    }
```

You should end up with the following entry in the inbound rules of your security group:

![](https://blowstack.com/images/blog/posts/how-to-setup-ec2-instance-connect/ec2-instance-connect-service-allowed-ip.jpg)

EC2 instance connect service allowed IPs.

### Task 2 - installing EC2 instance connect agent

If Task 2 is not properly completed, you may encounter the error message below, which does not specify a task number. Treat the displayed errors as diagnostic clues, not proof that a particular task is missing: this generic SSH failure can also reflect networking, sshd, or username problems.  
**Verification checklist:**  
1\. Check the public IP, internet gateway route, security group source rules, network ACLs and host firewall for SSH access on TCP port 22, as described in Task 1.  
2\. Verify that sshd is running and listening on port 22, and that the `ec2-instance-connect` package is installed with its `AuthorizedKeysCommand` and `AuthorizedKeysCommandUser` settings active.  
3\. Check that your IAM permissions allow `ec2-instance-connect:SendSSHPublicKey` for the target instance and OS username, along with `ec2:DescribeInstances` for the console workflow.  
**Connection test:** Once these checks pass, select the instance in the AWS Management Console, choose 'Connect', then 'EC2 Instance Connect', and enter the correct OS username: normally `ec2-user` for Amazon Linux or `ubuntu` for Ubuntu. For a custom AMI, use its configured OS account. Click 'Connect', then run `whoami` in the terminal. A working shell that returns the expected username confirms a successful connection.

```plaintext
Failed to connect to your instance
Error establishing SSH connection to your instance. Please wait and try again later
```

If the required `ec2-instance-connect` package is missing on your instance, you need another access method to install it. This package integrates with the SSH server (sshd), configuring `AuthorizedKeysCommand` and `AuthorizedKeysCommandUser` to retrieve temporary public keys from instance metadata; it is not a standalone agent. You can use a standard SSH client, or Session Manager or Systems Manager Run Command if the instance already has a working SSM Agent, appropriate IAM permissions and connectivity to Systems Manager. If these options are unavailable, an offline recovery procedure for an EBS-backed root volume may allow you to restore access: snapshot the volume, stop the instance, attach its root volume to a helper instance, repair SSH access, then reattach it to the original instance and start it. Losing your SSH key therefore does not necessarily prevent recovery. Installation requires administrative privileges, access to the distribution's package repositories and a running OpenSSH server. On Ubuntu 22.04 LTS, run `sudo apt-get update`, then `sudo apt-get install openssh-server ec2-instance-connect`. On Amazon Linux 2, run `sudo yum install openssh-server ec2-instance-connect`; on Amazon Linux 2023, use `sudo dnf install openssh-server ec2-instance-connect`. A full system upgrade is not required to install the package.

To resolve this, first connect to your instance using a standard SSH client. Once logged in, update the package list and upgrade the system. Then, install the EC2 Instance Connect agent. Below are the commands you should use for Amazon Linux and Ubuntu operating systems, respectively:

```plaintext
sudo yum install ec2-instance-connect
```

```plaintext
sudo apt-get install ec2-instance-connect
```

### **Task 3 - install CLI**

There will not be an error specifically related to Task 3, as this step is not mandatory for EC2 Instance Connect functionality. Task 3 pertains to the use of the AWS Command Line Interface (CLI), which is optional since you can alternatively use the AWS Management Console. This walkthrough covers console-based connections only, so you can skip Task 3. Current AWS CLI v2 supports `aws ec2-instance-connect ssh` without the older, separate Python CLI helper. For a separate CLI walkthrough, including client prerequisites and credentials, consult the EC2 Instance Connect connection instructions in the official AWS documentation linked above.

Additionally, it's important to update your security group to include your IP address for SSH connections. This ensures that your connection through the CLI is authorized and secure.

### **Task 4 - user permissions**

When using EC2 Instance Connect, whether from the CLI or the AWS Management Console, you are authenticating through the AWS Identity and Access Management (IAM) system, not directly via an SSH client. This process requires that certain permissions be granted to the IAM user attempting access. If these permissions are not correctly configured, you can expect to encounter errors. The specific errors that may appear will depend on which required permissions are missing or improperly set.

```plaintext
An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.
```

```plaintext
Failed to connect to your instance
Access denied by EC2 Instance Connect. Either your AWS credentials are not valid or you do not have access to the EC2 instance.
```

To rectify these errors, you need to add specific permissions to the IAM user. This can be done by updating the user's permissions policy with the JSON configuration provided below.

When doing so, it's crucial to replace the placeholders for 'region', 'accountId', 'instanceId', and the 'ec2:osuser' value with your actual instance's region, AWS account ID, instance ID, and the username of the instance, respectively.

It's important to note that the default value for 'ec2:osuser' is 'ec2-user' for Amazon Linux AMIs and 'ubuntu' for Ubuntu AMIs. Here is the JSON template for the permissions:

```plaintext
{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": "ec2-instance-connect:SendSSHPublicKey",
        "Resource": [
            "arn:aws:ec2:{region}:{accountId}:instance/{instanceId}"
        ],
        "Condition": {
            "StringEquals": {
                "ec2:osuser": "{"ec2-user | ubuntu | differentNotDefaultUserName}"
            }
        }
      },
      {
        "Effect": "Allow",
        "Action": "ec2:DescribeInstances",
        "Resource": "arn:aws:ec2:{region}:{accountId}:instance/{instanceId}"
      }
    ]
}
```

Additionally, it's important to note that beyond the specific permissions required for EC2 Instance Connect, the AWS Command Line Interface (CLI) needs valid AWS credentials, not an IAM user with 'Programmatic access' enabled or long-lived access keys. Prefer temporary credentials from IAM Identity Center or an assumed IAM role; the CLI also supports workload role credentials and IAM user access keys supplied through profiles or environment variables. Console access can likewise be federated through IAM Identity Center or another identity provider; the IAM user console-access requirement below applies only to IAM user sign-ins. For MFA, require it through IAM Identity Center or your identity provider's sign-in policy, or enforce it when obtaining temporary credentials through an MFA-required AWS STS workflow, such as a role trust policy requiring MFA for IAM users assuming the role. Use those temporary credentials for CLI requests. Merely enabling MFA on an IAM user does not make requests signed with that user's long-lived access keys MFA-protected.

Similarly, if you plan to interact with EC2 Instance Connect through the AWS Management Console, your IAM user needs to have 'AWS Management Console access' granted. These access types are essential for ensuring that the user can interact with AWS services either via the CLI or the Console, as appropriate.

## How secure is EC2 instance connect

EC2 Instance Connect offers enhanced security compared to traditional SSH clients. The key reason is that all authentication and authorization processes are managed by AWS Identity and Access Management (IAM), aligning the security of accessing your EC2 instance with the robust security measures of AWS itself.

To further enhance the security of EC2 Instance Connect, consider the following practices:

### **Enable Multi-Factor Authentication (MFA)**

This adds an additional layer of security, and is recommended for both AWS Management Console and CLI access.

### **Integrate with AWS CloudTrail**

By using CloudTrail, you can monitor and log who called EC2 Instance Connect APIs, such as SendSSHPublicKey to publish an SSH public key, and when they did so. A successful API event does not prove that an SSH login succeeded, and CloudTrail does not record commands executed inside the SSH session. To audit successful and failed SSH logins, collect the instance's sshd authentication logs. To audit commands or session activity, configure additional OS audit rules (for example, with auditd) or session recording. Together, these logs aid in auditing and identifying unauthorized access.

### **Use Least Privilege SSH Users**

Default users (like 'ec2-user' or 'ubuntu') are not root users, but commonly have broad sudo privileges. Instead of sharing these accounts, create individually attributable OS accounts with minimal necessary privileges and restrict their sudo access. These accounts must exist on the instance; use IAM conditions on 'ec2:osuser' to limit each connecting IAM principal to the appropriate OS account. The 'AMI Connecting User' mentioned below refers to the connecting person or IAM principal, not an AMI. This reduces the risk of extensive damage if a user account is compromised.

### **Assign Separate SSH Users for Each AMI Connecting User**

This practice helps in tracking and controlling individual user activities, enhancing accountability and security.

### **Restrict Security Group Access**

Avoid using '0.0.0.0/0' in your EC2 security group rules. Instead, specify the exact IP addresses used by EC2 Instance Connect (as mentioned in Task 1) to limit access to authorized sources only.

### **Specify Instance ARNs and Usernames in User Permissions**

When setting up IAM permissions (as outlined in Task 4), be specific about the instance ARNs and user names to ensure that permissions are tightly controlled and access is granted only to the intended entities."

These steps can significantly strengthen the security posture of your EC2 instances, making them less vulnerable to unauthorized access and potential threats.

## **Summary**

EC2 Instance Connect is a valuable AWS service that simplifies SSH connections, primarily for Amazon Linux and Ubuntu instances. It conveniently abstracts the complexity of managing SSH keys, although they are still utilized internally. However, it's important to enhance security measures. This includes enabling Multi-Factor Authentication (MFA) and considering the creation of new, non-sudo privileged SSH users for each IAM user who needs access to an EC2 instance.

While EC2 Instance Connect primarily supports Amazon Linux and Ubuntu, it's worth noting that with some configuration, it can be extended to other Linux distributions as well.

---

BlowStack: AWS practice exams and courses, https://blowstack.com/practice-exams
