GitHub ActionsでWebアプリのテスト・ビルド・デプロイを自動化するCI/CDパイプラインを構築します。
CI/CDとは?
| 用語 | 意味 | 内容 |
|---|---|---|
| CI(継続的インテグレーション) | Continuous Integration | コードをpushするたびに自動でテスト・ビルドを実行する |
| CD(継続的デリバリー) | Continuous Delivery | テスト通過後に自動でサーバーへデプロイする |
GitHub ActionsのワークフローファイルYAML
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest
- name: Run tests
run: pytest
deploy:
needs: test # testジョブ成功後に実行
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/myapp:latest
- name: Deploy to server
uses: appleboy/ssh-action@v1.0.0
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
docker compose pull
docker compose up -dまとめ
- GitHub Actionsはpush時に自動でテスト→ビルド→デプロイを実行できる
- needsで前のジョブの成功を条件にできる
- SecretsにAPIキーやSSH鍵を安全に保管する



コメント