2021 전국기능경기대회 2과제 풀이

PHYYOU·2022년 8월 14일
0

2021 전국기능경기대회 2과제

1. 네트워킹

  • VPC 생성
  • 서브넷 생성
  • 인터넷 게이트웨이 생성
  • 라우팅 테이블 생성
  • NAT Gateway 생성
  • 라우팅 테이블 서브넷 연결 편집
  • 라우팅 테이블 NAT Gateway, Internet Gateway 연결

Bastion Instance 생성

  • wsi-public-a 서브넷에 PowerUser Role 만들어서 연결 후 생성
  • 좀있다 만들 EC2 생성 스크립트에서 IAM Policy 연결할 때 PowerUserPolicy로는 부족해서 IAM Attach 권한 Policy도 직접 생성해서 Role에 연결
  • aws configure로 default region 설정, jq, curl 설치
  • docker도 설치

2. EC2 생성 스크립트

  • EC2용 보안 그룹 생성

  • CodeDeploy용 IAM Role 생성

  • ALB 생성 후 targe group 생성

  • /opt/ec2_launch.sh 에 제작.
    원래는 alb target group register가 codedeploy에 의해 이루어져야 하나 잘 안돼서 register target을 ec2 생성할 때부터 함

#!/bin/bash

Id=$(aws ec2 run-instances \
    --image-id ami-01cd604f66eeb80a1 \
    --count 1 \
    --instance-type t3.small \
    --key-name wsi-keypair \
    --security-group-ids sg-085c8edb70a0de357 \
    --subnet-id subnet-02d837315e9db8ade \
    --iam-instance-profile 'Arn=arn:aws:iam::492622758225:instance-profile/wsi-api' \ # iam role
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$1},{Key=wsi:deploy:group,Value=dev-api}]" | jq -r .Instances[0].InstanceId)
echo $Id

while true
do
    if aws elbv2 register-targets \
        --target-group-arn arn:aws:elasticloadbalancing:ap-northeast-2:492622758225:targetgroup/wsi-api-tg/0729c5f32c4ab990 \
        --targets Id=$Id ; then # target group registration
        echo "alb target group register succeeded"
        break
    else
        echo "alb target group register failed, please waiting register to target group"
    fi
done

CodeCommit

  • CodeCommit에 wsi-api-repo 생성
  • 이 구조로 repository 구성
  wsi-api-repo
  ├── scripts
  │   ├── install_dependencies
  │   ├── start_server
  │   └── stop_server
  ├── src
  │   └── app.py
  ├── appspec.yml
  ├── buildspec.yml
  └── Dockerfile
  • scripts
    - install_dependencies
#!/bin/bash

yum update -y
yum install -y docker
service docker start
usermod -aG docker ec2-user
chmod 777 /var/run/docker.sock 

FILE=/home/ec2-user/.aws/config
if [ -f "$FILE" ]; then
    echo "$FILE exists."
else 
    echo "$FILE does not exist. Crate directory"
    mkdir /home/ec2-user/.aws
fi
cat << EOF > /home/ec2-user/.aws/config
[default]
region = ap-northeast-2
EOF
  • start_server
#!/bin/bash

docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)  

$(aws ecr get-login --no-include-email)
aws ecr describe-images --repository-name wsi-api-ecr | docker pull 492622758225.dkr.ecr.ap-northeast-2.amazonaws.com/wsi-api-ecr:$(jq -r .imageDetails[0].imageTags[0])
aws ecr describe-images --repository-name wsi-api-ecr | docker run -d --name=app -p 80:80 492622758225.dkr.ecr.ap-northeast-2.amazonaws.com/wsi-api-ecr:$(jq -r .imageDetails[0].imageTags[0])  
  • stop_server
#!/bin/bash

isExistApp = `pgrep docker`
if [[ -n  $isExistApp ]]; then
    docker stop $(docker ps -a -q)
    docker rm $(docker ps -a -q)  
fi
  • src
    - app.py: 배포자료
  • Dockerfile
FROM python:3.9-slim-buster

# set a directory for the app
WORKDIR /app

# copy all the src files to the container
COPY ./src .

# install dependencies
RUN pip install flask

# tell the port number the container should expose
EXPOSE 80

# run the command
CMD ["python", "./app.py"]
  • appspec.yml
  version: 0.0
  os: linux
  hooks:
    BeforeInstall:
      - location: scripts/install_dependencies
        timeout: 300
        runas: root
      - location: scripts/start_server
        timeout: 300
        runas: ec2-user
    ApplicationStop:
      - location: scripts/stop_server
        timeout: 300
        runas: ec2-user

  • buildspec.yml - buildspec에 sed 명령어가 있는 이유는 CodeCommit 콘솔을 직접 이용해서 appspec 스크립트를 만들었더니 Linux 환경에서 ^M Bad Interpreter Error가 나 어쩔수 없이 추가함.
  version: 0.2

  artifacts:
    files:
      - appspec.yml
      - scripts/*
      - 
  phases:
    pre_build:
      commands:
        - echo Logging in to Amazon ECR...
        - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
    build:
      commands:
        - TZ='Asia/Seoul'
        - IMAGE_TAG=$(date +"%y%m%d%H%M%S")
        - echo Build started on $IMAGE_TAG
        - echo Building the Docker image...          
        - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
        - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG      
        - sed -i 's/\r$//' scripts/install_dependencies
        - sed -i 's/\r$//' scripts/start_server
        - sed -i 's/\r$//' scripts/stop_server

    post_build:
      commands:
        - echo Build completed on `date`
        - echo Pushing the Docker image...
        - docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG
  • release branch 만들고 끝

CodeBuild

  • CodeCommit에 만든 buildspec이 CodeBuild 내용.
  • IAM Role은 자동생성 되긴 하나 ECR Build 권한이 없을 때가 있었음.
  • 자동생성 안되는 ECR Build Policy 추가
  • buildspec에 phase마다 있던 환경변수 지정해서 생성
    - IMAGE_REPO_NAME
    - AWS_ACCOUNT_ID
    - AWS_DEFAULT_REGION
  • 본인은 이렇게 3가지를 사용했음
  • Release Branch용 Build 프로젝트도 생성

CodeDeploy

  • CodeDeploy에서 요구하는 IAM Role 생성(콘솔에서 작업시 AWS에서 자동 생성함)
  • inplace 배포로 default at all 구성으로 생성하면 끝

ECR

  • 앞선 buildspec과 appspec의 script를 보면 알겠듯이 ECR wsi-api-ecr 이름으로 private 레포지토리 생성

CodePipeline

  • 앞서 만들었던 3가지 Step(Source: Commit, Build, Deploy) 를 설정해서 시작하면 끝!
profile
박효영

0개의 댓글