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 createdcredentials.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;
}
Don't forget to encrypt
token.json
as well, as it is the actual file to allow automation. Thecredentials.json
only bring you to the consent screen. For automation it will mean you are stuck there forever