GitHub Actions as CI/CD
In this lab we’re going to cover using GitHub Actions (or just Actions) for deploying your R or Python code (i.e., models, APIs, apps, etc).
To help explain/demonstrate GitHub Actions, I’ll cover a few examples I use often.
Quarto/GitHub Pages
This book is published using GitHub Pages, which is a free hosting service provided by GitHub. Quarto provides an easy Terminal command for publishing using GitHub Pages:
quarto publish gh-pages If I wanted to accomplish the same thing using GitHub Actions, I could create a workflow file in the .github/workflows directory of my repository. The workflow file would look something like this:
# .github/workflows/publish.yml
name: Publish Quarto Site to GitHub Pages
on:
push:
branches: [main]
jobs:
build-deploy:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Quarto
uses: quarto-dev/quarto-actions/setup@v2
- name: Render and Publish to GitHub Pages
uses: quarto-dev/quarto-actions/publish@v2
with:
target: gh-pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}What it does:
- This triggers on every push to
main, mirroring the behavior of runningquarto publish gh-pageslocally. - The
contents: writepermission is required so the action can push the rendered output to thegh-pagesbranch.
- The
GITHUB_TOKENis automatically provided by GitHub Actions — no manual secret setup required.
We would also have to make sure our repository’s Pages settings (Settings → Pages) is configured to deploy from the gh-pages branch.
Running Tests
You can also use GitHub Actions to run tests on your code. For example, if you have an R package, you can set up a workflow to run R CMD check on every push or pull request. Here’s an example workflow file for that:
The original _labs/lab5/publish-r-py.yml file is below for reference:
on:
workflow_dispatch:
push:
branches: main
name: Quarto Publish
jobs:
build-deploy:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Check out repository
uses: actions/checkout@v2
- name: Set up Quarto
uses: quarto-dev/quarto-actions/setup@v2
- name: Install R
uses: r-lib/actions/setup-r@v2
with:
r-version: '4.2.0'
use-public-rspm: true
- name: Setup renv and install packages
uses: r-lib/actions/setup-renv@v2
with:
cache-version: 1
env:
RENV_CONFIG_REPOS_OVERRIDE: https://packagemanager.rstudio.com/all/latest
- name: Install Python and Dependencies
uses: actions/setup-python@v4
with:
python-version: '3.10'
cache: 'pip'
- run: pip install jupyter
- run: pip install -r requirements.txt
- name: Render and Publish
uses: quarto-dev/quarto-actions/publish@v2
with:
target: gh-pages
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}