GitHub Actions CI/CDベストプラクティス
GitHub Actionsのベストプラクティス: 再利用可能ワークフロー、マトリックス戦略、依存関係キャッシュ、セキュリティ強化(最小権限、シークレット管理、スクリプトインジェクション防止)。
# GitHub Actions Best Practices
GitHub Actions is the backbone of modern CI/CD. These best practices ensure your workflows are efficient, secure, and maintainable.
## 1. Workflow Design
### Use Reusable Workflows and Composite Actions
Abstract common sequences into reusable workflows or composite actions:
```yaml
# .github/workflows/reusable-build.yml
on:
workflow_call:
inputs:
build-script: { required: true, type: string }
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20' }
- run: npm ci
- run: ${{ inputs.build-script }}
```
### Use Matrix Strategies for Broad Testing
```yaml
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
node-version: ['18', '20']
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/setup-node@v4
with: { node-version: ${{ matrix.node-version }} }
- run: npm test
```
### Set Explicit Concurrency Groups
```yaml
jobs:
deploy:
environment: production
concurrency: production_deployment # Only one can run at a time
```
## 2. Performance: Cache Dependencies
```yaml
steps:
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- run: npm ci
```
## 3. Code Quality: Shift-Left
```yaml
jobs:
lint:
steps:
- run: npm run lint # Fail fast
test:
needs: lint # Only run tests if lint passes
```
### Pin Third-Party Actions to Specific SHA
```yaml
# Good: specific version
uses: actions/[email protected]
# Best: specific SHA
uses: actions/checkout@a81bbbf8298bb0ba8a753697672f0999c0179a61
```
## 4. Security Hardening
### Apply Principle of Least Privilege
```yaml
permissions:
contents: read # Default to read-only
jobs:
deploy:
permissions:
contents: write # Elevate only where needed
```
### Prevent Script Injection
Always pass untrusted input via environment variables, not direct interpolation:
Bad:
```yaml
- run: echo "Title: ${{ github.event.pull_request.title }}"
```
Good:
```yaml
- name: Check PR Title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: echo "Title: $PR_TITLE"
```
### Never Hardcode Secrets
```yaml
env:
API_KEY: ${{ secrets.MY_API_KEY }} # Always use GitHub Secrets
```
## 5. Common Gotchas
- Use `github.ref == 'refs/heads/main'` not `github.ref == 'main'` in job conditions
- Use `if: success()` in step conditions, not `if: true`
- Enable `ACTIONS_STEP_DEBUG` secret = `true` for verbose debugging (delete after)
## 6. Integrated Code Scanning
```yaml
jobs:
code-scan:
permissions:
security-events: write
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with: { languages: javascript }
- uses: github/codeql-action/autobuild@v3
- uses: github/codeql-action/analyze@v3
``` こちらもおすすめ
DevOps カテゴリの他のルール
もっとルールを探す
CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 223 ルールをチェック。



