CI/CDパイプライン設計 - 継続的インテグレーションとデリバリー

18分 で読める | 2025.01.10

公式ドキュメント

CI/CDとは

CI/CD(Continuous Integration / Continuous Delivery)は、コードの変更を自動的にビルド、テスト、デプロイするプラクティスです。開発サイクルを高速化し、品質を向上させます。

flowchart LR
 subgraph CI["継続的インテグレーション"]
 A["コード変更"] --> B["自動ビルド"]
 B --> C["自動テスト"]
 C --> D["コード品質チェック"]
 end

 subgraph CD["継続的デリバリー"]
 D --> E["ステージング環境"]
 E --> F["承認"]
 F --> G["本番デプロイ"]
 end

パイプラインの基本ステージ

1. ソースステージ

# GitHub Actions例
on:
 push:
 branches: [main, develop]
 pull_request:
 branches: [main]

2. ビルドステージ

build:
 runs-on: ubuntu-latest
 steps:
 - uses: actions/checkout@v4
 - uses: actions/setup-node@v4
 with:
 node-version: '20'
 cache: 'npm'
 - run: npm ci
 - run: npm run build
 - uses: actions/upload-artifact@v4
 with:
 name: build-output
 path: dist/

3. テストステージ

test:
 runs-on: ubuntu-latest
 needs: build
 strategy:
 matrix:
 test-type: [unit, integration, e2e]
 steps:
 - uses: actions/checkout@v4
 - run: npm ci
 - run: npm run test:${{ matrix.test-type }}
 - uses: codecov/codecov-action@v4
 if: matrix.test-type == 'unit'

4. 品質チェックステージ

quality:
 runs-on: ubuntu-latest
 steps:
 - uses: actions/checkout@v4
 - run: npm ci
 - run: npm run lint
 - run: npm run type-check
 - name: SonarQube Scan
 uses: sonarsource/sonarqube-scan-action@master

5. デプロイステージ

deploy:
 runs-on: ubuntu-latest
 needs: [test, quality]
 if: github.ref == 'refs/heads/main'
 environment: production
 steps:
 - uses: actions/download-artifact@v4
 with:
 name: build-output
 - name: Deploy to Production
 run: |
 # デプロイコマンド

環境戦略

環境用途デプロイトリガー
Development開発者テストプッシュごと
StagingQAテストdevelop マージ
Production本番main マージ + 承認

注意: シークレット(APIキー、DB接続文字列等)は絶対にコードにハードコーディングしないでください。必ず環境変数やシークレット管理サービスを使用しましょう。

セキュリティベストプラクティス

シークレット管理

# GitHub Secretsの使用
env:
 DATABASE_URL: ${{ secrets.DATABASE_URL }}
 API_KEY: ${{ secrets.API_KEY }}

# OIDC認証(AWS)
- uses: aws-actions/configure-aws-credentials@v4
 with:
 role-to-assume: arn:aws:iam::123456789:role/GitHubActions
 aws-region: ap-northeast-1

依存関係スキャン

- name: Dependency Review
 uses: actions/dependency-review-action@v4

- name: Trivy Security Scan
 uses: aquasecurity/trivy-action@master
 with:
 scan-type: 'fs'
 severity: 'CRITICAL,HIGH'

ポイント: キャッシュと並列実行はパイプライン高速化の二大要素です。依存関係のインストールをキャッシュし、独立したテストは並列で実行しましょう

パイプライン最適化

キャッシュ活用

- uses: actions/cache@v4
 with:
 path: |
 ~/.npm
 node_modules
 key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
 restore-keys: |
 ${{ runner.os }}-node-

並列実行

jobs:
 test-unit:
 runs-on: ubuntu-latest
 test-integration:
 runs-on: ubuntu-latest
 test-e2e:
 runs-on: ubuntu-latest
 # 3つのジョブが並列実行

実践メモ: 失敗時のSlack通知設定は必須です。ビルドが壊れたことに気づかないと、次の開発者も同じ問題に遭遇します。

現場での教訓

  1. テストの並列化でビルド時間を50%短縮 - マトリクス戦略の活用
  2. 失敗時の通知設定は必須 - Slack連携で即時対応
  3. ロールバック手順を事前に用意 - 本番障害時のリカバリ

関連記事

まとめ

CI/CDパイプラインは、コード品質と開発速度の両立に不可欠です。ステージを適切に設計し、セキュリティとパフォーマンスを考慮した実装を行いましょう。

参考リソース

← 一覧に戻る
PR
PR
PR
PR