GH-200 Cheatsheet
GitHub Actions
Download free PDFAuthor and manage workflows (20–25%)
Workflow structure and scripts
- Store workflow YAML in **.github/workflows/**. The **on** key selects triggers; **jobs** defines work; **runs-on** selects a runner; each job contains ordered **steps**.
- A **uses** step invokes an action; a **run** step executes commands on the runner or in the job container. Check out repository content before running scripts or local actions that need it.
- Use **run: |** for a multiline script. Set **shell: bash**, **shell: python** or **shell: pwsh** for the interpreter; PowerShell can run on Linux when installed.
- Use **working-directory** on a run step, or **defaults.run.working-directory** for shared defaults. In a composite action, set it on the relevant run step.
- Install project dependencies with **npm ci** when using a lockfile, then run **npm run build**. Install an additional npm package through **npm install** in a run step; setup actions select the runtime.
Events, filters and schedules
- Use **on: [push, pull_request]** for multiple simple events. Use an event mapping when adding activity **types**, **branches**, **tags** or **paths** filters.
- For **pull_request**, branch filters match the target branch. Combine **types: [labeled]**, a target branch filter and a **paths** filter for files under apps/ to narrow the trigger; inspect the label in a job condition when selecting a deployment.
- **workflow_dispatch** enables manual runs through the Actions UI, CLI or API. Declare optional typed **inputs** with descriptions, defaults and required flags; the workflow must exist on the default branch.
- **repository_dispatch** receives externally initiated activity through the API. Filter its custom event type and read supplied data through **github.event.client_payload**.
- **schedule** contains a list of **cron** entries. The UTC expression **45 7 * * 3,6** means 07:45 on Wednesday and Saturday; scheduled runs use the latest default-branch commit and may be delayed.
- **workflow_run** can start a workflow after another completes; test **github.event.workflow_run.conclusion == 'success'** before deployment. **check_run** handles check activity, while **issues** and **issue_comment** handle issue and comment events.
Variables, contexts and conditions
- Define custom **env** mappings at workflow, job or step scope. The most specific scope wins. A shell export applies to that step's process; it does not persist into later steps.
- In Bash, read **$MY_VARIABLE**; in PowerShell, read **$env:MY_VARIABLE**. Use **${{ env.MY_VARIABLE }}** in supported workflow expressions and **${{ vars.NAME }}** for configuration variables.
- Default variables include **GITHUB_REPOSITORY** for owner/repository, **GITHUB_ACTOR** for the initiating user or app, **GITHUB_REF** for the full ref and **GITHUB_RUN_NUMBER** for the workflow's run number.
- Expression equivalents include **github.repository**, **github.actor**, **github.ref**, **github.ref_name** and **github.run_number**. Default GITHUB_* variables are not automatically entries in the env context.
- Use job or step **if** conditions for conditional execution, such as **github.ref_name == 'feature-branch'**. Pull request refs can be merge refs; use **github.head_ref** when the source branch is required.
- A **strategy.matrix** generates jobs for combinations such as Node versions and operating systems. Read values through **matrix**, remove combinations with **exclude**, add them with **include**, and control parallelism with **max-parallel**.
Outputs and file transfer
- Write **echo "FOO=bar" >> "$GITHUB_ENV"** to expose a value to later steps in the same job. The producing step does not receive the new value automatically; this file does not transfer values between jobs.
- Write **echo "color=purple" >> "$GITHUB_OUTPUT"** in a step with an **id**. Later steps read **${{ steps.step_id.outputs.color }}**. Use environment files rather than deprecated set-env or set-output commands.
- Map step outputs under **jobs.<job_id>.outputs**. A downstream job declares **needs: job1** and reads **${{ needs.job1.outputs.output1 }}**; jobs otherwise run independently when resources permit.
- Use **artifacts** for files produced by jobs. Upload in the producing job and download in the consuming job; use **needs** when the consumer must wait for the upload. Job outputs suit small named values.
Consume and troubleshoot workflows (15–20%)
Reuse and workflow templates
- A **reusable workflow** declares **on: workflow_call** and stays in **.github/workflows/**. Call it at job level with **uses: owner/repo/.github/workflows/file.yml@ref**; a same-repository call can use **./.github/workflows/file.yml**.
- Declare reusable workflow **inputs**, **secrets** and **outputs** in workflow_call. The caller passes inputs with **with** and secrets with **secrets**; **secrets: inherit** is available for supported organization or enterprise relationships.
- Map reusable workflow outputs from job outputs. The caller reads them through **needs.<called_job>.outputs.<name>**. Caller permissions cannot be elevated by the called workflow.
- Store organization starter workflows in the **workflow-templates/** directory of its **.github** repository, with matching **.properties.json** metadata. A starter workflow is copied into the consuming repository and then evolves independently.
- A **composite action** bundles steps inside a job. A **reusable workflow** can define multiple jobs. Central reusable definitions reduce duplicated maintenance; starter workflows provide a consistent starting scaffold.
Logs, debugging and run control
- In the **Actions** tab, open a workflow run, select its job and expand the failed step. Read the first relevant error and the **Set up job** details to identify the runner image and environment.
- Set the repository secret or variable **ACTIONS_STEP_DEBUG** to **true** for detailed step messages. **ACTIONS_RUNNER_DEBUG** enables runner diagnostics; choose diagnostic logging when rerunning a workflow as needed.
- Workflow commands such as **echo "::debug::message"** and **echo "::error::message"** annotate logs. An error annotation alone does not fail a step; use a nonzero exit status or an action failure API.
- Download run logs through **GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs**. Repository read access allows downloading workflow artifacts; private repository access still requires authentication.
- **Disable** a workflow to stop new triggers while retaining its file and history, for example during an external service outage. Completed runs can be deleted by users with write access; deleting a run also removes its artifacts.
Packages, containers and releases
- For **GitHub Container Registry**, authenticate to **ghcr.io**, build and tag the image, then push it. Grant the workflow token **packages: write** and ensure package access permits the operation.
- For npm publishing, configure the target **registry** and authentication token, then run **npm publish**. npmjs.org and GitHub Packages are different registries with different authentication requirements.
- A publish job with **needs: build** waits for a successful build by default. An **if** condition can further restrict publishing to a tag, release or approved branch.
- Use **gh release create <tag> <asset-files>** to create a release and attach distributable files, with suitable **contents: write** permission. A Git tag, workflow artifact and release asset are separate objects.
Author and maintain actions (15–20%)
Action types and metadata
- **action.yml** or **action.yaml** defines an action's name, description, inputs, outputs and **runs** configuration. Inspect this contract before consuming an action; pass its inputs through the step's **with** mapping.
- A **JavaScript action** uses a supported Node runtime in **runs.using** and an entry script in **runs.main**. Compile TypeScript to JavaScript and ship runnable code and dependencies, commonly as a bundled distribution.
- A **Docker container action** uses **runs.using: docker** and **runs.image**, referencing a Dockerfile or an existing image. It requires a Linux runner with Docker; a Dockerfile is needed when building the image from source.
- A **composite action** uses **runs.using: composite** with **runs.steps**. It combines run steps and other actions; specify a **shell** for each run step and use **github.action_path** to locate bundled scripts.
- Declare an output under **outputs**, for example **foo** with a description. A composite output also maps **value** to a step output; JavaScript and Docker actions set outputs at runtime.
Action behavior and testing
- The **@actions/core** toolkit reads inputs, sets outputs, logs messages and reports failure. Catch JavaScript errors and call **core.setFailed(error.message)** so the action reports a failed result.
- JavaScript metadata supports **pre**, **main** and **post** entry scripts. Use **pre-if** or **post-if** to conditionally execute lifecycle scripts, for example **pre-if: github.event_name == 'push'**.
- A nonzero process **exit code** fails a script step or action by default. **continue-on-error** changes how the failure affects the job; logging an error and failing execution serve different purposes.
- Test an action through a small workflow that invokes it with representative inputs. Exercise success, invalid inputs and failure paths; bundling with a tool such as **ncc** packages code but does not test behavior.
Distribution and versioning
- Reference an action as **owner/repo/path@ref**, a checked-out local path such as **./.github/actions/build**, or a container reference such as **docker://image:tag**. An npm package is not directly a uses target.
- A reference such as **owner/action@v1** selects a major release tag; a branch or tag can move. A **full commit SHA** identifies fixed repository content and is the strongest pin for a third-party repository action.
- Keep broadly shared actions in dedicated repositories for independent releases, issue tracking and discovery. Document purpose, inputs, outputs, permissions, prerequisites and a working usage example.
- **GitHub Marketplace** helps discover and distribute actions. Check the publisher, code and maintenance; a verified creator badge identifies a verified partner organization and is not a code security review.
- Marketplace publication requires a **public repository**, a root **action.yml** or **action.yaml**, an eligible unique action name and acceptance of the publishing agreement. Publish a tagged release; the name must not collide with existing actions or Marketplace categories.
Manage GitHub Actions for the enterprise (20–25%)
Runner selection and lifecycle
- **GitHub-hosted runners** provide managed Linux, Windows and macOS images with preinstalled tools and maintained operating systems. Check image documentation for available software; do not rely on filesystem state carrying across jobs.
- Choose **self-hosted runners** for specialized hardware, custom operating systems, installed toolchains or access to private networks. You manage machine security, software, capacity, availability and cleanup.
- A label array uses **AND** matching: **runs-on: [self-hosted, linux, custom-software]** requires every label. A custom label such as **runner1** selects one machine only when uniquely assigned; it does not have to match its hostname.
- Use OS and architecture labels such as **[self-hosted, windows, x64]** where applicable. Add custom labels for precise toolchains; labels describe capability, while **runner groups** govern repository access to a runner pool.
- Hosted jobs have a **6-hour** execution limit; self-hosted jobs can execute for up to **5 days**. Longer work still needs suitable timeouts, checkpoints and reliable runner availability.
Containers, networking and diagnostics
- Define dependencies such as Redis under job **services** for a service container with a job-scoped lifecycle. The optional job **container** defines where job steps execute. Both require a Linux runner with Docker.
- Container jobs reach services by their service label on the container network. Jobs running directly on the host use published ports through **localhost**; add health checks before dependent tests.
- For an organization **IP allow list**, use runner egress addresses that satisfy the policy. Self-hosted runners can provide known addresses; eligible larger hosted runners support static IP configurations.
- For a queued job, check runner availability, matching labels, group access and network connectivity. Compare the last successful run's **Set up job** details and inspect **_diag/Runner_*.log** on the self-hosted machine.
- Self-hosted machines may retain state between jobs. Clean workspaces and service data, keep software patched, and isolate untrusted pull request code from persistent runners and privileged networks.
Organization policy and sharing
- Enterprise and organization **Actions policies** control whether Actions runs and which actions or reusable workflows are permitted. Use approved repositories and allowed references to enforce shared automation standards.
- Sharing from a **private or internal repository** requires compatible visibility and configured Actions access for the consuming repositories. Repository visibility alone does not grant unrestricted workflow use.
- An organization-only policy can distribute automation through repositories owned by that organization. Combine central reusable workflows, shared actions and starter workflows; Marketplace publication is not required for internal reuse.
- On **GitHub Enterprise Server**, administrators enable Actions and provision self-hosted runners. Use **GitHub Connect** for permitted GitHub.com actions or manually synchronize required actions in restricted environments.
Secret scopes and runtime delivery
- Store API keys, licenses and credentials as **encrypted secrets**, not plain configuration variables or committed files. Reference them through **${{ secrets.NAME }}** and pass them only to steps that need them.
- An **organization secret** can serve all eligible repositories or **selected repositories**. A repository secret narrows scope; an environment secret serves jobs that reference that environment.
- For the same secret name, **environment** scope takes precedence over **repository**, which takes precedence over **organization**. This permits repository-specific or environment-specific values without renaming workflow references.
- Environment secrets become available after protection rules pass. In a reusable workflow, a job that selects an environment uses that environment's secrets; workflow_call does not itself pass an environment from the caller.
- For a large sensitive file, encrypt it before committing the ciphertext and keep the decryption passphrase in a secret. Decrypt only when needed; Base64 is encoding, and decrypted file contents are not automatically masked.
- A deployment credential and an application's **runtime secret** have different lifecycles. Deliver runtime values through the target platform's secret mechanism or a shared external vault; GitHub secrets do not automatically become application runtime settings.
Secure and optimize automation (10–15%)
Tokens, federation and input safety
- **GITHUB_TOKEN** is a short-lived token supplied for a job and scoped to the repository. Use it for authenticated GitHub API calls, issues, releases or packages when its granted permissions allow the operation.
- Set least-privilege **permissions** at workflow or job scope, such as **contents: read**, **issues: write** or **packages: write**. It is not a general organization administration token; broader access may require a suitably scoped GitHub App token.
- Pass a token explicitly when an action input or API client requires it. Actions may also access **github.token**; checkout normally uses the provided token without a separate manual token input.
- **OpenID Connect (OIDC)** exchanges a workflow identity for short-lived cloud credentials. Grant **id-token: write** and configure the cloud or vault trust policy for the intended repository, ref or environment; this is separate from Enterprise Managed Users.
- Treat issue titles, pull request fields and dispatch inputs as untrusted. Pass values through environment variables and quote shell expansions rather than interpolating expressions directly into executable script text.
- Use **::add-mask::** for additional sensitive log values and avoid printing credentials. Fork pull requests normally receive restricted tokens and no repository secrets; privileged workflow_run or pull_request_target jobs must not execute untrusted code.
Deployment protection and concurrency
- Create deployment **environments** in repository settings and reference one with the job's **environment** key. Configure **required reviewers**, a **wait timer** or allowed deployment branches and tags as needed.
- Required reviewers gate a deployment job before it proceeds and receives environment secrets. An environment approval can wait up to **30 days**; protection features depend on repository visibility and plan.
- Set a shared **concurrency.group** for deployments to the same target. **cancel-in-progress** controls cancellation of active work; selecting an environment alone does not serialize deployments.
- Use an environment name as an explicit reusable workflow input when the called workflow selects its deployment environment. Keep cloud-specific credentials in separate environments and reuse the same secret names.
Caching, retention and efficiency
- A **cache** accelerates reuse of dependencies or other regenerable files across runs. An **artifact** preserves job results for later jobs or download after the workflow; a package registry distributes versioned packages.
- The cache action requires **path** and **key**. Include platform and dependency lockfile hashes in the key; optional **restore-keys** provide fallback matches. **cache-hit** reports whether the primary key matched exactly.
- Caches are subject to access scope and eviction, so workflows must tolerate a miss. Avoid storing credentials in caches, and do not treat a cache as durable storage for release deliverables.
- Control artifact and log **retention**, use artifact **retention-days** within policy limits, and delete obsolete artifacts or runs. Package cleanup is separate; switching to self-hosted runners does not remove artifact storage usage.