GitHub Actions CI/CD:自動デプロイパイプラインの構築
GitHub Actionsは、GitHubリポジトリで直接CI/CD(Continuous Integration/Continuous Deployment)パイプラインを構築できる強力なツールです。この記事では、GitHub Actionsの基本から、実践的なCI/CDパイプラインの構築、そして本番環境への自動デプロイまでを学びます。
コードの品質を保証し、デプロイメントを自動化することで、開発効率を大幅に向上させることができます。
1. GitHub Actionsとは
GitHub Actionsは、GitHubが提供するCI/CDプラットフォームで、以下の特徴があります。
- GitHub統合: リポジトリと完全に統合
- YAMLベース: ワークフローファイルで定義
- 無料プラン: 公開リポジトリは無料、プライベートリポジトリも月2000分まで無料
- 豊富なアクション: コミュニティが提供する再利用可能なアクション
1.1 基本概念
- Workflow: 自動化されたプロセス(YAMLファイルで定義)
- Job: ワークフロー内の実行単位
- Step: ジョブ内の個別のタスク
- Action: 再利用可能なコード単位
- Runner: ワークフローを実行するサーバー
1.2 ワークフローファイルの場所
.github/workflows/
├── ci.yml
├── deploy.yml
└── test.yml
2. 基本的なワークフロー
2.1 シンプルなCIワークフロー
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Run linter
run: npm run lint
2.2 マトリックスビルド
name: Test Matrix
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16, 18, 20]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v3
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm test
3. Node.jsプロジェクトのCI/CD
3.1 完全なCI/CDパイプライン
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
release:
types: [created]
env:
NODE_VERSION: '18'
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
# テストジョブ
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run linter
run: npm run lint
- name: Run tests
run: npm test
env:
CI: true
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
fail_ci_if_error: false
# ビルドジョブ
build:
needs: test
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build application
run: npm run build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
with:
name: dist
path: dist/
retention-days: 7
# Dockerイメージのビルドとプッシュ
docker:
needs: test
runs-on: ubuntu-latest
if: github.event_name != 'pull_request'
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to Container Registry
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
# デプロイジョブ
deploy:
needs: [build, docker]
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
environment: production
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Download build artifacts
uses: actions/download-artifact@v3
with:
name: dist
path: dist/
- name: Deploy to production
run: |
echo "Deploying to production..."
# デプロイスクリプトを実行
# ./deploy.sh
4. 環境変数とシークレット
4.1 シークレットの設定
GitHubリポジトリの Settings > Secrets and variables > Actions で設定
# シークレットの使用
- name: Deploy
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
run: |
echo "Deploying with credentials..."
4.2 環境変数の設定
# ワークフローレベル
env:
NODE_ENV: production
APP_VERSION: ${{ github.sha }}
jobs:
deploy:
# ジョブレベル
env:
DEPLOY_ENV: production
steps:
- name: Deploy
# ステップレベル
env:
API_URL: https://api.example.com
run: npm run deploy
5. デプロイ戦略
5.1 Vercelへのデプロイ
name: Deploy to Vercel
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Deploy to Vercel
uses: amondnet/vercel-action@v25
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.ORG_ID }}
vercel-project-id: ${{ secrets.PROJECT_ID }}
vercel-args: '--prod'
5.2 AWSへのデプロイ
name: Deploy to AWS
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- 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 S3
run: |
aws s3 sync dist/ s3://my-bucket --delete
- name: Invalidate CloudFront
run: |
aws cloudfront create-invalidation \
--distribution-id ${{ secrets.CLOUDFRONT_DISTRIBUTION_ID }} \
--paths "/*"
5.3 Kubernetesへのデプロイ
name: Deploy to Kubernetes
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up kubectl
uses: azure/setup-kubectl@v3
- name: Configure kubeconfig
uses: azure/k8s-set-context@v3
with:
kubeconfig: ${{ secrets.KUBE_CONFIG }}
- name: Deploy to Kubernetes
run: |
kubectl set image deployment/my-app \
my-app=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
6. 高度なワークフロー
6.1 条件付き実行
jobs:
deploy-staging:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/develop'
steps:
- name: Deploy to staging
run: echo "Deploying to staging"
deploy-production:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
steps:
- name: Deploy to production
run: echo "Deploying to production"
6.2 ジョブ間の依存関係
jobs:
build:
runs-on: ubuntu-latest
outputs:
image-tag: ${{ steps.meta.outputs.tags }}
steps:
- id: meta
run: echo "tags=my-app:latest" >> $GITHUB_OUTPUT
test:
needs: build
runs-on: ubuntu-latest
steps:
- name: Use build output
run: echo "Image tag: ${{ needs.build.outputs.image-tag }}"
deploy:
needs: [build, test]
runs-on: ubuntu-latest
steps:
- name: Deploy
run: echo "Deploying ${{ needs.build.outputs.image-tag }}"
6.3 ワークフローの再利用
# .github/workflows/reusable-workflow.yml
name: Reusable Workflow
on:
workflow_call:
inputs:
environment:
required: true
type: string
node-version:
required: false
type: string
default: '18'
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- name: Deploy to ${{ inputs.environment }}
run: |
echo "Deploying to ${{ inputs.environment }}"
echo "Using Node.js ${{ inputs.node-version }}"
# .github/workflows/call-reusable.yml
name: Call Reusable Workflow
on:
workflow_dispatch:
jobs:
call-workflow:
uses: ./.github/workflows/reusable-workflow.yml
with:
environment: production
node-version: '20'
7. 通知とレポート
7.1 Slack通知
- name: Send Slack notification
uses: 8398a7/action-slack@v3
with:
status: ${{ job.status }}
text: 'Deployment completed!'
webhook_url: ${{ secrets.SLACK_WEBHOOK_URL }}
if: always()
7.2 PRコメント
- name: Comment PR
uses: actions/github-script@v6
if: github.event_name == 'pull_request'
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '✅ All checks passed! Ready to merge.'
})
8. 実践的な例:フルスタックアプリのCI/CD
name: Full Stack CI/CD
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
# フロントエンドのテスト
frontend-test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./frontend
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: ./frontend/package-lock.json
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
# バックエンドのテスト
backend-test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./backend
services:
postgres:
image: postgres:15
env:
POSTGRES_PASSWORD: postgres
POSTGRES_DB: testdb
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: ./backend/package-lock.json
- run: npm ci
- run: npm run lint
- run: npm test
env:
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/testdb
# E2Eテスト
e2e-test:
needs: [frontend-test, backend-test]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install Playwright
run: npm install -g playwright
working-directory: ./e2e
- name: Install dependencies
run: npm ci
working-directory: ./e2e
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run E2E tests
run: npm test
working-directory: ./e2e
# デプロイ
deploy:
needs: [frontend-test, backend-test, e2e-test]
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
environment: production
steps:
- uses: actions/checkout@v3
- name: Deploy frontend
run: |
echo "Deploying frontend..."
# フロントエンドのデプロイコマンド
- name: Deploy backend
run: |
echo "Deploying backend..."
# バックエンドのデプロイコマンド
9. まとめと次のステップ
この記事を通じて、GitHub Actionsを使ったCI/CDパイプラインの構築方法を学びました。
学んだこと
- 基本概念: ワークフロー、ジョブ、ステップ、アクション
- ワークフローの作成: YAMLファイルでの定義
- CI/CDパイプライン: テスト、ビルド、デプロイの自動化
- デプロイ戦略: Vercel、AWS、Kubernetesへのデプロイ
- 高度な機能: 条件付き実行、ジョブ間の依存関係、ワークフローの再利用
- 通知: Slack、PRコメントなどの通知設定
ベストプラクティス
- セキュリティ: シークレットの適切な管理
- キャッシュ: 依存関係のキャッシュで高速化
- 並列実行: 独立したジョブの並列実行
- 条件付き実行: 必要な時のみジョブを実行
- エラーハンドリング: 適切な通知とロールバック戦略
次のステップ
- セルフホストランナー: カスタムランナーの設定
- 複雑なパイプライン: マルチステージデプロイ
- モニタリング: ワークフローの監視と最適化
- コスト最適化: 実行時間とリソースの最適化
GitHub Actionsは、開発ワークフローを自動化する強力なツールです。継続的な改善を通じて、効率的なCI/CDパイプラインを構築しましょう!
Happy Automating!
コメント
コメントを読み込み中...
