Github actions
Skill Mohameddhiab/github-actions-skill/skills/github-actions
Comprehensive, all-in-one GitHub Actions skill for authoring, debugging, reviewing, and securing CI/CD workflows. Use when creating, editing, or reviewing any file under .github/workflows/ (or any GitHub Actions YAML), when choosing between an action and a shell command in CI, when picking action versions, configuring workflow permissions, secrets, environments, matrix strategies, reusable workflows, caching, artifacts, OIDC cloud auth, or when troubleshooting GitHub Actions for web, mobile, DevOps, or enterprise projects. Trigger keywords: github actions, workflow yaml, ci cd, .github/workflows, action yml, workflow syntax, reusable workflow, matrix build, gha, GITHUB_TOKEN.From its SKILL.md
npx -y skills add Mohameddhiab/github-actions-skill --skill github-actionsAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
44.2 KB, as published. Nobody here has run it
GitHub Actions — Complete Skill (All-in-One)
Authoritative, copy-paste-ready guidance for GitHub Actions. Works with any agent (opencode, Claude Code, Cursor, Codex, Gemini CLI, Cline, Copilot). Consolidated into a single file.
HOW TO USE THIS SKILL
- Authoring → read sections 1–9, then copy from the Template Library (section 22).
- Reviewing / securing → read section 16 (Security) and use the checklist in 16.6.
- Choosing versions / actions → follow CRITICAL RULE 2: verify every version at authoring time.
- Debugging → section 23 (troubleshooting) and 24 (debugging practices).
Golden rules up front (see the rules in section 21):
- Prefer a mature, maintained action over a hand-rolled script (
actions/*,docker/*, vendor actions). - Verify every action version right now with
gh api repos/<owner>/<repo>/releases/latest. - Pin by major tag (
@v7) normally; pin by full commit SHA for supply-chain-sensitive workflows. - Explicit, minimal
permissions:on every job; start fromcontents: read. - OIDC for cloud auth; never long-lived cloud credentials in GitHub secrets.
- Concurrency group on every deploy; split default-branch→dev and
v*tags→prod.
1. WORKFLOW FILE STRUCTURE
File: .github/workflows/<name>.yml (or .yaml). Filenames: kebab-case / lowercase snake. Invalid Invalid workflow file cure: fix indentation.
name: Workflow Display Name
run-name: Run ${{ github.event_name }} by ${{ github.actor }}
on:
push:
branches: [main]
paths: ['src/**']
workflow_dispatch:
inputs:
environment:
type: choice
options: [dev, staging, prod]
permissions:
contents: read
packages: write
id-token: write # OIDC when needed
env:
NODE_VERSION: '20'
defaults:
run:
shell: bash
working-directory: ./app
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build and Test
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
version: ${{ steps.meta.outputs.version }}
steps:
- uses: actions/checkout@v4
- run: echo "hello"
Top-level keys:
| Key | Purpose |
|---|---|
name | Display name in Actions tab |
run-name | Dynamic run name (contexts: github, inputs, vars) |
on | Event triggers (REQUIRED) |
permissions | GITHUB_TOKEN scopes (18 available) |
env | Workflow-level env vars |
defaults | Default shell/working-directory for all jobs |
concurrency | Concurrency groups (group, cancel-in-progress, queue, max) |
Considerations: YAML is whitespace-sensitive; "- name / run" must share indentation (a one-space shift breaks parsing). Reserved keys only.
2. TRIGGERS (on) — COMPLETE
Simple
on: push # single event
on: [push, fork] # multiple events
With activity types
on:
pull_request:
types: [opened, synchronize, reopened]
issues:
types: [opened, labeled]
Branch/tag filters (push)
on:
push:
branches: [main, 'releases/**']
branches-ignore: ['**-alpha']
tags: ['v*']
tags-ignore: ['v0.*']
Path filters
on:
push:
paths: ['src/**', '*.json']
paths-ignore: ['docs/**']
- Path + branch filters: BOTH must match.
!prefix for exclusion:paths: ['src/**', '!src/docs/**']— order matters..github/workflows/ci.ymlitself is a path you can gate on.
Glob cheat sheet
| Pattern | Meaning |
|---|---|
* | any except / |
** | any including / |
? | zero or one |
+ | one or more |
[abc] | character class |
! | negation (first char only) |
Scheduled (cron) — POSIX, UTC
on:
schedule:
- cron: '0 0 * * *' # daily midnight UTC
- cron: '0 12 * * 1-5' # weekdays noon UTC
# timezone supported:
- cron: { expression: '0 9 * * 1', timezone: 'Asia/Tokyo' }
* any, , list, - range, / step. Min interval ~every 5 min on public-heavy repos. Scheduled runs only on the default branch.
Manual dispatch
on:
workflow_dispatch:
inputs:
debug: { type: boolean, default: false }
environment: { type: choice, options: [dev, prod] }
version: { type: string, required: true }
count: { type: number, default: 1 }
Reusable workflow call
on:
workflow_call:
inputs:
config-path: { required: true, type: string }
outputs:
result:
value: ${{ jobs.build.outputs.result }}
secrets:
token:
required: true
Triggered by another workflow
on:
workflow_run:
workflows: ["Build"]
types: [completed] # completed | requested | in_progress
branches: [main]
External trigger via API
on:
repository_dispatch:
types: [deploy-command]
3. EVENTS — ALL ~34 TYPES
| Event | Activity Types | Use Case |
|---|---|---|
push | — | branch/tag push |
pull_request | opened, synchronize, reopened (+17 more) | enabling PR checks |
pull_request_target | same as PR | privileged-context PR (DANGEROUS) |
pull_request_review | submitted, edited, dismissed | review automation |
pull_request_review_comment | created, edited, deleted | review comment |
schedule | — | cron |
workflow_dispatch | — | manual |
workflow_call | — | reusable |
workflow_run | completed, requested, in_progress | chained |
repository_dispatch | custom | external API |
issues | opened, edited, closed, labeled… | issue automation |
issue_comment | created, edited, deleted | issue/PR comment |
label | created, edited, deleted | label activity |
milestone | created, closed, opened, edited, deleted | milestone |
release | published, unpublished, created, edited, deleted | releases |
fork | — | fork |
watch | started | star/unwatch |
create / delete | — | branch/tag create/delete |
deployment / deployment_status | — | deployments |
discussion / discussion_comment | created, edited… | discussions |
page_build | — | Pages build |
public | — | repo made public |
gollum | — | wiki edits |
check_run / check_suite | created, rerequested, completed | checks |
status | — | commit status |
merge_group | checks_requested | merge queue |
registry_package | published, updated | packages |
branch_protection_rule | created, edited, deleted | protection |
image_version | names + versions | custom runner images |
pull_request — GITHUB_SHA = last merge commit, GITHUB_REF = refs/pull/N/merge. Runs for opened/synchronize/reopened. Does NOT run on merge conflicts (use pull_request_target if needed). Use github.event.pull_request.head.sha for actual head.
pull_request_target — GITHUB_SHA = last base commit, GITHUB_REF = base. Runs from the BASE repo with write access. SECURITY: never check out or execute untrusted PR code inside it (RCE + secrets exposure). Use only for label/comment/CI-status automation on merged base code.
issue_comment — fires for issues AND PRs; distinguish with if: ${{ github.event.issue.pull_request }}.
workflow_run — chained; can access secrets + write token. Cannot chain more than 3 levels deep (docs: A→B→C→D works; a 5th workflow in the chain won't run).
4. CONTEXTS — ALL 12
github (30+ properties)
| Property | Description |
|---|---|
github.actor | triggering username |
github.ref | full ref (refs/heads/main) |
github.ref_name | short ref (main) |
github.ref_type | branch or tag |
github.sha | triggering SHA |
github.event_name | event name |
github.event | full webhook payload |
github.repository | owner/repo |
github.repository_owner | owner |
github.workflow | workflow name |
github.run_id / run_number / run_attempt | run identifiers |
github.server_url / api_url | URLs |
github.workspace | runner workdir |
github.token | GITHUB_TOKEN |
github.head_ref / base_ref | PR branches |
github.event.issue.number | issue/PR number |
github.event.pull_request.head.sha | PR head |
github.event.release.tag_name | release tag |
env— workflow/job/step env vars (step > job > workflow precedence).vars— org/repo/environment config variables (non-secret).secrets— repo/org/environment secrets (not available in composite actions or fork PRs).inputs—workflow_dispatch/workflow_callinputs.matrix— current matrix values;strategy.job-index,strategy.job-total.needs— outputs/results ofneedsjobs (needs.<id>.outputs.x,.result).steps— outputs of steps withid(steps.<id>.outputs.<o>,.outcome,.conclusion).conclusionis aftercontinue-on-error,outcomebefore.runner— os, arch, temp, tool_cache, name, environment, debug.job/jobs— current job info; reusable-workflow job outputs.secrets— secrets context.
Context availability varies by location
on:and workflow-levelenv: github, secrets, inputs, vars.jobs.<id>.if: github, needs, vars, inputs + status functions.steps.*: ALL 12 contexts +hashFiles.
5. EXPRESSIONS
Operators
( ) grouping · [ ] index · . property · ! not · < <= > >= comparison · == != equality · && || logical.
Type casting
- number:
''→0,'1'→1,'abc'→0(NaN→0) - boolean:
''→false,'true'→true,'false'→true
Functions
| Function | Example |
|---|---|
contains(search, item) | contains('hello','ll') → true |
startsWith(search, value) | startsWith('hello','he') → true |
endsWith(search, value) | endsWith('hello','lo') → true |
format(str, vals...) | format('{0}/{1}','a','b') |
join(array, sep?) | join(['a','b'],'-') → 'a-b' |
toJSON(value) | serialize |
fromJSON(value) | parse JSON string |
hashFiles(pathGlob) | hash matched files (cache keys) |
case(p1,v1,p2,v2,...,default) | switch-like |
Status functions
success() (default for implicit if), failure(), always(), cancelled(), skipped().
Object filters
- steps.*.outcome # array of outcomes
- github.event.labels.*.name # label names
- contains(steps.*.outcome, 'failure')
Common patterns
if: ${{ secrets.MY_SECRET != '' }}
if: ${{ contains(github.event.pull_request.labels.*.name, 'deploy') }}
if: ${{ !contains(github.ref, 'dependabot') }}
if: ${{ github.ref == 'refs/heads/main' }}
key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
env:
MSG: ${{ github.event_name == 'push' && 'Pushed' || 'PR' }}
- String literals in expressions MUST be quoted:
github.ref == 'refs/heads/main'. ${{ }}are GitHub expressions;${ }is shell expansion — don't confuse.
6. JOBS
jobs:
build:
name: Build
runs-on: ubuntu-latest # delegate / labels
needs: [test] # dependencies; runs when ALL succeed
if: ${{ success() && github.ref == 'refs/heads/main' }}
timeout-minutes: 30
permissions:
contents: read
id-token: write # OIDC
env:
NODE_ENV: production
defaults:
run:
shell: bash
concurrency:
group: build-${{ github.ref }}
cancel-in-progress: true
outputs:
version: ${{ steps.version.outputs.value }}
strategy:
fail-fast: false
max-parallel: 3
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [18, 20, 22]
exclude:
- os: macos-latest
node: 18
include:
- os: ubuntu-latest
node: 20
experimental: true
container:
image: node:20
credentials:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
env:
NODE_ENV: test
ports: ['3000:3000']
volumes: ['/tmp:/tmp']
services: # Linux/container jobs only
redis:
image: redis:7
ports: ['6379:6379']
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
Runner selection
runs-on: ubuntu-latest # GitHub-hosted
runs-on: ubuntu-24.04 # pinned image
runs-on: self-hosted # self-hosted
runs-on: [self-hosted, linux, arm64, gpu] # labels
runs-on: ubuntu-latest-4-cores # larger runner
Conditionals
if: ${{ github.event_name == 'push' }}
if: ${{ needs.build.result == 'success' }}
if: ${{ always() }}
if: ${{ !cancelled() && needs.build.result == 'success' }}
Matrix as a sharding shard pattern
strategy:
matrix:
shard: [1, 2, 3, 4]
steps:
- run: npm test -- --shard=${{ matrix.shard }}/4
Job outputs
jobs:
build:
outputs:
version: ${{ steps.v.outputs.version }}
steps:
- id: v
run: echo "value=1.0.0" >> "$GITHUB_OUTPUT"
deploy:
needs: build
steps:
- run: echo "Deploying ${{ needs.build.outputs.version }}"
7. STEPS
steps:
- name: Checkout
id: checkout
uses: actions/checkout@v4
with:
repository: owner/repo # cross-repo checkout
ref: v1
token: ${{ secrets.GITHUB_TOKEN }}
submodules: true
fetch-depth: 0 # full history; 1 = shallow for speed
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm' # auto-cache
- name: Build
run: npm run build
env:
API_KEY: ${{ secrets.API_KEY }}
working-directory: ./app
shell: bash
timeout-minutes: 10
continue-on-error: false
- name: Test
id: test
run: |
echo "result=pass" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Background server
run: ./server
background: true
wait: true # wait | wait-all | cancel
- name: Parallel steps
parallel: # run concurrently (newer runner feature)
- name: Lint
run: npm run lint
- name: Type check
run: npm run typecheck
Step attributes: name, id, uses, run, shell, with, env, working-directory, timeout-minutes, continue-on-error, if, background, parallel.
Action references
uses: actions/checkout@v4 # GitHub-hosted
uses: owner/repo/.github/workflows/ci.yml@main # reusable workflow
uses: ./my-local-action # local composite action
uses: docker://nginx:latest # Docker action
Shells
- Linux/macOS default:
bash -e. Windows default:pwsh+cmd. - Others:
bash,sh,pwsh/powershell,cmd,python,perl {0},script(R),cscript. - Force bash on Windows:
shell: bash.
Step outputs (multiline-safe)
echo "color=blue" >> "$GITHUB_OUTPUT"
echo "data<<EOF" >> "$GITHUB_OUTPUT"
echo "line1" >> "$GITHUB_OUTPUT"
echo "line2" >> "$GITHUB_OUTPUT"
echo "EOF" >> "$GITHUB_OUTPUT"
# read: ${{ steps.my-step.outputs.color }}
8. ENVIRONMENT FILES & WORKFLOW COMMANDS
| File | Purpose |
|---|---|
$GITHUB_ENV | set env vars for subsequent steps |
$GITHUB_OUTPUT | set step outputs |
$GITHUB_PATH | prepend to PATH |
$GITHUB_STEP_SUMMARY | job summary markdown |
$GITHUB_STATE | persist data between pre/main/post of an action |
echo "MY_VAR=hello" >> "$GITHUB_ENV"
echo "MULTI<<EOF" >> "$GITHUB_ENV"
echo "line1" >> "$GITHUB_ENV"
echo "EOF" >> "$GITHUB_ENV"
Annotations:
echo "::error file=app.js,line=1::Missing semicolon"
echo "::warning title=Lint::Deprecated API usage"
echo "::notice file=test.js,line=42::Performance issue"
echo "::debug::Debug message" # requires ACTIONS_STEP_DEBUG=true
Log grouping:
echo "::group::My section"
echo "details here"
echo "::endgroup::"
Masking:
echo "::add-mask::$MY_SECRET" # MUST run before the value appears anywhere in logs
Stop/resume command processing:
echo "::stop-commands::$(uuidgen)"
echo "::$(uuidgen)::"
Job summary:
echo "### Build Result" >> "$GITHUB_STEP_SUMMARY"
echo "| Metric | Value |" >> "$GITHUB_STEP_SUMMARY"
echo "|--------|-------|" >> "$GITHUB_STEP_SUMMARY"
echo "| Tests | 142 |" >> "$GITHUB_STEP_SUMMARY"
9. REUSABLE WORKFLOWS
Caller
jobs:
call-build:
uses: owner/repo/.github/workflows/build.yml@v2
with:
config: ./config.yml
secrets: inherit
# or pass individually:
# secrets:
# token: ${{ secrets.PERSONAL_TOKEN }}
Callee definition
name: Build Workflow
on:
workflow_call:
inputs:
config: { required: true, type: string }
debug: { type: boolean, default: false }
outputs:
version:
value: ${{ jobs.build.outputs.version }}
secrets:
token: { required: true }
jobs:
build:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.version.outputs.value }}
steps:
- id: version
run: echo "version=1.0.0" >> "$GITHUB_OUTPUT"
Restrictions
- Max 10 levels of nesting; max 25 unique reusable workflows per workflow run.
- Permissions can only be maintained or reduced, never elevated.
- Secrets only pass to the directly called workflow (unless explicitly passed).
- Reusable levels cannot access secrets/env vars from call site.
- No recursive loops.
- On reusable
workflow_call,permissions:/environment:/concurrency:/env:/defaults:must be declared inside the reusable file, not the caller.id-token: writemust be granted at the caller when the callee needs the OIDC token from outside.
10. DEPENDENCY CACHING
actions/cache
- uses: actions/cache@v4
with:
path: |
~/.npm
node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
Built-in setup-* caching
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- uses: actions/setup-python@v5
with: { python-version: '3.12', cache: pip }
Cache limits & strategy
- 10 GB default per repo · 7-day eviction · 200 uploads/min, 1500 downloads/min.
- Strategy: 1) exact lock file hash; 2) restore-keys OS prefix partial fallback; 3) new cache created on miss.
- Cache poisoning: only write caches from trusted triggers (
if: github.event_name == 'push'), never from untrusted fork PRs onpull_request.
11. GITHUB-HOSTED RUNNERS (specs)
| Runner | OS | CPU | RAM | SSD |
|---|---|---|---|---|
ubuntu-latest (24.04) | Linux x64 | 4 | 16 GB | 14 GB |
ubuntu-latest arm64 | Linux arm64 | 4 | 16 GB | 14 GB |
ubuntu-slim | Linux x64 | 1 | 5 GB | 14 GB |
ubuntu-latest-4-cores | Linux x64 | 8 | 32 GB | 150 GB |
windows-latest | Windows x64 | 4 | 16 GB | 14 GB |
macos-15/macos-14 | macOS arm64 | 3 | 7 GB | 14 GB |
Job execution: GitHub-hosted 6h max, self-hosted 5 days; matrix max 256 jobs; concurrency Free=20, Pro=40, Team=60, Enterprise=500.
Artifacts: Free=500MB/2000min, Pro=1GB/3000min, Team=2GB/3000min, Enterprise=50GB/50000min.
12. DEFAULT ENVIRONMENT VARIABLES
CI (true), GITHUB_ACTION, GITHUB_ACTION_PATH, GITHUB_ACTIONS, GITHUB_ACTOR, GITHUB_API_URL, GITHUB_BASE_REF, GITHUB_ENV, GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, GITHUB_HEAD_REF, GITHUB_JOB, GITHUB_OUTPUT, GITHUB_PATH, GITHUB_REF, GITHUB_REF_NAME, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_NUMBER, GITHUB_SHA, GITHUB_WORKFLOW, GITHUB_WORKSPACE, RUNNER_OS, RUNNER_ARCH, RUNNER_TEMP, RUNNER_TOOL_CACHE — plus RUNNER_DEBUG job-level.
13. LIMITS (reference)
| Limit | Value |
|---|---|
| Workflow run time | 35 days |
| Job execution (GitHub-hosted) | 6 hours |
| Job execution (self-hosted) | 5 days |
| Queue time | 24 hours |
| Matrix jobs | 256 per workflow |
| Re-runs per workflow | 50 |
| Event rate | 1500 / 10s / repo |
| Reusable nesting | 10 levels |
| Workflow file size | 1 MB |
Step run size | 21,000 chars |
timeout-minutes | max 360 |
| Background steps | max 10 concurrent |
| Job outputs | 1 MB/job, 50 MB/workflow |
| Config variables | 48 KB each |
| Repo variables | 500, 256 KB combined with org |
| Cache per repo | 10 GB default |
(Error correction: also limit #12 "cache eviction" is covered in §10.)
14. WORKFLOW CANCELLATION & CONCURRENCY
On cancellation: re-evaluate if conditions (always() keeps running) → signal escalation SIGINT → SIGTERM → kill → 5-minute forcible timeout for everything remaining.
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref == 'refs/heads/main' }}
queue:
max: 5 # max queued runs if you want to queue instead of cancel
Use branch-specific groups so unrelated refs aren't cancelled together.
15. GITHUB_TOKEN PERMISSIONS (18 scopes)
actions, attestations, checks, code-quality, contents, deployments, discussions, id-token, issues, models, packages, pages, pull-requests, security-events, statuses, vulnerability-alerts, metadata (read-only, always), artifact-metadata.
permissions: # no broad write by default
contents: read
issues: write
pull-requests: write
id-token: write # OIDC only
Default for GITHUB_TOKEN is permissive — always set permissions: at workflow or job level. Or set restrictive org default: Settings → Actions → General → "Workflow permissions" → Read repository contents.
16. SECURITY & HARDENING (critical)
16.1 Script injection (CRITICAL)
# BAD
- run: echo "title=${{ github.event.issue.title }}"
# GOOD
- env:
TITLE: ${{ github.event.issue.title }}
run: echo "title=$TITLE"
Never interpolate untrusted github.event.* into run: scripts — env-var indirection only.
16.2 pull_request_target — never execute untrusted code
# DANGEROUS: PR code with write access
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
Right pattern: run untrusted code in pull_request, then a privileged follow-up with workflow_run that validates conclusion == 'success' and runs only base-branch code.
16.3 Pinning actions / supply chain
# BAD
uses: actions/checkout@v4
uses: some-org/action@main # branch can be force-pushed
# GOOD (SHA-pinned)
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11
Tighten at org level: Settings → Actions → General → "Allow select Actions" allowlist, and enable dependency/audit updates (Dependabot or Renovate). Fork risky third-party actions; monitor the tj-actions class of compromise (e.g. CVE-2025-30066).
16.4 Secrets management
- Never log or echo secrets; never
echo "${{ secrets.X }}"inrun. - Pass instances via step-level
env:(best masking) or$GITHUB_ENV; mask dynamic secrets with::add-mask::before they appear. - Keep secrets out of commit messages, PR titles, structured (JSON) secrets, artifacts — exclude env files from
upload-artifact. - Environment-scope the unavoidable repos (SaaS tokens) instead of repo-wide.
- Rotate exposed secrets immediately.
16.5 Artifact & cache poisoning
# After download-artifact in workflow_run, verify:
- name: Verify artifact integrity
run: sha256sum ./build/* | grep -q "<expected-hash>"
- Restrict cache writes to trusted triggers (
if: github.event_name == 'push').
16.6 Self-hosted runners
- NEVER use on public repos (fork PRs can exfiltrate data / execute code).
- Use ephemeral / just-in-time (GitHub Actions-runners) runners, destroyed after each job.
- Use runner groups with restricted membership and network isolation; harden the host (normalized OS, patching, no secrets in environment).
16.7 OIDC (credential-less cloud auth)
GitHub issues a short-lived JWT; no long-lived cloud keys needed:
permissions:
id-token: write
contents: read
# AWS
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789:role/github-actions
aws-region: us-east-1
# GCP workload identity federation (no SA keys)
- uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/P/locations/global/workloadIdentityPools/github/providers/github
service_account: [email protected]
# Azure
- uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
For reusable workflows, OIDC requires id-token: write on the job and the caller step. Custom properties (repo_property_*) can be added to claims org-wide.
16.8 DevSecOps scans — add to every repo
on: [push, pull_request] # + merge_group for merge queue
permissions:
contents: read
security-events: write
pull-requests: write
jobs:
deps:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/dependency-review-action@v4
with:
fail-on-severity: moderate
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with: { languages: javascript } # python, java, cpp, ...
- uses: github/codeql-action/analyze@v3
Plus: gitleaks/gitleaks-action@v2 (secret scan), anchore/sbom-action@v0 + anchore/scan-action@v3 (SBOM + vuln scan), ossf/scorecard-action@v4.
16.9 Audit & watchdog
- Use branch protection + required status checks so CI must pass.
CODEOWNERSon.github/workflows/**so workflow changes get review.- Prevent Actions from creating/approving PRs under org settings.
16.10 Full security checklist
github.event.*used only via env indirection- Third-party actions pinned to full SHA (or @vN on GitHub-maintained)
permissions:minimal on every job- Secrets never logged/printed
pull_request_targetnever executes untrusted codeworkflow_runvalidates conclusion/event- Self-hosted only for private
- Cache writes on trusted triggers only
- Artifacts verified before execution
- Dependabot/Renovate active for actions + deps
17. COMMON PATTERNS
Matrix build
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node: [18, 20]
fail-fast: false
Required checks compose with branch protection
Apply pull_request + merge_group so the merge queue waits on CI.
Environment protection
deploy:
environment:
name: production
url: https://app.acme.com
- Environments gate secrets/vars per environment + optional required reviewers (manual approval).
Deployment split by ref
on:
push:
branches: [main] # → dev/staging env
tags: ['v*'] # → production env
Skip CI
# commit message: "[skip ci]" or "[no ci]"
# branch trigger only:
on:
push:
paths-ignore: ['**.md']
Monorepo path filters
- uses: dorny/paths-filter@v3
id: changes
with:
filters: |
frontend: ['apps/frontend/**']
backend: ['apps/backend/**']
- if: steps.changes.outputs.frontend == 'true'
run: npm run build --workspace frontend
Artifacts pass between jobs
- uses: actions/upload-artifact@v4 # in job 1
with: { name: build, path: dist/ }
- uses: actions/download-artifact@v4 # in job 2
with: { name: build, path: out/ }
18. COMPOSITE ACTIONS (action.yml)
# .github/actions/my-action/action.yml
name: My Action
description: Does things
inputs:
name: { required: true }
outputs:
result:
value: ${{ steps.step1.outputs.value }}
runs:
using: composite
steps:
- id: step1
run: echo "result=done" >> "$GITHUB_OUTPUT"
shell: bash
Used as uses: ./my-local-action. Reusable workflow rules on composite steps (secrets injected via with:).
19. CUSTOM ACTION DEVELOPMENT
- New custom actions MUST be merged to
mainbefore first use; test from feature branches after the initial merge. - Add debug steps printing non-secret
inputs/githubcontext parameters when creating/testing an action. - Always pin your own action invocation
used byactions/*@vN(or SHA in prod). - Documentation drift: keep the action's own README/
action.ymldescription truthful.
20. WORKFLOW POLICY RULES
- Prefer established actions:
actions/*,docker/*,google-github-actions/*,puslà/*... If no mature action exists, hand-roll and say so in the PR. Obscure single-maintainer actions holding credentials are worse than a script. - Verify versions at authoring time — never from memory. Example: a model confidently wrote
actions/checkout@v4+google-github-actions/auth@v2; the real latest werev8+/v3. Run the check:
for every action in the workflow, at the moment you write it.gh api repos/actions/checkout/releases/latest --jq .tag_name - Least privilege — explicit
permissions:block on every job; OIDC only for cloud. - Deploy hygiene —
concurrency:group on deploys; split dev/prod triggers.
Rationalizations that don't fly: "v4 is what I always use" (that's answering from memory), "old majors barely matter" (compat + security), "I'll leave a TODO" (it ships), "a curl is simpler than the action" (no auth/retries), "credentials just until WIF is set up" (keys outlive intentions).
21. ENTERPRISE-GRADE PATTERNS
- Organization defaults: restrict allowed actions + pin to SHA, turn on Actions allowlist, enable audit log.
- Alternatively: centralize pipelines in an
infra/repo with org-wide reusable workflows; repos call them@main(their default branch) withuses: org/infra/.github/workflows/X.yml@main. - Environments with required reviewers + deployment branches for staging/prod; keep secrets env-scoped.
- Business controls: runner groups + self-hosted hardened hosts, spending quotas, egress controls where needed.
- Enforce CODEOWNERS on
.github/workflows/**and require PR review on workflow changes (branch protection). - Run security checks as required checks (CodeQL, dependency-review) on PRs AND on the merge queue (
merge_group). - Use
gh+ audit API to review run costs and who triggered what.
22. RULES & GOLDEN GUIDELINES (quick reference)
- Always add
permissions:🍃 (scoped) — never broad defaults. - Pin third-party/community actions to full SHA; use Dependabot for the rest.
- OIDC for cloud; short-lived environment secrets only for non-cloud.
- Reusable workflows for org-wide logic; composite actions for repeated step sets.
- Cache deps (lockfile-keyed) +
path:matching; shallow clone (fetch-depth: 1) for speed. - Environments + required reviewers to protect deployments.
- DevSecOps in every default-branch check (CodeQL, gitleaks, dependency-review, SBOM).
- One workflow = one purpose (lint, test, deploy, release, security).
if:+pathsfilters + matrix sharding to skip redundant jobs.- Never echo secrets or pass secrets as command args; use
env:masking. - Set
timeout-minuteson every long job;continue-on-errorfor optional helpers. - Prefer
npm ci/pnpm install --frozen-lockfile/bun install --frozen-lockfileovernpm install. concurrencygroup per ref on every deploy workflow.name:steps — readable logs andif:steps.<id>references.- Add
.github/workflows/**to CODEOWNERS.
23. TROUBLESHOOTING
| Symptom | Fix |
|---|---|
| "Invalid workflow file" | YAML parse under jobs/steps; check indentation; use actionlint. |
| "Resource not accessible by integration" | Add required permissions: for the tool (e.g. issues: write, pull-requests: write). |
| Cache not restoring | Ensure key matches exactly (use hashFiles); add restore-keys prefix for partial hits. |
| Secrets unavailable | Not present in fork PRs, fork workflow_dispatch, or untrusted triggers. Use environment secrets (environment: production). |
| Steps failing randomly | Enable debug: set secrets ACTIONS_STEP_DEBUG: true, ACTIONS_RUNNER_DEBUG: true. |
| Slow checkout | fetch-depth: 1; for mono repo smaller sparse-checkout. |
Dump context / debug session:
- name: Dump context
run: |
echo "Event: ${{ github.event_name }}"
echo "Ref: ${{ github.ref }} | SHA: ${{ github.sha }} | Actor: ${{ github.actor }}"
echo '${{ toJSON(github) }}'
- name: SSH debug (on failure)
if: failure()
uses: mxschmitt/action-tmate@v3
timeout-minutes: 15
24. DEBUGGING PRACTICES (Open as a CLI workflow, not guesswork)
- Monitor, don't poll —
gh run watch,gh pr checks --watch. - Read logs, don't guess — fetch the failed job log before changing code.
- Print actual values — debug steps print real
inputs/githubcontext, not assumptions. - Test locally first —
act(Docker-based) ongithub/actavoids burning CI minutes (note: matrix/schedule ≈ offline differences). - Plan the smallest repro — one job, minimal matrix, narrow trigger before scaling.
YAML correctness before push:
# Linux/macOS
actionlint .github/workflows/*.yml
# Windows (where available)
# or npx actionlint
Video loop: fix → run → log → repeat is expected; keep runs cheap to prevent burn.
25. TEMPLATE LIBRARY (copy-paste ready)
All templates validated as parseable YAML. Swap
@vNfor the real current major a runtime (run thegh api .../releases/latestcheck).
22.1 Minimal CI
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Add commands here"
22.2 Node.js CI (matrix + cache)
name: Node CI
on: [push, pull_request]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
cache: npm
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build
22.3 Multi-OS matrix
name: Cross-Platform
on: push
jobs:
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- run: echo "Platform=${{ runner.os }}"
22.4 Docker build & push (GHCR)
name: Docker
on:
push:
tags: ['v*']
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v5
id: meta
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=ref,event=branch
- uses: docker/build-push-action@v6
with:
push: true
tags: ${{ steps.meta.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: true
22.5 GitHub Pages deploy
name: Deploy Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo "Build your site"
- uses: actions/upload-pages-artifact@v3
with:
path: ./dist
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- id: deployment
uses: actions/deploy-pages@v4
22.6 Reusable workflow (callee + caller)
# .github/workflows/reusable-build.yml
name: Reusable Build
on:
workflow_call:
inputs:
node-version: { type: string, default: '20' }
outputs:
version:
value: ${{ jobs.build.outputs.version }}
description: version
secrets:
token: { required: false }
jobs:
build:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.v.outputs.version }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
cache: npm
- run: npm ci && npm run build
- id: v
run: echo "version=1.0.0" >> "$GITHUB_OUTPUT"
# caller job
jobs:
build:
uses: ./.github/workflows/reusable-build.yml
with:
node-version: '22'
secrets:
token: ${{ secrets.GITHUB_TOKEN }}
22.7 Manual deploy with environment
name: Deploy
on:
workflow_dispatch:
inputs:
environment: { type: choice, options: [staging, production], required: true }
version: { type: string, required: true }
jobs:
deploy:
runs-on: ubuntu-latest
environment: ${{ inputs.environment }}
steps:
- run: echo "Deploying ${{ inputs.version }} to ${{ inputs.environment }}"
22.8 Scheduled cleanup (delete old runs)
name: Cleanup
on:
schedule:
- cron: '0 2 * * *'
workflow_dispatch:
permissions:
actions: write
contents: read
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const runs = await github.rest.actions.listWorkflowRunsForRepo({
owner: context.repo.owner, repo: context.repo.repo, per_page: 100,
});
for (const run of runs.data.workflow_runs) {
if (run.created_at < new Date(Date.now() - 30*24*60*60*1000).toISOString()) {
await github.rest.actions.deleteWorkflowRun({ owner: context.repo.owner, repo: context.repo.repo, run_id: run.id });
}
}
22.9 Mobile — Android Gradle
name: Android CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 17
cache: gradle
- run: chmod +x gradlew
- run: ./gradlew assembleDebug test
- name: Build release (signed in real CI)
run: ./gradlew assembleRelease
env:
KEYSTORE_B64: ${{ secrets.KEYSTORE_B64 }}
22.10 iOS
name: iOS
on: [push, pull_request]
jobs:
test:
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
- run: pod install --repo-update || swift build
working-directory: ios
- run: >
xcodebuild clean test
-workspace MyApp.xcworkspace
-scheme App
-destination 'platform=iOS Simulator,name=iPhone 15'
working-directory: ios
22.11 Flutter
name: Flutter
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
with:
channel: stable
cache: true
- run: flutter pub get
- run: flutter analyze
- run: flutter test
android:
needs: [test]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: subosito/flutter-action@v2
- run: flutter build apk
- uses: actions/upload-artifact@v4
with:
name: apk
path: build/app/outputs/flutter-apk/
22.12 React Native (Expo)
name: RN
on: [push, pull_request]
jobs:
ci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- uses: expo/expo-github-action@v8
with:
eas: false
- run: npx tsc --noEmit
- run: npm run lint
- run: npm test
22.13 Terraform + OIDC (no stored keys)
name: Terraform
on:
push:
branches: [main]
paths: ['terraform/**']
pull_request:
paths: ['terraform/**']
permissions:
id-token: write
contents: read
jobs:
terraform:
runs-on: ubuntu-latest
defaults:
run:
working-directory: terraform
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with: { terraform_version: 1.9 }
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/terraform
aws-region: us-east-1
- run: terraform fmt -check
- run: terraform init
- id: plan
run: terraform plan -no-color
- name: Apply
if: github.ref == 'refs/heads/main'
run: terraform apply -auto-approve
22.14 Node app + Docker → AWS ECR via OIDC
name: Deploy ECR
on:
push:
branches: [main]
env:
ECR_REGISTRY: ${{ vars.ECR_REGISTRY }}
permissions:
id-token: write
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/ci
aws-region: us-east-1
- uses: docker/login-action@v3
with:
registry: ${{ env.ECR_REGISTRY }}
- run: docker build -t "$ECR_REGISTRY/app:latest" .
- run: docker push "$ECR_REGISTRY/app:latest"
22.15 Release → npm publish
name: Release
on:
push:
tags: ['v*']
permissions:
contents: write
packages: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org'
- run: npm ci
- run: npm run build
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
22.16 PR check with dependency review + gitleaks
name: PR Gate
on: pull_request
permissions:
contents: read
pull-requests: write
security-events: write
jobs:
deps:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/dependency-review-action@v4
with: { fail-on-severity: moderate }
secrets:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
22.17 Staging → Production environments
name: Deploy
on:
push:
branches: [main]
jobs:
staging:
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh staging
production:
needs: staging
runs-on: ubuntu-latest
environment:
name: production
url: https://app.acme.com
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- run: ./deploy.sh production
26. TERMINAL: LOCAL VERIFICATION
actionlint— YAML + semantic validation, before pushing.act(nektos/act) — run workflows locally (Docker); matrix and cloud contexts not fully reproduced.gh run watch/gh pr checks --watch— live follow.gh api repos/<owner>/<repo>/releases/latest --jq .tag_name— verify the current action version.