Skip to main content

Cloud and deployment · Intermediate · 20 min

Connect to EC2 instances without open SSH ports using Session Manager

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4 · Session Manager plugin

You will reach an Ubuntu 26.04 EC2 instance through AWS Systems Manager Session Manager with port 22 closed, forward a port to a private database, copy files with scp using a 60-second key, and record shell sessions to S3.

On this page

The usual way into a cloud server is SSH on port 22, open to your address, with a key pair you have to keep safe. When a team grows, that turns into a bastion host: one more server with a public address, its own patches, its own keys, and a list of who can reach it that lives in a security group rather than in your identity system.

AWS Systems Manager Session Manager replaces both. A small agent on the instance makes an outbound HTTPS connection to AWS, and when you run aws ssm start-session, AWS joins your terminal to that connection. Nothing listens on the internet. Who may connect is decided by IAM, each session start is recorded in CloudTrail, and you can keep a transcript of every shell in S3. There are no long-lived keys on the server to rotate or leak.

In this tutorial you give an existing Ubuntu 26.04 instance a role that Session Manager can use, open a shell through it, close port 22 for good, forward a port to a private database, copy files with scp, and turn on session logging. Each fence is labelled with where it runs: on your computer or on the instance.

This uses billable resources. The instance from the prerequisite keeps billing while it exists, and the S3 bucket bills for what it stores. Session Manager itself has no extra charge for EC2 instances, but check current pricing on the AWS Systems Manager pricing page. The last step removes everything this tutorial adds.

Step 1 · Install the Session Manager plugin

The AWS CLI hands the session to a separate program, session-manager-plugin, which it does not bundle. Install it from the AWS download location.

On your computer, Ubuntu or Debian on x86_64 (for an ARM machine, replace ubuntu_64bit with ubuntu_arm64):

Bash
cd "$(mktemp -d)"
curl -fsSLo session-manager-plugin.deb "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb"
sudo dpkg -i session-manager-plugin.deb

On your computer, macOS with Apple silicon (for an Intel Mac, replace mac_arm64 with mac):

Bash
cd "$(mktemp -d)"
curl -fsSLo session-manager-plugin.pkg "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac_arm64/session-manager-plugin.pkg"
sudo installer -pkg session-manager-plugin.pkg -target /
sudo mkdir -p /usr/local/bin
sudo ln -sf /usr/local/sessionmanagerplugin/bin/session-manager-plugin /usr/local/bin/session-manager-plugin

The Debian package is not in an apt repository, so apt upgrade will not update it. To upgrade later, download and install the package again; it always points at the latest release.

Check it worked

Bash
session-manager-plugin --version
aws --version

The first command prints a 1.2.x version number; if yours is old, install the latest package again. The second should show aws-cli/2.42.4 or newer. If the shell says command not found for the plugin, open a new terminal so it picks up the new file in your PATH.

Step 2 · Give the instance a role Session Manager can use

The agent on the instance needs AWS credentials to register itself. You give it those through an instance profile: an IAM role that EC2 is allowed to assume, wrapped so it can be attached to an instance. The AWS managed policy AmazonSSMManagedInstanceCore holds exactly the permissions the agent needs for sessions.

On your computer, set the instance ID (replace the example with yours) and make a working folder:

Bash
export INSTANCE_ID=i-0123456789abcdef0
mkdir -p ~/ssm-demo && cd ~/ssm-demo

Write the trust policy, which says that only the EC2 service may assume this role:

Bash
cat > ec2-trust.json <<'EOF'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

Create the role, attach the managed policy, wrap it in an instance profile and attach that to the instance:

Bash
aws iam create-role --role-name ssm-demo-ec2 --assume-role-policy-document file://ec2-trust.json
aws iam attach-role-policy --role-name ssm-demo-ec2 --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam create-instance-profile --instance-profile-name ssm-demo-ec2
aws iam add-role-to-instance-profile --instance-profile-name ssm-demo-ec2 --role-name ssm-demo-ec2
sleep 15
aws ec2 associate-iam-instance-profile --instance-id "$INSTANCE_ID" --iam-instance-profile Name=ssm-demo-ec2

The sleep gives IAM a moment to make the new profile visible to EC2; without it the last command can fail with an "invalid instance profile" error. If it does, run the last command again.

This tutorial needs an instance with no instance profile, because later steps and the clean-up all use the ssm-demo-ec2 role by name. If the instance already has a profile, associate-iam-instance-profile refuses: launch a fresh instance for this tutorial rather than changing a role other things may depend on.

Check it worked

Bash
aws ec2 describe-iam-instance-profile-associations \
  --filters Name=instance-id,Values="$INSTANCE_ID" \
  --query 'IamInstanceProfileAssociations[0].[State,IamInstanceProfile.Arn]' --output text

You see associated (or associating for a few seconds) followed by an ARN ending in instance-profile/ssm-demo-ec2.

Step 3 · Check the agent is running and registered

Canonical's Ubuntu AMIs ship the SSM Agent as a snap called amazon-ssm-agent. Confirm it is there while you can still log in with SSH. Use the same SSH command you use today.

On the instance:

Bash
sudo snap list amazon-ssm-agent
sudo snap services amazon-ssm-agent
sudo snap restart amazon-ssm-agent

The restart makes the agent fetch the new role's credentials straight away instead of on its next retry. If snap list says the snap is not installed, install it with sudo snap install amazon-ssm-agent --classic.

The agent only connects outwards, to ssm, ssmmessages and ec2messages endpoints for your Region on port 443. An instance in a public subnet with the default outbound rule reaches them already. An instance in a private subnet needs a NAT gateway or VPC interface endpoints for those three services.

Check it worked

On the instance, snap services shows the amazon-ssm-agent service as enabled and active.

On your computer, ask Systems Manager whether it can see the instance:

Bash
aws ssm describe-instance-information \
  --filters Key=InstanceIds,Values="$INSTANCE_ID" \
  --query 'InstanceInformationList[0].[PingStatus,PlatformName,AgentVersion]' --output text

You want Online, then Ubuntu and an agent version. None means the instance has not registered yet: wait two minutes and run it again. If it stays None after ten minutes, check the role from the previous step and the outbound route to port 443.

Step 4 · Start a shell and close port 22

On your computer:

Bash
aws ssm start-session --target "$INSTANCE_ID"

You get a prompt that says Starting session with SessionId: ... and then a $ sign. You are on the instance, logged in as a local account the agent created called ssm-user, which has sudo. Run a couple of commands to prove it, then leave:

Bash
whoami
hostname
exit

Now that a second way in is proven, remove the SSH rule. Do not do this before the session above worked, or you can lock yourself out. List the inbound rules for port 22 on the instance's security groups:

Bash
SG_ID=$(aws ec2 describe-instances --instance-ids "$INSTANCE_ID" \
  --query 'Reservations[0].Instances[0].SecurityGroups[0].GroupId' --output text)
aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG_ID" \
  --query 'SecurityGroupRules[?FromPort==`22` && !IsEgress].[SecurityGroupRuleId,CidrIpv4,CidrIpv6]' --output table

The table shows one row per SSH rule. Revoke each one by its ID (replace sgr-0abc... with the IDs from your table; if the instance has more than one security group, repeat for each):

Bash
aws ec2 revoke-security-group-ingress --group-id "$SG_ID" --security-group-rule-ids sgr-0abc1234def567890

SSH stays installed and running on the instance. It just no longer answers from the internet. Later steps reach it through the Session Manager tunnel.

Check it worked

Run the describe-security-group-rules command again: the table is empty. Your old ssh ubuntu@<public address> command now hangs and times out. aws ssm start-session --target "$INSTANCE_ID" still gives you a shell.

Step 5 · Forward a port to a private database

A database in a private subnet has no public address, so your laptop cannot reach it directly. The instance can. A port forwarding session to a remote host opens a port on your computer and sends everything through the instance to the database. The database does not need the agent.

This step assumes a PostgreSQL database, such as Amazon RDS, in the same VPC as the instance, whose security group allows port 5432 from the instance's security group. The instance from the EC2 launch tutorial sits in the default VPC, so it cannot reach a database built in its own VPC, like the one in the RDS tutorial. To use that database, run this step against an instance inside that VPC that the database already allows (the RDS tutorial's app instance, for example), after giving it this tutorial's role and checking its agent as in the earlier steps. If you have no such database yet, skip this step and come back to it.

On your computer, set the database endpoint (replace the example) and start the tunnel:

Bash
export DB_HOST=app-db.abcdefghijkl.eu-west-1.rds.amazonaws.com
aws ssm start-session --target "$INSTANCE_ID" \
  --document-name AWS-StartPortForwardingSessionToRemoteHost \
  --parameters "{\"host\":[\"$DB_HOST\"],\"portNumber\":[\"5432\"],\"localPortNumber\":[\"15432\"]}"

It prints Port 15432 opened for sessionId ... and Waiting for connections..., then stays in the foreground. Leave it running and open a second terminal.

On your computer, second terminal (on Ubuntu, install the client first with sudo apt install -y postgresql-client; on macOS, brew install libpq then brew link --force libpq, because Homebrew does not put libpq's psql on your PATH by itself):

Bash
psql "host=127.0.0.1 port=15432 dbname=app user=app sslmode=require"

Replace app with your database name and user. psql prompts for the password, so it never lands in your shell history.

Port forwarding sessions are not written to the session logs you set up later, because the data passes through as an encrypted stream. CloudTrail still records who started the session.

If you work from a mobile connection on prepaid data, a shell session uses very little. A forwarded port uses as much as the traffic you send through it, so a database dump through this tunnel costs the same data as the dump itself.

Check it worked

At the psql prompt, run \conninfo. It reports a connection to host 127.0.0.1 on port 15432 with SSL in use, and SELECT 1; returns one row. In the first terminal, the tunnel prints Connection accepted for session. Quit psql with \q and stop the tunnel with Ctrl+C.

Step 6 · Copy files with scp using a 60-second key

Session Manager can also carry an SSH connection, which is how you get scp, rsync and tools that only speak SSH. SSH still wants a key the instance trusts. Instead of keeping one in authorized_keys, push a public key with EC2 Instance Connect each time you connect. The instance accepts it for 60 seconds and then forgets it. EC2 Instance Connect comes preinstalled on Ubuntu 20.04 and later AMIs.

On your computer, make a key used only for this. It never goes into authorized_keys:

Bash
ssh-keygen -t ed25519 -f ~/.ssh/ssm-demo -N '' -C ssm-demo

Add a block to your SSH config. It matches any host name that looks like an instance ID, pushes the key, then opens the tunnel:

Bash
mkdir -p ~/.ssh && chmod 700 ~/.ssh
cat >> ~/.ssh/config <<'EOF'

# ssm-demo: SSH over Session Manager with a 60-second key
Host i-*
    User ubuntu
    IdentityFile ~/.ssh/ssm-demo
    IdentitiesOnly yes
    ProxyCommand sh -c "aws ec2-instance-connect send-ssh-public-key --instance-id %h --instance-os-user %r --ssh-public-key file://$HOME/.ssh/ssm-demo.pub >/dev/null && aws ssm start-session --target %h --document-name AWS-StartSSHSession --parameters portNumber=%p"
EOF

If you use a named AWS profile, run export AWS_PROFILE=<your profile> before connecting so both commands inside ProxyCommand use it.

Copy a file up and back:

Bash
echo "sent over Session Manager" > ~/ssm-demo/hello.txt
scp ~/ssm-demo/hello.txt "$INSTANCE_ID":/tmp/hello.txt
ssh "$INSTANCE_ID" 'cat /tmp/hello.txt && rm /tmp/hello.txt'

The first connection asks you to accept the host key. Type yes. Each later ssh or scp pushes a fresh copy of the key, so the 60-second window only has to cover the login, not the whole session.

Your IAM user needs ec2-instance-connect:SendSSHPublicKey for this, alongside the Session Manager permissions. Administrators already have both.

Check it worked

scp shows hello.txt at 100%, and the ssh command prints sent over Session Manager. Then, on your computer, run ssh "$INSTANCE_ID" 'cat ~/.ssh/authorized_keys'. This logs in as ubuntu and prints that account's stored keys: none of the lines ends in ssm-demo, because the key was never stored there.

Step 7 · Record shell sessions to S3

Session Manager can save a transcript of every shell session to an S3 bucket when the session ends. Session preferences live in a Systems Manager document called SSM-SessionManagerRunShell, one per Region.

On your computer, create a private bucket. New buckets block public access and encrypt objects with SSE-S3 by default, which session logging needs:

Bash
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
REGION=$(aws configure get region)
export LOG_BUCKET="ssm-demo-logs-$ACCOUNT_ID-$REGION"
aws s3 mb "s3://$LOG_BUCKET"

Let the instance role write to one prefix in that bucket and nothing else:

Bash
cat > s3-logs-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::$LOG_BUCKET/ssm-sessions/*"
    },
    {
      "Effect": "Allow",
      "Action": "s3:GetEncryptionConfiguration",
      "Resource": "*"
    }
  ]
}
EOF
aws iam put-role-policy --role-name ssm-demo-ec2 --policy-name ssm-demo-session-logs --policy-document file://s3-logs-policy.json

Write the preferences and apply them. This also ends idle sessions after 20 minutes:

Bash
cat > session-prefs.json <<EOF
{
  "schemaVersion": "1.0",
  "description": "Session Manager preferences",
  "sessionType": "Standard_Stream",
  "inputs": {
    "s3BucketName": "$LOG_BUCKET",
    "s3KeyPrefix": "ssm-sessions",
    "s3EncryptionEnabled": true,
    "idleSessionTimeout": "20"
  }
}
EOF
aws ssm update-document --name SSM-SessionManagerRunShell \
  --content file://session-prefs.json --document-version '$LATEST'

If update-document says the document does not exist, your account has never saved Session Manager preferences in this Region. Create it instead:

Bash
aws ssm create-document --name SSM-SessionManagerRunShell \
  --content file://session-prefs.json --document-type Session

The setting applies to every Session Manager shell in this account and Region, not only this instance.

Check it worked

Start a session, type something you will recognise, and end it:

Bash
aws ssm start-session --target "$INSTANCE_ID"

At the instance prompt, run echo ssm-demo-log-check, then exit. Back on your computer, wait a minute and list the prefix:

Bash
aws s3 ls "s3://$LOG_BUCKET/ssm-sessions/"

You see an object named something like <your user>-0a1b2c3d4e5f.log. Print it with aws s3 cp "s3://$LOG_BUCKET/ssm-sessions/<object name>" - and find the ssm-demo-log-check line in the transcript.

Step 8 · Remove what this tutorial added

Do this when you are finished, or keep the role and the closed port and skip to the last two commands if you want to go on using Session Manager.

Warning: the next command removes the logging preference for every Session Manager session in this Region. If your account had preferences before this tutorial, put those back instead.

On your computer:

Bash
cd ~/ssm-demo
cat > session-prefs-reset.json <<'EOF'
{
  "schemaVersion": "1.0",
  "description": "Session Manager preferences",
  "sessionType": "Standard_Stream",
  "inputs": {
    "s3BucketName": "",
    "s3EncryptionEnabled": false
  }
}
EOF
aws ssm update-document --name SSM-SessionManagerRunShell \
  --content file://session-prefs-reset.json --document-version '$LATEST'

Warning: --force deletes every object in the bucket, including the session transcripts. Check that $LOG_BUCKET is the bucket you made above before you run it.

Bash
echo "$LOG_BUCKET"
aws s3 rb "s3://$LOG_BUCKET" --force

Warning: once the role is detached, Session Manager can no longer reach the instance, and port 22 is closed, so the instance has no way in. Before you run the next block, decide: if you still need the instance, add your SSH rule back first, as in the EC2 launch tutorial; if you do not, plan to terminate it as that tutorial's last step shows, because it bills until you do.

Detach the instance profile and delete the role:

Bash
ASSOC_ID=$(aws ec2 describe-iam-instance-profile-associations \
  --filters Name=instance-id,Values="$INSTANCE_ID" \
  --query 'IamInstanceProfileAssociations[0].AssociationId' --output text)
aws ec2 disassociate-iam-instance-profile --association-id "$ASSOC_ID"
aws iam remove-role-from-instance-profile --instance-profile-name ssm-demo-ec2 --role-name ssm-demo-ec2
aws iam delete-instance-profile --instance-profile-name ssm-demo-ec2
aws iam delete-role-policy --role-name ssm-demo-ec2 --policy-name ssm-demo-session-logs
aws iam detach-role-policy --role-name ssm-demo-ec2 --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam delete-role --role-name ssm-demo-ec2

Finally, remove the local files: delete the # ssm-demo block from ~/.ssh/config in your editor, then:

Bash
rm -f ~/.ssh/ssm-demo ~/.ssh/ssm-demo.pub
rm -rf ~/ssm-demo

Check it worked

aws iam get-role --role-name ssm-demo-ec2 fails with NoSuchEntity, aws s3 ls "s3://$LOG_BUCKET" fails with NoSuchBucket, and ls ~/.ssh/ssm-demo* finds nothing.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.