Skip to content

Instantly share code, notes, and snippets.

@twfahey1
Last active June 7, 2024 12:11
Show Gist options
  • Save twfahey1/7593185b4c8dd09287726ca4c6844920 to your computer and use it in GitHub Desktop.
Save twfahey1/7593185b4c8dd09287726ca4c6844920 to your computer and use it in GitHub Desktop.
Using Google API credentials.json file in Github Action or other scripts

The question: What is the best way we can use Google API via a service account in Github Actions? Answer: encrypt the credentials and decrypt during Action w/ a configured secret.

  • The credentials.json.gpg is originated from the credentials.json that can be downloaded from Cloud Console for the service account.
  • Encrypt it via: gpg --symmetric --cipher-algo AES256 credentials.json - Note the password used, as it will be added as a secret in this repo to be used for decoding the file and accessing Google APIs.
  • Update the credentials.json.gpg file in this repo using the contents of the newly created credentials.json.gpg, commit and push.
  • The password used should be added as a secret, e.g. the GOOGLE_API_PW secret in the github repo

Then, in the Github action or script, call gpg to decrypt and write the unencrypted file:

#!/bin/sh

# Decrypt the file
mkdir $HOME/secrets
# --batch to prevent interactive command
# --yes to assume "yes" for questions
gpg --quiet --batch --yes --decrypt --passphrase="$GOOGLE_API_PW" \
--output $HOME/secrets/credentials.json credentials.json.gpg

You can then use the credentials.json normally, for example in a PHP script for Sheets API:

<?php

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    // Checks for github actions env variable.
    $root_path = !empty(getenv('GITHUB_WORKFLOW')) ? getenv('HOME') : __DIR__;
    $apiOptions = [
      'application_name' => 'My App Name',
      'credential_path' => $root_path . '/secrets/credentials.json'
    ];

    $client = new Google_Client();
    $client->setApplicationName($apiOptions['application_name'], 'Google Sheets API PHP');
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
    $client->setAuthConfig($apiOptions['credential_path']);
    $client->setAccessType('offline');
    return $client;
}


- name: Decrypt Google credentials.json
env:
GOOGLE_API_PW: ${{ secrets.GOOGLE_API_PW }}
run: |
mkdir $GITHUB_WORKSPACE/secrets
# --batch to prevent interactive command
# --yes to assume "yes" for questions
gpg --quiet --batch --yes --decrypt --passphrase="$GOOGLE_API_PW" \
--output $GITHUB_WORKSPACE/secrets/credentials.json credentials.json.gpg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment