# GitHub Actions over Jenkins

> A YAML file, a managed runner, and ordinary Bash or JavaScript when the job gets interesting. Why GitHub Actions is my default for a repository already on GitHub.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-03-13
- Tags: GitHub Actions, Jenkins, CI/CD, YAML, JavaScript, Bash, Groovy
- URL: https://deyanpeev.com/posts/github-actions-over-jenkins

Jenkins can run almost anything. I've used it for automated validation,
and that flexibility is real. So is the work around the pipeline. You prepare
agents, keep plugins compatible, manage credentials, and then try to work out
why a piece of perfectly reasonable Groovy behaves differently inside a
Jenkinsfile.

For a new project already hosted on GitHub, I would start with GitHub Actions.
The tests live in the repository, the workflow sits beside them in one file,
and the result shows up on the pull request.

What I like is how little infrastructure I need before the first useful
build, and that the code can stay ordinary after that.

# Start with the same job

Take a Node.js application with a committed `package-lock.json` and npm
scripts called `lint`, `test`, and `build`. A Jenkins declarative pipeline
might look like this:

```groovy
pipeline {
  agent { label 'linux' }
  tools { nodejs 'node-16' }

  stages {
    stage('Install') {
      steps { sh 'npm ci' }
    }
    stage('Lint') {
      steps { sh 'npm run lint' }
    }
    stage('Test') {
      steps { sh 'npm test' }
    }
    stage('Build') {
      steps { sh 'npm run build' }
    }
  }
}
```

That's readable. But it assumes a working Jenkins controller, an available
Linux agent, the NodeJS plugin, and a tool installation configured under the
name `node-16`. In a multibranch Pipeline job Jenkins can check out the
repository automatically, though the GitHub integration and credentials still
need to be in place.

The GitHub Actions version goes in `.github/workflows/ci.yml`:

```yaml
name: CI

on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '16'
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test
      - run: npm run build
```

Commit it to an Actions-enabled repository and GitHub handles the event,
allocates a runner, and shows the logs and result alongside the code. There's
no separate job to create in another application.

The versions here are available today: [checkout v3 shipped on March 1](https://github.com/actions/checkout/releases/tag/v3.0.0),
and [setup-node v3 on February 24](https://github.com/actions/setup-node/releases/tag/v3.0.0).
Node.js 16 is the application runtime in this example. I also named the
Ubuntu image explicitly so the intended operating-system version is visible,
although GitHub still updates the software within that image.

# YAML is a small language to learn

The useful vocabulary is short. `on` describes the events. `jobs` describes
the work. `runs-on` selects the machine. `steps` execute in order inside a
job. `uses` calls an action, `run` executes a command and `with` supplies inputs.

I can read the workflow from top to bottom without learning Groovy closures,
the Jenkins Pipeline DSL, or the controller's script approval rules. The
indentation matters (it's YAML), and GitHub's expressions are one more syntax
to learn, but a basic build needs very little of either.

Testing two Node versions is a good example of the configuration being
useful. This replaces the `jobs` section above:

```yaml
jobs:
  test:
    runs-on: ubuntu-20.04
    strategy:
      matrix:
        node: ['14', '16']
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node }}
          cache: npm
      - run: npm ci
      - run: npm test
```

GitHub expands that into two jobs, each with its own runner. Jenkins has
matrix support too, but here the runners and the Node installation are
already part of the same small declaration. One thing the
[setup-node documentation](https://github.com/actions/setup-node/blob/v3.0.0/README.md)
is careful about is that its npm cache stores package-manager data, not
`node_modules`. So `npm ci` still installs the locked dependencies.

# When configuration runs out, use Bash

YAML is good at describing steps and a poor place to implement an
algorithm. A multiline `run: |` block gives me a normal shell script when
there's a bit more work to do.

For an application whose build writes `dist/`, add these steps after the
build:

```yaml
      - name: Package the build
        shell: bash
        env:
          COMMIT_SHA: ${{ github.sha }}
        run: |
          set -euo pipefail
          mkdir -p artifacts
          archive="app-${COMMIT_SHA:0:8}.tar.gz"
          tar -czf "artifacts/$archive" -C dist .
          sha256sum "artifacts/$archive" > "artifacts/$archive.sha256"

      - uses: actions/upload-artifact@v3
        with:
          name: application
          path: artifacts/
```

It's just Bash, with ordinary variables, quoting, and command-line tools. The
artifact action makes the archive and checksum downloadable from the run
([its v3 release arrived on March 3](https://github.com/actions/upload-artifact/releases/tag/v3.0.0)).

When the block grows, move it to `ci/package.sh` and call
`bash ci/package.sh`. Then I can run the same script locally. Each `run`
step starts a new shell, so an `export` in one step doesn't carry into the
next. Files do stay available to later steps in the same job.

Jenkins can call Bash as well, of course. What is better here is the short
path from a repository to a machine executing it, with the surrounding setup
visible in the workflow.

# JavaScript for the parts that need actual code

Shell is excellent for invoking tools. Once I'm manipulating JSON or
calling an API, I'd usually rather write JavaScript.

`actions/github-script` supplies an authenticated GitHub API client and the
event context. For example, this separate workflow labels a newly opened
issue when its title starts with `[bug]`. Create the `bug` label in the
repository first, then save this as `.github/workflows/label-issues.yml`:

```yaml
name: Label bug reports

on:
  issues:
    types: [opened]

permissions:
  issues: write

jobs:
  label:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/github-script@v6
        with:
          script: |
            const issue = context.payload.issue;
            if (!issue.title.toLowerCase().startsWith('[bug]')) return;

            await github.rest.issues.addLabels({
              ...context.repo,
              issue_number: issue.number,
              labels: ['bug']
            });
```

No checkout is needed because this job only calls the API. There's no
personal access token to generate for this either. The action uses the
workflow's `GITHUB_TOKEN`, with the issue permission declared above.

[Version 6 runs on Node.js 16](https://github.com/actions/github-script/blob/v6.0.0/README.md).
That means ordinary `const`, object spread, and `async`/`await`. The issue
title is read as data from `context`, it is not interpolated into the
JavaScript source. And I get familiar language semantics, without Jenkins
serializing my local variables across pipeline steps.

For larger logic, I can check out the repository and load a separate module,
or run a Node script directly. npm packages, local tests, and the debugger
I already use are all still there. If the team prefers TypeScript, compile it
to JavaScript first. The action runtime doesn't execute TypeScript directly.

Reusable JavaScript actions can also package that logic for other
repositories. Dependencies need to ship with the action, commonly bundled
into a distribution file, but consumers get a simple `uses` entry. A
JavaScript action can run on Linux, Windows, and macOS without needing a
Docker container, provided its own code and dependencies support those
platforms.

# The library removes a lot of glue

The [GitHub Marketplace](https://github.com/marketplace?type=actions) is one
of the strongest arguments for Actions. Checking out code, installing a
language runtime, caching dependencies, saving artifacts, authenticating to
a cloud, building a Docker image - these are common problems and there are
reusable actions for them already.

The first workflow uses that library twice before it reaches an application
command. `setup-node` alone handles finding or downloading Node, updating
`PATH`, and restoring an npm cache. That's several pieces of setup I don't
have to maintain in a shell script.

Jenkins has a rich plugin ecosystem too. The difference for me is that an
action reference belongs to the workflow in the repository, so I can
review a version change in a pull request instead of changing a plugin
installation shared by unrelated jobs on a controller.

An action still executes somebody else's code. I check its source and
maintenance before giving it credentials. Major tags such as `@v3` keep
these examples readable and accept updates within that major version. A
full commit SHA gives a workflow an immutable action reference when I
need that.

# Managed runners are the bigger saving

With GitHub-hosted runners, GitHub operates the machines. A job gets a fresh
environment, so yesterday's workspace doesn't become today's dependency. Linux,
Windows, and macOS are available without maintaining my own fleet for each
operating system.

I still own the build, dependency choices, permissions, and deployment
logic. But I don't have a Jenkins controller to patch, back up, or recover,
and I do not need to repair an idle build agent before I can test a change.

The GitHub integration helps in smaller ways too. Pull-request checks,
logs, repository secrets, and manual workflow runs are in the same place
as the code review, and a required check can gate merging through branch
protection.

# The free minutes make trying it easy

Public repositories can use GitHub-hosted Actions for free, subject to the
service's usage limits. Private repositories get a monthly allowance tied
to the owning account, shared across its repositories.

GitHub Free includes **2,000 minutes per month and 500 MB of storage**.
GitHub Pro includes 3,000 minutes and 1 GB, and GitHub Team 3,000
minutes and 2 GB. Windows jobs consume the allowance at twice the Linux
rate, and macOS at ten times the rate. Those are the
[current billing terms](https://github.com/github/docs/blob/2f88a09341ecc7d0eccbafae92a6f0edefe9d128/content/billing/managing-billing-for-github-actions/about-billing-for-github-actions.md).

As a simple example, 200 builds with one five-minute Linux job each consume
1,000 minutes. Run every build against both Node 14 and 16, with each job
taking five minutes, and that becomes 2,000. Parallel execution reduces the
waiting time but it doesn't reduce the minutes used. GitHub also rounds each
job up to a whole minute.

Beyond the allowance, Linux minutes cost $0.008, Windows $0.016, and macOS
$0.08 when paid overages are enabled. Storage has its own billing, and a
spending limit controls whether additional paid usage is allowed, as
described in the same billing documentation.

Jenkins has no licence fee, but its machines, storage, and the time spent
operating it still cost something. For a small project the included Actions
allowance can cover the build workload, and a lot of that operational work
goes away.

# Reasons to stay on Jenkins

An established Jenkins installation with a team maintaining it is a
different decision from starting a new project. Private-network access,
special hardware, long-running jobs, and extensive existing shared
libraries can all justify staying with it.

Actions has self-hosted runners for work that needs your own machines, but
then maintaining them is your job again. It also has service limits, it
depends on GitHub being available, and it ties the workflow to GitHub's event
model and expression syntax. And deeply nested YAML can get just as
unpleasant as an oversized Jenkinsfile.

For a new repository on GitHub, though, I'd still go with Actions. Jobs
described in YAML, tools invoked from Bash, the complicated parts written in
JavaScript, and maintained actions for the common setup.
