Deploying Google Cloud Run to different environments with GitHub Actions
At MisterGreen we are moving our repositories to GitHub. Coming from Bitbucket, we had to move our Bitbucket pipelines to GitHub Actions. In this post I will describe how to deploy to Google Cloud Run from GitHub:
- This blog assumes that there is an image available on gcr.io. More information on how to set this up can be found here.
- Deploy to Staging by creating a Tag with
git tag staging-v1 && git push origin --tags
- Deploy to Production by creating a Tag with
git tag production-v1 && git push origin --tags
TL;DR: Create .github/workflows/deploy.yml
with the following content:
Let’s see what is happening in the workflow configuration file shown above:
on:
push:
tags:
- '**'
This part tells GitHub to trigger this pipeline when a tag is being pushed.
- name: Extract tag
run: echo "::set-env name=TAG::$(echo ${GITHUB_REF##*/})"
Here we set the tag as environment variable. ::set-env
is a way of sharing environment variables between steps. export TAG="test-tag"
will not work between steps.
- name: Invalid tag
if: (! contains(env.TAG, 'staging')) && (! ...
run: |
echo "Specify 'staging' or production in your tag."
exit 1
This step above tells the workflow to stop if the condition is met: tag does not contain ‘staging’ or ‘production’
- name: Set STAGING env
if: contains(env.TAG, 'staging')
run: |
echo "::set-env name=PROJECT_ID::google-staging-project"
echo "::set-env name=SECRET_KEY_NAME::GITHUB_STAGING_SECRET"
This step exports the staging environment variables if the tag contains ‘staging’. The same is being done for the Production step.
- uses: GoogleCloudPlatform/github-actions/setup-gcloud@master
with:
project_id: ${{ env.PROJECT_ID }}
service_account_key: ${{ secrets[env.SECRET_KEY_NAME] }}
export_default_credentials: true
This step uses the preset Action ‘setup-gcloud’ with the previously set environment variables. The {{$ secrets[env.SECRET_KEY_NAME] }}
syntax can be used to dynamically get a GitHub secret.
- name: Deploy to CloudRun
run: |-
gcloud run deploy "$SERVICE_NAME" \
--quiet \
--image "eu.gcr.io/my-project/$SERVICE_NAME:$GITHUB_SHA" \
--region "$RUN_REGION" \
--platform "managed" \
--allow-unauthenticated \
--memory=512Mi
This final step uses the installed gcloud
and previously set ENV to deploy the container to Google Cloud Run. See this blog on how to build a Docker image with GitHub Actions.
Good luck, and don’t forget to order your Tesla Model Y on MisterGreen.nl