Github Actions CI/CD

Twoeyes·2024년 12월 12일
0

아 이건 전에 한번 해봤다.

Github Actions

저 빨간 박스가 Github Actions 이다.

EC2 22, 80 열고 아무거나 하나 생성.

OK

1. Repo 생성 및 git 세팅

  • Repo 생성

  • 토큰 뽑기

난 실습 이후 내 노트북에서도 쓰려고 그냥 expire 제한을 풀었다.

#
GITUSER=btwoeyes

git clone https://github.com/$GITUSER/cicd-2w.git
tree cicd-2w/
cp server.py cicd-2w/
cd cicd-2w/

#
git status
git add .
git commit -m "first commit"
git push origin main
Username for 'https://github.com': btwoeyes$
Password for 'https://gasida@github.com': <토큰값>

CI/CD가 왜 필요한가?

push 이후, 파일 배포까지 많은 과정이 있다.
목표는 공수의 감소. 인력으로 하는 행위를 줄이고, 휴먼 에러를 없애는 것이 목표이다
최근 맡고있는 사업 진행하면서, 손 배포해봤는데, 눈 빠진다. 옆에서 이사님의 불만이 쏟아지신다. ㅋㅋ 자동화 배워보자.

push 하면 자동 배포 Actions 추가

먼저 github Repo에 Secret을 추가한다.

대상 : SSH_PRIVATE_KEY, EC2_PIP

로컬(Ec2말고)에 actions workflows 정의 파일 생성하기.

.github/workflows/deploy.yaml을 생성한다.
workflows여야만 한다.(workflow안된다.)

이거 깃헙 페이지에서도 가능함.
#
git clone https://github.com/gasida/cicd-2w.git
cd cicd-2w

#
mkdir -p .github/workflows/
touch .github/workflows/deploy.yaml

sed -i -e "s/CICD/CICD 2w/g" server.py

나는 Amazon-Linux 2023에서 진행했다. 그래서 ubuntu를 ec2-user로 변경했다.
별 내용 없으므로, ubuntu-latest는 특이사항 없음.

name: CICD1
on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Configure the SSH Private Key Secret
        run: |
          mkdir -p ~/.ssh/
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa

      - name: Set Strict Host Key Checking
        run: echo "StrictHostKeyChecking=no" > ~/.ssh/config

      - name: Git Pull
        run: |
          export MY_HOST="${{ secrets.EC2_PIP }}"
          ssh ec2-user@$MY_HOST << EOF
            cd /home/ubuntu/cicd-2w || exit 1
            git pull origin main || exit 1
          EOF

      - name: Run service
        run: |
          export MY_HOST="${{ secrets.EC2_PIP }}"
          ssh ec2-user@$MY_HOST sudo fuser -k -n tcp 80 || true
          ssh ec2-user@$MY_HOST "nohup sudo -E python3 /home/ec2-user/cicd-2w/server.py > /home/ec2-user/cicd-2w/server.log 2>&1 &"

Git push

git add . && git commit -m "add workflow" && git push origin main

서버에서(Ec2) 로그 확인

# [서버1]
cd cicd-2w/
grep -i cicd server.py
sudo ps -ef |grep server.py
tail /home/ubuntu/cicd-2w/server.log

에러 발생 현황

  1. ec2-user에 인증 정보가 등록되지 않았다.
git config --global credential.helper store
git push origin main

      위 명령어를 통해 credential을 영구적으로 서버에 등록했다.

  1. 편의상 root로 하다가 디렉터리 권한 문제가 발생...할 뻔했으나, 위 문제 해결하다가 어? 하고 다 ec2-user로 바꿨다.

Github Actions?

Github Actions에서 돌아가는 파이썬은 정체가 뭐야?

  • 버전, 파이썬 경로, 환경변수 확인
# /home/ymw/1.2/cicd-2w/.github/workflows/deploy.yaml 수정
name: CICD2
on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  deployfinal:
    runs-on: ubuntu-latest
    steps:
      - name: Test
        run: |
          python -V || true
          python3 -V || true
          which python || true
          which python3 || true
          env

.gitignore를 통해 제외된 민감 파일 내용을 안전하게 가져와서 사용하기

  • 예시 : Secret 생성
ACCESSKEY : asdf1234
SECRETKEY : qwer1234

  • Marketplaces 확인

https://github.com/appleboy/ssh-action

  • 워크플로우 수정(/home/ymw/1.2/cicd-2w/.github/workflows/deploy.yaml)
name: CICD2
on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  ssh-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Github Repository Checkout
        uses: actions/checkout@v4

      - name: executing remote ssh commands
        uses: appleboy/ssh-action@v1.2.0
        env:
          AWS_KEYS: ${{ secrets.MYKEYS }}
        with:
          host: ${{ secrets.EC2_PIP }}
          username: ec2-user
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          envs: AWS_KEYS
          script_stop: true
          script: |
             cd /home/ec2-user/cicd-2w
             echo "$AWS_KEYS" > .env

ssh-action이라는 job을 이용해 Github에 등록된 Secret을 원격지 서버에 echo를 동작시킴으로서, .env파일을 만들었다!!

scp 를 이용한 파일 복사

name: CICD2
on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  scp-ssh-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Github Repository Checkout
        uses: actions/checkout@v4

      - name: executing remote ssh commands
        uses: appleboy/ssh-action@v1.2.0
        env:
          AWS_KEYS: ${{ secrets.MYKEYS }}
        with:
          host: ${{ secrets.EC2_PIP }}
          username: ec2-user
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          envs: AWS_KEYS
          script_stop: true
          script: |
            cd /home/ec2-user/cicd-2w
            echo "$AWS_KEYS" > .env
            sudo fuser -k -n tcp 80 || true

      - name: copy file via ssh
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.EC2_PIP }}
          username: ec2-user
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          source: server.py
          target: /home/ec2-user/cicd-2w

선정했던, server.py가 바로 배포되었다.

변경된 py파일 배포하고, 서비스 재기동

  • server.py 수정
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from datetime import datetime

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.end_headers()
        now = datetime.now()
        response_string = now.strftime("The time is %-I:%M:%S %p, CICD2 End\n")
        self.wfile.write(bytes(response_string, "utf-8")) 

def startServer():
    try:
        server = ThreadingHTTPServer(('', 80), RequestHandler)
        print("Listening on " + ":".join(map(str, server.server_address)))
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()

if __name__== "__main__":
    startServer()
  • deploy.yaml 파일 수정
name: CICD2
on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Github Repository Checkout
        uses: actions/checkout@v4

      - name: copy file via ssh
        uses: appleboy/scp-action@v0.1.7
        with:
          host: ${{ secrets.EC2_PIP }}
          username: ec2-user
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          source: server.py
          target: /home/ec2-user

      - name: executing remote ssh commands
        uses: appleboy/ssh-action@v1.2.0
        env:
          AWS_KEYS: ${{ secrets.MYKEYS }}
        with:
          host: ${{ secrets.EC2_PIP }}
          username: ec2-user
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          envs: AWS_KEYS
          script_stop: true
          script: |
            cd /home/ec2-user/cicd-2w
            echo "$AWS_KEYS" > .env
            sudo fuser -k -n tcp 80 || true
            rm server.py
            cp /home/ec2-user/server.py ./
            nohup sudo -E python3 /home/ec2-user/cicd-2w/server.py > /home/ec2-user/cicd-2w/server.log 2>&1 &
            echo "test" >> /home/ec2-user/text.txt

스크립트를 보면, server.py를 삭제하고, 복사해서 넣고, python3를 동작시킨다.

git add . && git commit -m "Deploy CICD2 Final" && git push origin main

profile
아 배고파

0개의 댓글