chan.dev / posts

Schedule Netlify Builds with GitHub Actions, Cron, and Webhooks

Instructions

Add this GitHub Action to your repo at .github/workflows/schedule-netlify-build.yml

.github/workflows/schedule-netlify-build.yml
name: Schedule Netlify Build
on:
schedule:
# Customize schedule expression at crontab.guru
# This one runs at 800 UTC daily
- cron: '0 8 * * *'
jobs:
build:
name: Call Netlify build hook
runs-on: ubuntu-latest
steps:
- name: Curl request
run: curl -X POST -d {} #YOUR_BUILD_HOOK_URL#

Tailor your cron schedule

Determine a build schedule and use crontab.guru to describe it as a cron schedule expression.

# This one runs at 800 UTC daily
- cron: "0 8 * * *"
# This one runs every 6 hours
- cron: "* */6 * * *"

Generate a Netlify build hook

Netlify build hooks are webhooks with one function: re-build your site when called. Any POST request to your Netlify build hook triggers a build.

Generate a new build hook here: Site settings > Build & deploy > Continuous deployment > Build hooks.

Settings path: Site settings > Build & deploy > Continuous deployment > Build hooks Image from Netlify build hooks documentation

You have to name your hook. The name doesn’t make much difference as long as it’s unique and descriptive to you.

Paste your build hook into the GitHub Action

run: curl -X POST -d {} #YOUR_BUILD_HOOK_URL#
run: curl -X POST -d {} https://api.netlify.com/build_hooks/#GENERATED_BUILD_HOOK_URL

Push!

Push your new workflow up to your repository and watch the Actions tab. You’ll seeing scheduled jobs show up, according to your schedule.

Here’s what to expect: https://github.com/LunchDevCommunity/community-calendar/actions

Extra credit

Get fancy and ensure that nobody spams your build hook with a GitHub Action secrets.

A Story

Dynamic Site; Static Builds

Over at lunch.dev, we’ve built a calendar of events in Eleventy (a slick static site generator).

Events are listed under Upcoming and Past event headings based on their publishDate. Because Eleventy generates static sites, that deterimation happens at build time.

If we want to keep data fresh, we have to manually re-build the site at least once per day.

Using Netlify build hooks, we can automate those builds on a schedule!

There are plenty of services that will run a cron job. What I like about a GitHub Actions based solution is that everything is kept in the repo. The source can be maintained and documented with the rest of the project!

Resources

Watch me and the lunch.dev crew struggle thru this the first time

{% youtube-video “https://youtu.be/155Q4gDU1Uo” %}