Is it possible to SSH into FARGATE managed container instances?

Viewed 55341
5 Answers

Starting from the middle of March 2021, executing a command in the ECS container is possible when the container runs in AWS Fargate. Check the blog post Using Amazon ECS Exec to access your containers on AWS Fargate and Amazon EC2.

Quick checklist:

  1. Enable command execution in the service.
  2. Make sure to use the latest platform version in the service.
  3. Add ssmmessages:.. permissions to the task execution role.
  4. Force new deployment for the service to run tasks with command execution enabled.

AWS CLI command to run bash inside the instance:

aws ecs execute-command  \
    --region eu-west-1 \
    --cluster [cluster-name] \
    --task [task id, for example 0f9de17a6465404e8b1b2356dc13c2f8] \
    --container [container name from the task definition] \
    --command "/bin/bash" \
    --interactive

The setup explained above should allow to run the /bin/bash command and get an interactive shell into the container running on AWS Fargate. Please check the documentation Using Amazon ECS Exec for debugging for more details.

It is possible, but not easy.straight forward. Shortly: install SSH, don't expose ssh port out from VPC, add bastion host, SSH through bastion.

A little bit more details:

  • spin up SSHD with password-less authentication. Docker instructions
  • Fargate Task: Expose port 22
  • Configure your VPC, instructions
  • create EC2 bastion host
  • From there SSH into your Task's IP address

Here is an example of adding SSH/sshd to your container to gain direct access:

# Dockerfile
FROM alpine:latest

RUN apk update && apk add --virtual --no-cache \
  openssh

COPY sshd_config /etc/ssh/sshd_config

RUN mkdir -p /root/.ssh/
COPY authorized-keys/*.pub /root/.ssh/authorized_keys
RUN cat /root/.ssh/authorized-keys/*.pub > /root/.ssh/authorized_keys
RUN chown -R root:root /root/.ssh && chmod -R 600 /root/.ssh

COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
RUN ln -s /usr/local/bin/docker-entrypoint.sh /

# We have to set a password to be let in for root - MAKE THIS STRONG.
RUN echo 'root:THEPASSWORDYOUCREATED' | chpasswd

EXPOSE 22
ENTRYPOINT ["docker-entrypoint.sh"]
# docker-entrypoint.sh
#!/bin/sh

if [ "$SSH_ENABLED" = true ]; then
  if [ ! -f "/etc/ssh/ssh_host_rsa_key" ]; then
    # generate fresh rsa key
    ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
  fi
  if [ ! -f "/etc/ssh/ssh_host_dsa_key" ]; then
    # generate fresh dsa key
    ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa
  fi

  #prepare run dir
  if [ ! -d "/var/run/sshd" ]; then
    mkdir -p /var/run/sshd
  fi

  /usr/sbin/sshd

  env | grep '_\|PATH' | awk '{print "export " $0}' >> /root/.profile
fi

exec "$@"

More details here: https://github.com/jenfi-eng/sshd-docker

Related