[AWS]Fargate SSH접근

Ronie🌊·2021년 7월 23일
1

AWS

목록 보기
3/3
post-thumbnail

FargateSSH



개요

  • ECS Fargate에서 실행되고 있는 작업에 SSH접근을 해보기
    • 흔한 ubuntu이미지에 openssh-server를 설치하고 생성한 ssh공개키를 복붙하여 설정하고, 이미지를 ECR로 업로드하고 Fargate의 작업생성을 하여 RUN되고 있는 Fargate의 Public ip에 ssh보안키를 사용해 ssh접속을 할 수 있게 한다.
  • https://medium.com/ci-t/9-steps-to-ssh-into-an-aws-fargate-managed-container-46c1d5f834e2

준비

SSH 키 생성

ssh-keygen -t rsa
  • 생성된 id_rsa.pub의 내용 복사(추후 필요)

SSH 접근 가능 Docker 이미지 빌드

  • ubuntu기반
  • openssh-server설치
  • ssh 공개키
  • Dockerfile
FROM ubuntu:latest

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

EXPOSE 22

COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
  • docker-entrypoint.sh
#!/bin/sh
#SSH_PUBLIC_KEY=생성된 id_rsa.pub의 내용 복사부분(AWS Systems Manager Parameter Store에 저장해놓고 끌어오거나 그게 아니라면 직접 적용해줄 수 도있다.)
if [ -z "$SSH_PUBLIC_KEY" ]
then
  echo "Need your SSH public key as the SSH_PUBLIC_KEY env variable."
  exit 1
fi

# Create a folder to store user's SSH keys if it does not exist.
USER_SSH_KEYS_FOLDER=~/.ssh
[ ! -d "$USER_SSH_KEYS_FOLDER" ] && mkdir -p $USER_SSH_KEYS_FOLDER

# Copy contents from the `SSH_PUBLIC_KEY` environment variable
# to the `${USER_SSH_KEYS_FOLDER}/authorized_keys` file.k
# The environment variable must be set when the container starts.
echo $SSH_PUBLIC_KEY > ${USER_SSH_KEYS_FOLDER}/authorized_keys

# Clear the `SSH_PUBLIC_KEY` environment variable.
unset SSH_PUBLIC_KEY

# Start the SSH daemon.
/usr/sbin/sshd -D

ECR 업로드

  • 생성한 DockerImage를 AWS ECR로 업로드
  1. AWS ECR Repository설정

    https://ap-northeast-2.console.aws.amazon.com/ecr/repositories?region=ap-northeast-2

  2. AWS ECR에 로그인

// aws configure 사전 등록 완료할 것
// 명령어
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin ${AWS ECR Repository URL}
// 예시
aws ecr get-login-password --region ap-northeast-2 | docker login --username AWS --password-stdin 762202190844.dkr.ecr.ap-northeast-2.amazonaws.com/fargate-ssh
  1. AWS ECR에 도커이미지 추가
// 명령어1(docker repository 복사, 이름변경)
docker tag ${REPOSITORY}:${TAG} ${AWS ECR Repository URL}:${TAG}
docker tag info/m2sj/camel-ose-springboot-xml:latest 762202190844.dkr.ecr.ap-northeast-2.amazonaws.com/test-fargate-efs
docker tag sshawsfargate:1.0.0 762202190833.dkr.ecr.ap-northeast-2.amazonaws.com/test0713-fargatessh
docker tag docker-ssh-aws-fargate4:latest 762202190844.dkr.ecr.ap-northeast-2.amazonaws.com/fargate-ssh
// 명령어2(docker images 새롭게 만들어진 image의 repository를 사용)
docker push ${REPOSITORY}:${TAG}
docker push 762202190844.dkr.ecr.ap-northeast-2.amazonaws.com/fargate-ssh

ECS 클러스터 생성

  • 클러스트 생성
    • 네트워킹 전용
    • 클러스터 이름 : cluster-FargateEFS
    • VPC생성, subnet2개 생성
      • VPC이름 설정(vpc-FargateEFS)
      • 보안그룹 자동생성(인바운드 모든 트래픽 허용 + ssh 22포트 허용)
    • ECS작업정의
      • Fargate
      • 작업 이름 정의
      • 메모리 정의
      • 컨테이너 추가(테스트용 컨테이너)
      • 볼륨
{
  "executionRoleArn": "arn:aws:iam::account-id:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "portMappings": [
        {
          "hostPort": 22,
          "protocol": "tcp",
          "containerPort": 22
        }
      ],
      "secrets": [
        {
          "valueFrom": "arn:aws:ssm:region:account-id:parameter/parameter-name",
          "name": "SSH_PUBLIC_KEY"
        }
      ],
      "image": "account-id.dkr.ecr.region.amazonaws.com/ssh-public-key:latest",
      "name": "ssh-public-key-container"
    }
  ],
  "memory": "1024",
  "family": "fargate-ssh-public-key",
  "requiresCompatibilities": [
    "FARGATE"
  ],
  "networkMode": "awsvpc",
  "cpu": "512"
}

RUN TASK

  • 클러스터에서 작업 시작
  • RUNNING 상태확인 후 Public IP 주소 확인

SSH 접속

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

주의점

  • ssh 공개키, 보안키의 구분
    • 공개키를 image에 적용하고 ssh접근할때 보안키를 사용한다.
  • .sh파일의 저장형식
    • 저장형식에 따라서 linux운영체제가 받아들이는게 다른듯
    • windows에서는 기본적으로 CRLF로 되어있지만 이를 인식못하는 경우, LF로 형식변환하여 처리.

0개의 댓글