Python CI/CD自動化完全マスター – GitHub Actions・Docker・pytest実践ガイド
CI/CDとは?Pythonプロジェクトでの重要性
**CI/CD(Continuous Integration/Continuous Deployment)**は、コードの統合・テスト・デプロイを自動化する開発手法です。Pythonプロジェクトでは、テスト実行・コード品質チェック・パッケージ化・デプロイまでを自動化できます。
CI/CDの基本フロー
| ステージ | 内容 | ツール例 |
|---|---|---|
| CI(継続的統合) | テスト・リント・ビルド | GitHub Actions, pytest |
| CD(継続的デプロイ) | 本番環境への自動デプロイ | Docker, AWS, Heroku |
GitHub Actionsで始めるPython CI/CD
基本的なワークフロー設定
# .github/workflows/ci.yml
name: Python CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Run tests
run: pytest
マルチPythonバージョンテスト
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9', '3.10', '3.11', '3.12']
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Test
run: pytest
コード品質チェックの自動化
リント・フォーマットチェック
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
- name: Install tools
run: pip install black flake8 mypy
- name: Check formatting
run: black --check .
- name: Lint
run: flake8 .
- name: Type check
run: mypy .
pre-commitフックの設定
# .pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.3.0
hooks:
- id: mypy
テストカバレッジとレポート
カバレッジレポート生成
- name: Test with coverage
run: |
pip install pytest-cov
pytest --cov=src --cov-report=xml
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
テスト結果の可視化
- name: Publish test results
uses: dorny/test-reporter@v1
if: success() || failure()
with:
name: pytest
path: test-results.xml
reporter: java-junit
Dockerを使った環境標準化
基本的なDockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
Docker Composeでの開発環境
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8000:8000"
volumes:
- .:/app
environment:
- FLASK_ENV=development
db:
image: postgres:15
environment:
POSTGRES_DB: myapp
POSTGRES_PASSWORD: password
DockerでのCI実行
docker-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker image
run: docker build -t myapp .
- name: Run tests in container
run: docker run --rm myapp pytest
依存関係管理とセキュリティ
Dependabotの設定
# .github/dependabot.yml
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10
セキュリティスキャン
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Security check
run: |
pip install safety bandit
safety check
bandit -r src/
デプロイメント自動化
Herokuへの自動デプロイ
deploy:
needs: test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
- name: Deploy to Heroku
uses: akhileshns/heroku-deploy@v3.12.12
with:
heroku_api_key: ${{ secrets.HEROKU_API_KEY }}
heroku_app_name: "your-app-name"
heroku_email: "your-email@example.com"
AWS ECSへのデプロイ
deploy-aws:
runs-on: ubuntu-latest
steps:
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Deploy to ECS
run: |
aws ecs update-service --cluster myapp --service myapp-service --force-new-deployment
パッケージの自動リリース
PyPIへの自動公開
publish:
needs: test
runs-on: ubuntu-latest
if: github.event_name == 'release'
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
- name: Build package
run: |
pip install build
python -m build
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
password: ${{ secrets.PYPI_API_TOKEN }}
セマンティックバージョニング
- name: Semantic Release
uses: cycjimmy/semantic-release-action@v3
with:
semantic_version: 19
extra_plugins: |
@semantic-release/changelog
@semantic-release/git
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
環境別デプロイ戦略
ブランチベースデプロイ
deploy-staging:
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
environment: staging
steps:
- name: Deploy to staging
run: echo "Deploying to staging"
deploy-production:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- name: Deploy to production
run: echo "Deploying to production"
環境変数の管理
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
SECRET_KEY: ${{ secrets.SECRET_KEY }}
DEBUG: ${{ github.ref != 'refs/heads/main' }}
高度なCI/CDパターン
並列実行によるスピード最適化
jobs:
lint:
runs-on: ubuntu-latest
steps: [linting steps]
test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ['3.9', '3.11']
steps: [testing steps]
security:
runs-on: ubuntu-latest
steps: [security checks]
deploy:
needs: [lint, test, security]
runs-on: ubuntu-latest
steps: [deployment steps]
キャッシュ活用によるビルド高速化
- name: Cache pip packages
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
- name: Cache Docker layers
uses: actions/cache@v3
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
モニタリングと通知
Slack通知の設定
- name: Notify Slack
if: failure()
uses: 8398a7/action-slack@v3
with:
status: failure
webhook_url: ${{ secrets.SLACK_WEBHOOK }}
text: "CI/CD failed for ${{ github.repository }}"
メトリクス収集
- name: Upload metrics
run: |
curl -X POST "${{ secrets.METRICS_ENDPOINT }}" \
-H "Content-Type: application/json" \
-d '{"build_time": "${{ env.BUILD_TIME }}", "status": "success"}'
トラブルシューティング
よくある問題と解決法
# デバッグ用の詳細ログ出力
- name: Debug info
run: |
python --version
pip list
env | grep -E "(PYTHON|PATH)"
# ワークフロー失敗時の調査
- name: Upload logs
if: failure()
uses: actions/upload-artifact@v3
with:
name: logs
path: logs/
実プロジェクトでの完全なCI/CDパイプライン
フルスタックWebアプリの例
name: Full Stack CI/CD
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest-cov flake8 black
- name: Lint and format check
run: |
flake8 .
black --check .
- name: Run tests
run: pytest --cov=src --cov-report=xml
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test
- name: Build Docker image
run: docker build -t myapp:${{ github.sha }} .
- name: Deploy to staging
if: github.ref == 'refs/heads/develop'
run: |
docker tag myapp:${{ github.sha }} myapp:staging
# Deploy to staging environment
- name: Deploy to production
if: github.ref == 'refs/heads/main'
run: |
docker tag myapp:${{ github.sha }} myapp:production
# Deploy to production environment
パフォーマンス最適化
ビルド時間の短縮
# 条件付き実行でスキップ
- name: Skip if no Python changes
id: changes
uses: dorny/paths-filter@v2
with:
filters: |
python:
- '**/*.py'
- 'requirements.txt'
- name: Run tests
if: steps.changes.outputs.python == 'true'
run: pytest
まとめ:Python CI/CD成功の秘訣
CI/CDの効果
- 品質向上と バグ減少
- デプロイ時間の大幅短縮
- 開発者の生産性向上
- リリースの信頼性向上
導入のベストプラクティス
- 小さく始めて段階的に拡張
- テストの自動化を最優先
- 環境の標準化(Docker活用)
- セキュリティチェックの組み込み
避けるべき落とし穴
- 過度に複雑なパイプライン
- テスト時間の長期化
- 環境間の設定差異
- シークレット管理の不備
推奨する段階的導入
- 基本的なテスト自動化
- コード品質チェック追加
- Docker化と環境標準化
- 本番デプロイ自動化
Python CI/CDをマスターすることで、開発チームの生産性が大幅に向上し、より安全で高品質なソフトウェアを継続的にリリースできるようになります。まずはGitHub Actionsでの基本的なテスト自動化から始めて、徐々に高度な機能を追加していきましょう。
■プロンプトだけでオリジナルアプリを開発・公開してみた!!
■AI時代の第一歩!「AI駆動開発コース」はじめました!
テックジム東京本校で先行開始。
■テックジム東京本校
「武田塾」のプログラミング版といえば「テックジム」。
講義動画なし、教科書なし。「進捗管理とコーチング」で効率学習。
より早く、より安く、しかも対面型のプログラミングスクールです。
<短期講習>5日で5万円の「Pythonミニキャンプ」開催中。
<月1開催>放送作家による映像ディレクター養成講座
<オンライン無料>ゼロから始めるPython爆速講座
