터칭 데이터

Docker & K8S - Github Actions 사용 # 1 본문

Docker & K8S

Docker & K8S - Github Actions 사용 # 1

터칭 데이터 2023. 12. 19. 23:36

 

학습 목표

 

CI/CD의 개념과 가장 많이 사용되는 소스 컨트롤 시스템

 

Git과 Github에 대해 알아보고 Github이 제공하는 CI/CD 서비스인

 

Github Actions에 대해 알아보려 합니다.

 

 

이렇게 배운 개념들을 바탕으로

1. Github Actions로 Hangman 코드에 테스트를 붙이는 실습

 

2. Github Actions를 통해 Docker Image를 만들고 Docker hub에 push하는 실습

 

2개의 실습을 하려합니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1. Github Actions로 Hangman 코드에 테스트를 붙이는 실습

정확하게는 테스트이외에도 문법 에러코딩 스타일 이슈까지도 체크하는 스텝을 추가하겠습니다.

 

 

 

 

 

 

 

 

 

 

 

 

시작하기 전에

 

먼저 learndataeng/hangman_web repo를 본인의 Github 어카운트로 fork 

여기에 앞서 만든 Dockerfile도 있어야함! (두 번째 실습에서 필요: Docker Image 생성에서 필요)
여기에 보면 test.py가 있고 여기에 unittest 모듈을 이용한 테스트 코드가 존재 (Python에는 pytest나 unittest라는 test를 위한 라이브러리가 존재)

 

Github Actions를 통해 main 브랜치에 push나 PR이 있는 경우 test.py를 실행할 예정

하나의 repo에 대해 다수의 workflow들이 존재 가능
모두 .github/workflows/ 밑에 yml 파일 형태로 존재

 

 

 

 

 

 

 

 

 

 

 

 

사용해볼 CI Template: Python Application

CI의 기본적인 뼈대를 제공해 CI 작성을 쉽게 시작하도록 도와줍니다.

 

 

 

Python Application이란 CI Template을 사용할 예정

테스트 코드 실행 이외에도 flake8을 사용해서 코딩 스타일을 체크해볼 예정

 

기본으로 pytest를 테스트 프레임웍으로 설치 -> 우리는 unittest로 작성되어 있음

pytest를 unittest로 바꿔야 하는데 내용이 크게 달라지지는 않습니다.

 

Python code linting tool으로 flake8을 설치하고 문법 에러와 코딩 스타일 체크

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

파이썬 코드 스타일 체크 - flake8

 

파이썬 코드에서 에러나 코딩 스타일 등에서 이슈를 체크해주는 툴

이런 툴을 Linting tool이라 부름 (언어별로 존재)

 

보통 명령의 모양은 아래와 같습니다.
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics

코드 한줄의 최대 길이는 127 등등..

 

 

 

sample.py

import random

def lower(a)
    return a.lower()

lower("aBC") # 테스트 출력 예

 

def lower(a) 뒤에 콜론(:)이 빠져 있습니다.

 

 

 

$ flake8 sample.py
sample.py:3:12: E999 SyntaxError: invalid syntax

 

이 때 flake8 sample.py를 실행하면 sample.py 파일의 3번 라인 12번째 글자가 잘못 되었다고 얘기해줍니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

테스트 코드 소개


테스트 소스 코드  (hangman_web의 test.py)

unittest를 사용 (pytest라는 대안도 있음)


테스트 코드 실행

python3 test.py 혹은 python3 -m unittest test.py(unittest 모듈을 test.py에게 실행시켜라)

 

전자는 main 메서드가 정해진 경우, 후자는 메인 메서드가 정해지지 않은 경우에 사용합니다.

 

test.py는 아래와 같이

"""Unit test cases for hangman game."""
import unittest
import app as hangman


class HangmanTestCase(unittest.TestCase):

    # def setUp(self):
    #

    # checkCorrectAnswer(correctLetters, secretWord)
    def test_checkCorrectAnswer(self):
        answer = hangman.checkCorrectAnswer("baon", "baboon")
        self.assertTrue(answer)

    def test_checkWrongAnswer(self):
        answer = hangman.checkWrongAnswer("zebrio", "zebra")
        self.assertTrue(answer)

    def test_1(self):
        answer = hangman.checkCorrectAnswer("bazn", "baboon")
        self.assertFalse(answer)

    def test_2(self):
        answer = hangman.checkCorrectAnswer("", " ")
        self.assertFalse(answer)

    def test_3(self):
        answer = hangman.checkCorrectAnswer("ZEBRA", "zebra")
        self.assertFalse(answer)


if __name__ == "__main__":
    unittest.main()
Ran 5 tests in 0.000s
OK

 

 

main method가 정해져 있고 메인 메서드가 실행될 때 파일안의 테스트 코드들을 전부 실행시키게 되어 있어 두 방법 모두 사용 가능합니다.

 

 

 

 

 

 

 

 

 

 

 

 

작업 Repo에서 Actions 탭 선택

 

https://github.com/learndataeng/hangman_web 을 fork한 본인의 hangman_web Repo로 이동

 

 

fork 방법은 위와 같습니다.

 

 

 

 

 

 

 

 

 

CI Templates에서 Python Application 선택

 

 

찾을 수 없다면 검색창에서 검색하시거나 밑으로 스크롤을 쭉 내리신 뒤 continuous integration에서 view all을 클릭하고 찾으셔도 좋습니다.

 

Python application을 찾았다면 Configure를 클릭합니다.

 

 

 

 

 

 

 

 

 

 

 

.github/workflows/python-app.yml 편집

 

 

 

그러면 repo이름/.github/workflows/ 밑에 yml 파일이 자동으로 생성됩니다.

 

on에 어떤 Events로 workflow(Github actions)가 트리거될지 정할 수 있습니다. 현재는 main 브랜치로의 push와 pull_request인 경우가 디폴트로 정해져있습니다.

 

 

 

 

 

 

 

 

 

 

 

 

그런데 yaml 파일이 뭔지 알아볼까요?

잠깐! yml (or yaml) 파일 포맷: 환경설정 파일에 많이 쓰임

# Comments start with a #

# Key-value pairs are separated by a colon and a space
name: John Doe
age: 30

# Lists are denoted by a hyphen and a space
hobbies:
 - reading
 - hiking

# Nested key-value pairs are indented with two spaces
contact:
 email: john.doe@example.com
 phone:
 home: 555-1234
 work: 555-5678

# multi-line string
description: |
 This is a
 multi-line
 string

 

JSON으로 표현가능한 것은 Yaml로도 표현 가능합니다. JSON과 사실상 동일하며 이들간의 변환도 가능합니다. yaml이 JSON보다 타이핑이 적다는 차이가 있습니다.

 

#로 표시된 Comment는 꼭 읽어 주세요.

 

 

 

 

 

 

 

 

 

잠깐! JSON to YAML: https://www.json2yaml.com/

 

{
 “course”: “Docker & K8s”,
 “company”: “Grepp”,
 “price”: 0,
 “tags”: [“software”, “devops”],
 “author”: {
 “first_name”: “keeyong”,
 “last_name”: “han”
 }
}

 

위와 같은 JSON 파일을

 

 

 

 

---
course: Docker & K8s
company: Grepp
price: 0
tags:
- software
- devops
author:
 first_name: keeyong
 last_name: han

 

위와 같은 YAML로 바꾸거나 반대의 경우도 가능합니다.

 

 

 

 

 

 

 

 

 

 

 

.github/workflows/python-app.yml 설명 (1)

 

“on”: 트리거 이벤트 지정. main 브랜치에 push되거나 PR이 만들어지는 경우

 

on:
 push:
 branches: [ "main" ] # 모든 브랜치에 적용하고 싶다면 [ "main", "dev"]
 pull_request:
 branches: [ "main" ] # 모든 브랜치에 적용하고 싶다면 [ "main", "dev"]

 

 

 

 

 

 

 

 

 

 

 

.github/workflows/python-app.yml 설명 (2)

 

jobs: 여기에 실제 CI 프로세스가 스텝(name)별로 기술됨. 여긴 빌드 하나임

 

requirements.txt가 있으면 이를 설치

 

아래 녹색 부분만 수정. 코드 전체를 뒤져 test로 시작하는 모든 테스트를 실행

기본적으로 많은 내용을 채워주기 때문에 조금만 수정하면 됩니다.

 

jobs:
 build:
 runs-on: ubuntu-latest
 steps:
 - uses: actions/checkout@v3
 - name: Set up Python 3.10
 uses: actions/setup-python@v3
 with:
 python-version: "3.10"
 - name: Install dependencies
 run: |
 python -m pip install --upgrade pip
 pip install flake8 pytest(우리는 pytest를 쓰지 않으므로 삭제)
 if [ -f requirements.txt ]; then pip install -r requirements.txt; fi

name: Lint with flake8
 run: |
 # stop the build if there are Python syntax errors or undefined names
 flake8 . --count --select=E9,F63,F7,F82 --show-source 
--statistics
 # exit-zero treats all errors as warnings
 # The GitHub editor is 127 chars wide
 flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
 - name: Test with unittest(pytest에서 수정)
 run: |
 python -m unittest discover -p 'test*.py' (현재 위치의 모든 서브 디렉토리까지 뒤져서 test로 시작하는 모든 파이썬 파일에 대해 unittest 실행)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python-app.yml 파일을 PR로 추가

 

커밋하고 변경을 새로운 PR(Pull Request)로 생성

 

PR에서 머지하고 해당 브랜치 삭제

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

실습

 

 

작업 Repo에서 Actions 탭 선택

 

https://github.com/learndataeng/hangman_web 을 fork한 본인의 hangman_web Repo로 이동

 

 

fork 방법은 위와 같습니다.

 

 

 

 

 

 

 

 

 

CI Templates에서 Python Application 선택

 

 

찾을 수 없다면 검색창에서 검색하시거나 밑으로 스크롤을 쭉 내리신 뒤 continuous integration에서 view all을 클릭하고 찾으셔도 좋습니다.

 

Python application을 찾았다면 Configure를 클릭합니다.

 

 

 

 

 

 

 

 

 

 

 

.github/workflows/python-app.yml 편집

 

 

 

그러면 repo이름/.github/workflows/ 밑에 yml 파일이 자동으로 생성됩니다.

 

on에 어떤 Events로 workflow(Github actions)가 트리거될지 정할 수 있습니다. 현재는 main 브랜치로의 push와 pull_request인 경우가 디폴트로 정해져있습니다.

 

 

python-app.yml

# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python

name: Python application

on: # workflow가 트리거될 이벤트들 지정하는 곳
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

jobs:
  build: # CI만 한다면 build만 필요

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Set up Python 3.10
      uses: actions/setup-python@v3
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install flake8
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Lint with flake8
      run: |
        # stop the build if there are Python syntax errors or undefined names
        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
        # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
        flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
    - name: Test with unittest
      run: |
        python -m unittest discover -p 'test*.py' # 추가

 

편집은 위와 같이 했습니다.

 

 

 

 

 

 

 

 

 

 

 

편집이 끝났다면 Commit changes...를 클릭합니다.

 

 

 

 

 

별다른 설정 없이 commit changes를 클릭합니다.

 

 

 

 

 

 

 

 

 

 

 

 

test가 진행되는지 확인해보기

 

test가 실행되는지 확인하기 위해 hangman_web repo로 가서

 

 

 

 

 

 

 

 

README.md 파일을 위와 같이 수정해봅니다.

 

 

 

main 브랜치로 push가 되면 테스트가 진행이 되어야 합니다.

 

 

 

 

 

 

README.md 옆의 주황색불이 들어와있고 클릭을 해보면 위와 같이 checks가 끝나지 않았다는 창이 뜹니다.

 

창의 우측 하단의 Details 링크를 클릭하면

 

 

 

 

 

 

 

단계별로 실행된 작업들이 보입니다. Lint with flake8이나 Test with unittest 등 Workflow들을 확인하실 수 있습니다.

 

 

 

 

 

 
 
 

'Docker & K8S' 카테고리의 다른 글

Docker & K8S - Docker 명령 정리  (0) 2023.12.20
Docker & K8S - Github Actions 사용 # 2  (0) 2023.12.19
Docker & K8S - Github Actions 소개  (0) 2023.12.19
Docker & K8S - Git과 Github 소개  (0) 2023.12.19
Docker & K8S - CI/CD  (0) 2023.12.19