Use Github Actions to set up an automated backup of Google Apps Scripts to Github.

Backup Google Apps Script using Github Actions

Ravgeet Dhillon

Ravgeet Dhillon

Updated on Nov 05, 2021 in Automation

⏱ 7 min read

Blog banner for Backup Google Apps Script using Github Actions

Google Apps Scripts are amazing. Without setting any servers, you can do a lot of things like collecting form responses, email marketing campaigns, etc. But as a developer, you like your code to be on Version Control System like Github. In this blog, you will learn to set up Github Actions to automatically backup your Google Apps Scripts to Github.

Contents

Prerequisites

Before getting started, make sure that you have set up the following:

  • A Google Apps Script Project
  • A Github Account

Installing Clasp

Clasp is a Google tool to develop Apps Script projects locally. It is short for Command-Line Apps Script Projects. You can follow this amazing guide by Google to get your login credentials, which you will be using later while setting up Github Actions.

Once you have successfully logged in, use the following command to get the content of the credentials file.

cat ~/.clasprc.json

Creating a New Repository

Depending upon your requirement, create a new public/private repository in Github. Once you have created a new repository, add a .gitignore file with the following content:

.*.json

This prevents your credential file to be committed to the repository.

Adding Important Files

Now it’s time to add some new files to the repository.

a.) setup.sh

This script will prevent you from logging in again by using your already logged in credentials from Github Actions secrets, which you will be setting up later. Add the following bash code to the file:

#!/bin/sh

LOGIN=$(cat <<-END
    {
        "token": {
            "access_token": "$ACCESS_TOKEN",
            "refresh_token": "$REFRESH_TOKEN",
            "scope": "https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/service.management https://www.googleapis.com/auth/script.deployments https://www.googleapis.com/auth/logging.read https://www.googleapis.com/auth/script.webapp.deploy https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/script.projects https://www.googleapis.com/auth/drive.metadata.readonly",
            "token_type": "Bearer",
            "id_token": "$ID_TOKEN",
            "expiry_date": 1595752666211
        },
        "oauth2ClientSettings": {
            "clientId": "$CLIENT_ID",
            "clientSecret": "$CLIENT_SECRET",
            "redirectUri": "http://localhost"
        },
        "isLocalCreds": false
    }
END
)

echo $LOGIN > ~/.clasprc.json

Replace the value of scope key with value in your ~/.clasprc.json.

b.) scripts.json

This script will contain the id and name of the Google Apps Script projects. You can add single or multiple projects here depending upon your backup strategy. Add the following JSON object to the file:

[
    {
        "id": "google-apps-script-project-id",
        "name": "google-apps-script-project-name"
    },
    {
        "id": "google-apps-script-project-id",
        "name": "google-apps-script-project-name"
    }
]

c.) clone.sh

This script will use Clasp’s clone command to download all the scripts that you provided in the scripts.json file. This script will delete all the previous projects committed to the repository. This is an important step to reflect the deleted files in Github. Add the following bash code to this file:

#!/bin/sh

# remove all the pre-existing projects
rm -r -f */

content=$(cat scripts.json)
for row in $(echo "${content}" | jq -r '.[] | @base64'); do
    _jq() {
      echo ${row} | base64 --decode | jq -r ${1}
    }

    # get name and id for project
    name=$(_jq '.name')
    id=$(_jq '.id')

    # create a project directory
    mkdir $name
    cd $name

    # clone the project using the clasp
    clasp clone $id

    # come out of the directory
    cd ..
done

Setting up Github Actions

Now comes the best part of the project. You can automate the whole backup process using Github Actions. You can schedule the script to run every midnight using Cron job syntax.

Create a directory path at .github/workflows. In this path, create a backup.yml file and add the following code to it:

name: Backup

on:
  schedule:
    - cron: '0 0 * * *'

jobs:
  backup:
    runs-on: ubuntu-latest

    env:
      ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
      REFRESH_TOKEN: ${{ secrets.REFRESH_TOKEN }}
      CLIENT_ID: ${{ secrets.CLIENT_ID }}
      CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }}
      ID_TOKEN: ${{ secrets.ID_TOKEN }}
      REMOTE_BRANCH: master

    steps:
      - name: Setup repository
        uses: actions/checkout@v2

      - name: Setup Node
        uses: actions/setup-node@v1
        with:
          node-version: '12'

      - name: Install Clasp
        run: npm install -g @google/clasp

      - name: Install jq
        run: |-
          sudo apt update -y
          sudo apt install jq -y

      - name: Setup Logins
        run: bash setup.sh

      - name: Clone Scripts
        run: bash clone.sh

      - name: Update Progress
        run: |
          if [ $(git status --porcelain=v1 2>/dev/null | wc -l) != "0" ] ; then
            git config user.name "GitHub Actions"
            git config user.email noreply@github.com
            git add .
            git commit -m "github-actions: took backup"
            git push origin master --force
          fi

The workflow setups the repository, installs Node, installs Clasp, runs Clasp Setup, clones the Google Apps Scripts, checks whether there are any new changes, and if so commits them back to the repository as with a pre-defined commit message.

Adding Github Actions Secrets

You can get your Action Secrets values from the ~/.clasprc.json and add them accordingly.

Setting up Github Actions Secrets
Setting up Github Actions Secrets

Results

Hurray! You can see that the Github Action workflow completed with success at 00:00 UTC.

Scheduled Actions workflow completed successfully
Scheduled Actions workflow completed successfully

Let us check the repository to confirm that the backup was taken successfully.

Backup taken successfully to Google Apps Script
Backup taken successfully to Google Apps Script

You can see that the Google Apps Scripts projects were committed back to the repository with a commit message github-action: took backup.

Using this workflow, you can stay connected with both Google Apps Script and Github.

📫

Loved this post? Join our Newsletter.

We write about React, Vue, Flutter, Strapi, Python and Automation. We don't spam.

Please add a valid email.
By clicking submit button, you agree to our privacy policy.
Thanks for subscribing to our newsletter.
There was some problem while registering your newsletter subscription. Please try again after some time or notify the owners at info@ravsam.in

ABOUT AUTHOR

Ravgeet Dhillon

Ravgeet is a Co-Founder and Developer at RavSam. He helps startups, businesses, open-source organizations with Digital Product Development and Technical Content Writing. He is a fan of Jamstack and likes to work with React, Vue, Flutter, Strapi, Node, Laravel and Python. He loves to play outdoor sports and cycles every day.

Got a project or partnership in mind?

Let's Talk

Contact Us ->