이 시리즈의 처음 두 부분에서 우리는 : - 작동하는 CI/CD 파이프라인을 Python 애플리케이션용으로 GitHub Actions 및 PyPI를 이용해 구축했습니다. - 이 파이프라인을 다중 버전 테스트, Test PyPI를 통한 점진적 배포, 그리고 품질 및 보안 도구로 산업화했습니다.

이 세 번째 부분에서 우리는 갈 것입니다.PyPI에 단순한 게시를 넘어CI/CD 파이프라인을 완전히 강력하고 전문적으로 구축하기 위해 : - 시현대적인 패키징과 최적화된 의존성 관리를 위해 - 도커재현 가능하고 다중 플랫폼을 지원하는 빌드를 만들기 위해 - 조건부 발행릴리스 후보와 같은 시나리오를 관리하기 위해 - 자동화 도구(Renovate, Dependabot)를 사용해 파이프라인을 손쉽게 최신 상태로 유지하기

Poetry와의 통합

Poetry는 기존 패키징 도구(setup.py, requirements.txt)를 대체하여 의존성 및 빌드 관리를 중앙 집중화하여`pyproject.toml`.

Poetry 설치

# Installer Poetry
curl -sSL https://install.python-poetry.org | python3 -
# Vérifier la version
poetry --version

프로젝트 초기화

# Initialiser un nouveau projet avec Poetry
poetry init
# Suivre l'assistant pour renseigner : nom, version, description, licence, dépendances.

이는 파일을 생성합니다.pyproject.toml :

[tool.poetry]
name = "playlist-downloader"
version = "0.1.0"
description = "CLI tool for managing YouTube playlists"
authors = ["Christophe Hérolivier <[email protected]>"]

[tool.poetry.dependencies]
python = ">=3.8"
typer = "^0.9.0"
yt-dlp = "^2023.7.6"
google-api-python-client = "^2.0.0"
google-auth-oauthlib = "^1.0.0"

[tool.poetry.group.dev.dependencies]
pytest = "^7.0"
mypy = "^1.0"
bandit = "^1.7"
safety = "^2.3"
black = "^23.0"
ruff = "^0.1"

의존성 추가 및 설치

poetry add typer yt-dlp google-api-python-client google-auth-oauthlib
poetry add --group dev pytest mypy black bandit safety ruff

Poetry와 함께 게시

Poetry 네이티브하게 출판을 :

# Publication sur Test PyPI
poetry publish --build --repository test-pypi

# Publication sur PyPI
poetry publish --build

이 명령은 자동으로 에 있는 정보를 사용합니다`pyproject.toml`.

도커를 사용한 재현 가능한 빌드

개발, CI/CD, 프로덕션에서 동일한 실행 환경을 보장하기 위해 Docker는 Poetry와 완벽하게 통합됩니다.

Dockerfile 예시

FROM python:3.11-slim

WORKDIR /app
COPY pyproject.toml poetry.lock ./
RUN pip install poetry
RUN poetry install --no-root --only main

COPY . .

CMD ["poetry", "run", "python", "cli.py"]

이것은 보장합니다: - 동결된 파이썬 환경. - 잠긴 의존성들 via`poetry.lock`. - Docker를 지원하는 모든 시스템에서 실행 가능한 이미지.

GitHub Actions 통합

name: Docker Build

on:
  push:
    branches: [main]

jobs:
  build-docker:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build Docker image
        run: docker build -t ghcr.io/${{ github.repository }}:latest .
      - name: Push Docker image
        run: docker push ghcr.io/${{ github.repository }}:latest

조건부 게시

전문적인 파이프라인에서는 특정 경우에만 게시할 수 있어야 합니다 : - Release candidates Test PyPI сторону - 안정적인 버전을 PyPI로. - 도커 빌드만 트리거됨`main`.

- name: Publish to Test PyPI
  if: contains(github.ref, '-rc')
  run: poetry publish --build --repository test-pypi

- name: Publish to PyPI
  if: startsWith(github.ref, 'refs/tags/v')
  run: poetry publish --build

이 접근법은 실수로 게시되는 것을 방지합니다.

Renovate 및 Dependabot을 사용한 의존성 자동화

의존성이 낡아지지 않도록 자동 업데이트 도구를 통합하세요.

Dependabot

version: 2
updates:
  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"

Dependabot는 매주 Python 및 GitHub Actions 의존성을 업데이트하기 위해 PR을 엽니다.

리모델링하다

{
  "extends": ["config:base"],
  "packageRules": [
    {
      "matchManagers": ["pip"],
      "groupName": "python-dependencies",
      "schedule": ["before 6am on monday"]
    }
  ]
}

Renovate는 더 세밀한 제어를 제공합니다: 의존성 그룹화, 일정, 그리고 고급 규칙.

PlantUML 다이어그램

사용 사례 – 고급 CI/CD

@startuml
actor Developer
actor GitHub as "GitHub Actions"
actor PyPI
actor DockerRegistry as "Docker 레지스트리"
actor Automation as "Renovate/Dependabot"

Developer --> (Push code)
(Trigger CI) --> GitHub
GitHub --> (Run Tests & Lint)
GitHub --> (Build Docker Image)
GitHub --> DockerRegistry
GitHub --> (Publish to Test PyPI)
GitHub --> (Promote to PyPI)
Automation --> (Update Dependencies)
@enduml

시퀀스 – 조건부 게시

@startuml
!theme vibrant
left to right direction
Developer -> GitHub: Push tag v1.2.3-rc
GitHub -> CI: Run tests
CI -> CD: Check release type
CD -> Test PyPI: Publish RC
Developer -> GitHub: Push tag v1.2.3
GitHub -> CD: Publish to PyPI
CD -> Docker Registry: Push Docker image
@enduml

상태 – CI/CD 파이프라인

@startuml
[*] --> Idle
Idle --> CI_Running : push
CI_Running --> CI_Success : tests ok
CI_Running --> CI_Failed : tests fail
CI_Success --> CD_Running : tag detected
CD_Running --> CD_Success : publish ok
CD_Running --> CD_Failed : error
CD_Success --> [*]
@enduml

배포 – CI/CD 아키텍처

@startuml
node "개발자 머신" {
  component "Git 클라이언트"
}

node "GitHub 작업" {
  component "CI 워크플로우"
  component "CD 워크플로우"
}

node "패키지 저장소" {
  artifact "테스트 PyPI"
  artifact "PyPI"
  artifact "도커 레지스트리"
}

"개발자 머신" --> "GitHub 작업"
"GitHub 작업" --> "테스트 PyPI"
"GitHub 작업" --> "PyPI"
"GitHub 작업" --> "도커 레지스트리"
@enduml

결론

이 세 번째 부분에서 우리는 다음과 같이 보았습니다: - Poetry를 활용한 Python 패키징 현대화 Docker을 통해 재현 가능한 빌드를 보장한다. - 조건부 게시물을 설정하세요. - 자동화 의존성 업데이트.

이제 CI/CD 파이프라인을 보유하고 있습니다.완전한, 산업화된, 그리고 안전한, 귀하의 프로젝트와 함께 발전할 준비가 된

관련 기사