How to ssh into aws farget container?

Create a docker file

First of all create a docker file and install ssh server. Open port 22 so that we can ssh into the container.

FROM ubuntu:18.04

# Install openssh server
RUN apt-get update \
    && apt-get install -y openssh-server \
    && mkdir -p /var/run/sshd

EXPOSE 22

# create docker entrypoint file and assign permissions
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

ENTRYPOINT ["docker-entrypoint.sh"]

Create docker entrypoint script

Next, we need to create docker entrypoint script. This script basically relay on env variable SSH_PUBLIC_KEY. If we have this env variable passed we will add this key to our authorized key list.

#!/bin/sh

if [ -z "$SSH_PUBLIC_KEY" ]; then
  echo "Undefined env var: SSH_PUBLIC_KEY."
  exit 1
fi

# create ssh folder
USER_SSH_KEYS_FOLDER=~/.ssh
[ ! -d "$USER_SSH_KEYS_FOLDER" ] && mkdir -p $USER_SSH_KEYS_FOLDER

# add ssh key to authorized key
echo $SSH_PUBLIC_KEY > ${USER_SSH_KEYS_FOLDER}/authorized_keys

# remove env var
unset SSH_PUBLIC_KEY

# start sshd deamon
/usr/sbin/sshd -D

Build Image

Now, build this image and push to aws ECR.

# build docker image and tag it
docker tag -t test-image:latest .

# use following syntax on your terminal to connect your ECR Repo
# change parameter in square bracket to meet your need
aws ecr get-login-password --region [region] | docker login --username AWS --password-stdin [aws_account_id.dkr.ecr.region.amazonaws.com]

# tag the image
docker tag [test-image] [aws_account_id.dkr.ecr.region.amazonaws.com/my-repository:tag]

# push the image to ecr
docker push [aws_account_id.dkr.ecr.region.amazonaws.com/my-repository:tag]

Get your local public ssh key

In order to access aws farget container from your local computer you need to get your public ssh key. Copy the public key using following command.

cat ~/.ssh/id_rsa.pub

Create env var in farget task

You can read this article to create a new env variable for your aws farget container: Https://Docs.Aws.Amazon.Com/AmazonECS/Latest/Developerguide/Taskdef-Envfiles.Html. Make sure to add your public ssh key you copied as SSH_PUBLIC_KEY env variable.

Re-create your farget task

Stop the current task and re-create a new task with env variable updated. You can now ssh into the newly created container. Grab the public IP address of your task and run following command on your local computer.

ssh -i ~/.ssh/id_rsa root@ip-address-of-task