In the previous post I went through using Cloudflare's wrangler
tool to set up Clouflare Workers using a config as code approach. This approach needed to be run from a local machine. While this allows changes to be tracked in version control it leaves room for what's running and what's in version control to be out of sync.
A better solution is to have changes pushed into the main branch automatically deployed into the production environment.
This post will go through taking the example from the previous post and setting it up to deploy to Cloudflare on each push to the main branch. I will do this using Github Actions.
Cloudflare have provided a base action that can be used to deploy workers from Github Actions.
To get this functioning I'll add a new file to the repository. .github/workflows/buildAndDeploy.yml
. This file will include the following text taken from the actions readme.
name: buildAndDeployWorker
on: push
jobs:
deploy:
runs-on: ubuntu-latest
name: Deploy
steps:
- uses: actions/checkout@v2
- name: Publish
uses: cloudflare/wrangler-action@1.3.0
with:
apiToken: ${{ secrets.CF_API_TOKEN }}
The ${{ secrets.CF_API_TOKEN }}
subs in a secret value that needs to be provided in the Github API. Before I can put that into Github I have to get it from Cloudflare.
To create a new token I need to:
Log in to Cloudflare, open the workers tab and then select Manage Workers.
Select API tokens.
Create a new API token
Start with the cloudflare workers template
Give the token a meaningful name
Limit the resources the token has to my account and the saladsimulator zone.
Now Cloudflare will display the API token. Once this page is closed the token is gone so I need to immediately copy it into Github. (I can re-run through the steps above to generate a new one if I need to.)
Over in github I've opened the settings tab and secrets section.
And added my secret copied from Cloudflare
Now when I push the action code it runs and deploys to Cloudflare
The logs show the successful deployment output from wrangler
.
Downloading release from https://workers.cloudflare.com/get-npm-wrangler-binary/1.19.3/x86_64-unknown-linux-musl
wrangler has been installed!
+ @cloudflare/wrangler@1.19.3
added 22 packages from 9 contributors in 2.082s
No build command specified, skipping build.
Successfully published your script to
foo.saladsimulator.com/* => stayed the same
https://foo-stage-auth.kleeut.workers.dev
Top comments (1)
Thank you for explaining how to create the API token!