DEV Community

Andy Tran
Andy Tran

Posted on

How to Connect to an EC2 Instance in a Private Subnet

Prerequisites

Before you start, ensure you have the following:

  • An EC2 instance running in a private subnet.
  • AWS Systems Manager (SSM) Agent installed and running on the instance.
  • An IAM role attached to the instance with the necessary permissions to use SSM.
  • AWS CLI configured on your local machine.

Step 1: Attach an IAM Role to the EC2 Instance

  1. Create an IAM Role (if you don’t have one):

    • Go to the IAM service in the AWS Management Console.
    • Choose Roles and then Create role.
    • Select AWS service and choose EC2.
    • Attach the AmazonEC2RoleforSSM managed policy.
    • Name your role and complete the creation process.
  2. Attach the IAM Role to your EC2 Instance:

    • Go to the EC2 Dashboard.
    • Select your instance.
    • Click on Actions > Security > Modify IAM Role.
    • Attach the IAM role you created or an existing role with the necessary SSM permissions.

Step 2: Verify SSM Agent Installation

  1. Check if SSM Agent is Installed:

    • Connect to your instance using an existing method (if possible) or check the instance launch configuration.
    • For Amazon Linux, the SSM Agent is pre-installed. For other AMIs, you might need to install it manually.
  2. Install SSM Agent Manually (if not installed):

    • For Amazon Linux:
     sudo yum install -y amazon-ssm-agent
     sudo systemctl start amazon-ssm-agent
     sudo systemctl enable amazon-ssm-agent
    

Step 3: Connect to the Instance Using SSM

  1. Configure AWS CLI:

    • Open your terminal or command prompt.
    • Configure the AWS CLI with your credentials and default region:
     aws configure
    
  • Follow the prompts to enter your AWS Access Key ID, Secret Access Key, Default region name (e.g., us-east-1), and Default output format (e.g., json).
  1. Start an SSM Session:

    • Use the following command to start a session with your instance:
     aws ssm start-session --target <instance-id>
    
  • Replace <instance-id> with the actual instance ID of your EC2 instance in the private subnet.

Example

Assuming your instance ID is i-0a677d0c4370bebab, you would run:

aws ssm start-session --target i-0a677d0c4370bebab
Enter fullscreen mode Exit fullscreen mode

We are now connected and can run simple commands like hostname and uptime.

Image description

Note: If you have trouble for any reason, you can reference this deployment guide and use the CloudFormation template provided.

Top comments (0)