GitHub Actions Cheatsheet
GitHub Actions
Download free PDFWorkflow authoring and data flow
Workflow structure and execution
- Store YAML workflows in **.github/workflows/**. **on** selects events; **jobs** defines work; **runs-on** selects a runner; **steps** contains sequential tasks.
- A step uses **run** for shell commands or **uses** for an action. Jobs can run in parallel; **needs** creates dependencies between jobs.
- Use **shell: pwsh** for PowerShell, including on Linux when PowerShell is installed. A script can run directly in a **run** step; a custom action is optional.
- **strategy.matrix** expands a job across combinations such as operating systems and language versions. **include**, **exclude** and **max-parallel** refine the combinations and parallelism.
- **if** controls whether work runs. **success()**, **failure()**, **cancelled()** and **always()** inspect execution status; use cleanup conditions deliberately.
Events, schedules and follow-up runs
- **workflow_dispatch** provides manual or API-triggered execution with optional inputs. **repository_dispatch** accepts API events from external systems, with an event type and client payload.
- **schedule** contains a list of **cron** entries. In the standard UTC form, **45 7 * * 3,6** means 07:45 on Wednesday and Saturday; fields are minute, hour, day of month, month and day of week.
- Scheduled workflows use the latest commit on the **default branch**, where the workflow must exist. A schedule is automation timing, not a guarantee of exact start time.
- **workflow_run** can start a workflow when a named upstream workflow completes. Completion includes failure: gate deployment with **github.event.workflow_run.conclusion == 'success'**.
- **check_run** responds to Checks API activity, such as completion of a third-party check. Filter activity types and inspect the check identity and conclusion before acting.
Variables, contexts and scope
- Define **env** as a YAML mapping at workflow, job or step scope, such as **MY_VARIABLE: my-value**. The most specific applicable definition wins; step scope is the narrowest.
- Shell expansion happens on the runner: Bash uses **$MY_VARIABLE** and PowerShell uses **$env:MY_VARIABLE**. Expressions such as **${{ env.MY_VARIABLE }}** are evaluated by Actions in supported fields.
- **GITHUB_ACTOR** identifies the initiating actor; **GITHUB_REPOSITORY** is owner/repository; **GITHUB_WORKSPACE** is the workspace path. Check out the repository when its files are needed.
- **GITHUB_REF** is the triggering fully qualified ref, which can be a branch, tag or pull-request merge ref. **GITHUB_RUN_NUMBER** numbers runs of a particular workflow.
- Use **${{ github.run_number }}** in expressions and **$GITHUB_RUN_NUMBER** in Bash. Default **GITHUB_*** and **RUNNER_*** variables are provided by the platform; do not redefine them.
- **vars** exposes configuration variables; **secrets** exposes permitted sensitive values. **defaults.run** selects defaults such as shell and working directory; it does not define environment variables.
Environment files and job outputs
- In Bash, **echo "FOO=bar" >> "$GITHUB_ENV"** makes FOO available to later steps in the same job. The writing step does not receive the new value automatically; a shell **export** alone does not persist to later steps.
- **echo "result=value" >> "$GITHUB_OUTPUT"** sets a step output. Give the step an **id**, then read **${{ steps.build.outputs.result }}** when its id is build.
- Map a step output to **jobs.build.outputs.result**. A downstream job declares **needs: build** and reads **${{ needs.build.outputs.result }}**.
- Use **outputs** for small values such as identifiers and image digests. Use **artifacts** for files passed between jobs; each job has its own execution environment.
- Environment files are platform-provided paths. In PowerShell, append through **$env:GITHUB_ENV** or **$env:GITHUB_OUTPUT**. Avoid obsolete **set-env** and **set-output** command syntax.
Caches, artifacts and storage
- A **cache** speeds reuse of dependencies or other recreatable files across jobs and runs. An **artifact** preserves run products such as binaries, test results and reports for later download.
- **actions/cache** requires **path** and **key**. Include relevant OS, toolchain and lockfile information in the key; **hashFiles()** can detect dependency changes.
- **restore-keys** supplies fallback key prefixes. **cache-hit** indicates an exact primary-key match; a restored fallback can still require dependency installation. Treat caches as disposable and exclude secrets.
- Upload files with **actions/upload-artifact** and retrieve them with **actions/download-artifact**. A dependent job still needs an explicit dependency if it must wait for the producer.
- Users need repository **read access** to download workflow artifacts. Manage artifact and log retention, delete unneeded artifacts, and review package storage separately; self-hosted compute does not remove hosted storage usage.
Action consumption, creation and reuse
Discover and reference actions
- Review an action's **README**, publisher, repository code, requested permissions and maintenance before adoption. A verified publisher helps establish identity; still assess the action's behavior.
- Reference repository actions with **owner/repo[/path]@ref**, local actions with **./path**, or a published container with **docker://image:tag**. Local actions require their files to be present on the runner.
- A full **commit SHA** fixes the referenced code. A branch or release tag can move; a major tag such as **@v1** is convenient for receiving compatible updates but is mutable.
- An action's **action.yml** or **action.yaml** defines its interface and execution configuration. Inspect **inputs**, **outputs** and **runs**; pass inputs with **with**.
- Private or internal action sharing requires compatible repository visibility, access settings and consumer policies. Internal visibility does not grant arbitrary public repositories access.
Choose a custom action type
- A **JavaScript action** declares a supported Node runtime in **runs.using** and an entry file in **runs.main**. Compile TypeScript to JavaScript and ship the executable code and dependencies.
- A **composite action** uses **runs.using: composite** to bundle run steps and other actions. Specify a shell for its run steps and map declared outputs to internal step outputs.
- A **Docker container action** uses **runs.using: docker** and **runs.image**, which identifies a Dockerfile or container image. A source-built action includes its **Dockerfile** and action metadata.
- Docker actions require a **Linux runner with Docker**. A container can package Python or another runtime; there is no separate native Python action type.
- Choose a direct **run** step for one workflow's script, a **composite action** for reusable step sequences, and a **reusable workflow** for shared job orchestration.
Action behavior and distribution
- The JavaScript **@actions/core** toolkit reads inputs, sets outputs, exports variables and writes annotations. **@actions/github** supplies GitHub API and event-context helpers.
- **core.warning()** creates a warning annotation; **core.notice()** creates a notice; **core.info()** writes informational logs. **core.setFailed()** marks failure; a nonzero process exit also signals failure.
- Test action logic and exercise it in a small workflow on its supported runners. Bundlers such as **ncc** package dependencies; compilation alone does not validate workflow behavior.
- A separate **action repository** permits independent releases, clearer issue ownership and easier discovery. Document purpose, inputs, outputs, permissions and a working usage example.
- Marketplace publication requires a **public repository** and action metadata at its root. Follow naming eligibility and publication requirements; an action can be consumed without a Marketplace listing.
Reusable workflows and starter workflows
- A reusable workflow lives in **.github/workflows/** and includes **on: workflow_call**. Call it with job-level **uses**, rather than a step-level action reference.
- Use **owner/repo/.github/workflows/file.yml@ref** across repositories, or **./.github/workflows/file.yml** within the same repository. Declare typed inputs and named secrets at the reusable workflow boundary.
- The caller passes inputs through **with** and secrets through **secrets**. Eligible callers can use **secrets: inherit**; permissions in a chain of reusable workflows cannot be elevated beyond the caller's grant.
- For environment-specific deployment, pass a target input and select **environment** on the deploying job inside the called workflow. Pass required secrets explicitly or through supported inheritance; an applicable environment secret takes precedence.
- An organization's **.github/workflow-templates/** directory holds starter workflow files and their properties metadata. Users select starters through **Actions > New workflow**; the resulting copy does not automatically track future template changes.
Secrets, permissions and deployment control
Secret scope and secure handling
- **Organization secrets** centralize values for all or selected eligible repositories. **Repository secrets** specialize one repository. **Environment secrets** belong to a repository environment and are available to jobs that reference it.
- For the same secret name, an applicable **environment** value overrides a **repository** value, which overrides an **organization** value. Reuse one logical name with different values for different deployment targets.
- Reference a value through **${{ secrets.NAME }}** and expose it only to steps that need it. Do not publish secrets as outputs, artifacts, cache contents or log messages.
- Secrets cannot be referenced directly in **if** expressions. For a step condition, place the secret in a job-level **env** variable and test that variable without printing it.
- For a file too large for an encrypted secret, encrypt it before committing the ciphertext and store the decryption passphrase as a secret. Decrypt only when needed; prevent plaintext and decrypted content from reaching logs.
- Use an external **secret manager** when centralized runtime retrieval and rotation are required. A workflow secret is not automatically available to a deployed application; configure its runtime secret delivery deliberately.
Tokens and trust boundaries
- **GITHUB_TOKEN** is an automatically issued, short-lived installation token scoped to the workflow repository. Use **${{ secrets.GITHUB_TOKEN }}** or **${{ github.token }}** for permitted GitHub API calls and action inputs.
- Set **permissions** at workflow or job scope for least privilege. Creating issues needs **issues: write**; publishing packages needs **packages: write**. Changing permissions configures the token rather than rotating a stored secret.
- Some actions can access **github.token** automatically. Review every action that runs in a job with write permissions; the token is not a general-purpose organization administration credential.
- Use **OIDC** federation for supported cloud or vault integrations instead of a long-lived cloud key. **id-token: write** permits requesting an identity token; the destination's trust policy determines resource access.
- Treat pull-request content, event payloads and downloaded artifacts as **untrusted input**. Pass values through quoted environment variables instead of interpolating them into shell code, and isolate privileged follow-up workflows from untrusted code.
Environments and concurrency
- Create deployment **environments** in repository settings and reference the target with job-level **environment**. Required reviewers and wait timers are protection rules, subject to feature availability.
- An environment's protected job must satisfy its rules before proceeding and receiving environment secrets. Configure production approvers as required reviewers; repository write access alone is not the approval gate.
- **Deployment branch and tag rules** restrict eligible refs. Environment protection, branch protection and workflow trigger filters enforce different boundaries.
- A shared **concurrency.group** serializes deployments to the same target. Use a consistent group across relevant workflows; merely naming an environment does not create a deployment mutex.
- Choose **cancel-in-progress** deliberately: cancelling an active deployment can leave partial changes. A waiting deployment is also subject to workflow and approval limits; investigate unmet rules rather than assuming a runner failure.
Publish container images
- Publishing to **GitHub Container Registry** follows three operations: authenticate to **ghcr.io**, build the image, and push the tagged image.
- Name images as **ghcr.io/owner/image:tag**. In an authorized workflow, grant **packages: write** and authenticate with **GITHUB_TOKEN**; existing package access settings must also permit the repository.
- Use a commit-derived tag or immutable **image digest** for deployment traceability. Pulling an image consumes it; pushing publishes it. Keep registry credentials out of image layers and build logs.
Runners, troubleshooting and enterprise governance
Runner ownership and routing
- **GitHub-hosted runners** provide managed Linux, Windows and macOS environments. GitHub maintains their runner images and operating systems; use explicit caches or artifacts instead of assuming persistent local files.
- **Self-hosted runners** suit specialized hardware, custom OS or tool requirements, and private-network access. You operate their capacity, software, patching, connectivity and isolation.
- Runner **labels** describe capabilities. **runs-on: [self-hosted, windows, x64]** requires a runner matching every label; custom labels can identify a GPU, toolchain or installed software.
- Runner **groups** govern which repositories or workflows may use a pool. Groups control access; labels route jobs by capability. A label does not install software or guarantee it remains correct.
- For organizations with an **IP allow list**, use runners with permitted egress addresses, such as self-hosted runners or supported larger runners with static IPs. Standard hosted runner addresses are not automatically trusted.
Container jobs and services
- Job-level **container** runs steps in a chosen container. **services** supplies sidecars such as PostgreSQL or Redis for that job; GitHub creates and removes service containers with the job lifecycle.
- Container jobs, service containers and Docker container actions need a **Linux host with Docker**. Installing Docker on a Windows runner does not satisfy that execution model.
- When the job runs in a container, reach a service by its **service label** and container port on the shared network. When steps run directly on the host, publish service ports and connect through **localhost**.
- Add service **health checks** before tests depend on readiness. Job-scoped services avoid leaving a database installed on a persistent runner; separately clean any host files or external volumes your workflow creates.
Logs, annotations and run management
- Open the repository's **Actions** tab, choose a workflow run, then inspect the failed job and step. Compare **Set up job** logs with a successful run to identify the runner and environment changes.
- Download workflow logs with **GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs** using suitable authentication. Distinguish run logs from separately uploaded workflow artifacts.
- For self-hosted disconnections, inspect the runner installation's **_diag** directory. **Runner_*.log** covers runner activity; **Worker_*.log** covers individual job execution. Check service state, network access and resource pressure.
- A queued job may lack an online, idle, authorized runner matching all labels. Inspect labels, group access and runner health before changing usage limits.
- Use **echo "::debug::message"** for debug logging and enable **ACTIONS_STEP_DEBUG** when needed. **ACTIONS_RUNNER_DEBUG** adds runner diagnostics; avoid exposing sensitive values.
- Annotations use **::warning::message** or **::error::message**. Add location properties with **::error file=main.py,line=10,col=15::message**; an error annotation alone does not set a failing process exit code.
- **::add-mask::value** masks a sensitive value in later logs. Disable a workflow to stop new triggers during an incident; cancel active runs separately. Completed runs can be deleted with appropriate repository permissions.
Enterprise policy and shared automation
- Enterprise and organization **Actions policies** can limit allowed actions and reusable workflows. An allow policy may select enterprise-owned code, GitHub-authored actions, verified publishers or explicitly approved references.
- A lower-level policy cannot bypass a higher-level restriction. Where only internally owned actions are allowed, host approved action code in permitted repositories and configure access for its consumers.
- Combine centralized reusable workflows, reviewed custom actions, starter workflows and selected-repository secrets to standardize automation. Keep releases and ownership explicit; Marketplace is not an internal distribution partition.
- **GitHub Enterprise Server** controls access to GitHub.com actions through administrator configuration. GitHub Connect can enable permitted external actions; disconnected installations can synchronize approved action repositories instead.
- For Enterprise Server, check action-runtime and platform compatibility against the installed release. External services still require network connectivity, while locally available automation need not rely on unrestricted internet access.