Search code examples
pythonamazon-web-servicesamazon-ec2boto3boto

Cannot SSH on to AWS EC2 instance created using Boto


I have been creating AWS EC2 instances using Ubuntu and Boto for months. They start-up, I issue commands from Python etc. This has been working fine.

I create the instances using this:

instances = ec2.create_instances(
            ImageId=image_id,
            MinCount=1,
            MaxCount=num_instances,
            InstanceType=instance_type,
            IamInstanceProfile={ 'Name': 'SSMInstanceProfile' },
            Placement={'AvailabilityZone': availability_zone}

Today I created and downloaded a private key file from EC2 console. I then created another instance using Boto (exactly how I have been doing previously).

I got the public DNS address from the console and tried to ssh on to it from my local machine using:

ssh -i /path/to/private/key.pem ec2-user@1.2.3.4.region.compute.amazonaws.com

etc

Nothing happened, the command line just hung.

Do I need to change how I create my boto instances, to accept the new .pem key file?

If not, do I need to change something in the EC2 console to map SSMInstanceProfile to be SSH'd using that .pem?


Solution

  • When attempting to SSH into an Amazon EC2 instance, a 'hanging' response indicates that your SSH client was unable to connect to the instance. (If it did connect, but the connection was refused, the error would appear immediately.)

    Things to check:

    • The instance is running Linux
    • The instance is launched in a public subnet, which is defined as having a Route Table entry to points to an Internet Gateway
    • The instance has a public IP address, which you are using for the connection
    • The Network Access Control Lists (NACLs) are set to their default "Allow All" values
    • A Security Group associated with the instance that permits inbound access on port 22 (SSH) either from your IP address, or from the Internet (0.0.0.0/0)
    • Your corporate network permits an outbound SSH connection (try alternate networks, eg home vs work vs tethered to your phone) -- presumably this is fine since you previously connected to an instance

    Most times, the problem is related to the Security Group. Instead of using the Default security group, I recommend that you create a new Security Group with:

    • An Inbound rule permitting SSH from your IP address (more secure than allowing from Anywhere)
    • An Outbound rule permitting all outbound traffic to Anywhere (0.0.0.0/0)

    Or, instead of attempting to connect via SSH, you could use AWS Systems Manager Session Manager. Please note that this requires some permissions to be added to the IAM Role associated with the EC2 instance. See: Add instance permissions for Session Manager