Sometimes you’ll need to translate Google credential JSON files into environment variables. This can be a bit of a problem because there’s multiple values to escape but there’s a few ways to get it done. I’ve got a few here I’ve used that can be taken on their own or combined in several circumstances.


The simplest of course is base64 encoding. On Linux and MacOS it’s done like this:

$ base64 ~/.gcloud/user@google-project.json

Problem is that’ll give you carraige returns. What you REALLY want is to disable wrapping:

$ base64 -w 0 ~/.gcloud/user@google-project.json

Much better.

Carriage Returns

Suppose you’ve got your file:

$ cat ~/.gcloud/user@google-project.json
  "type": "service_account",
  "project_id": "google-project",
  "private_key_id": "AAAAAAAAAAAAAAAAAAAAAAA",
  "client_email": "",
  "client_id": "CCCCCCCCCCCCCC",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""

Great, but small problem. It’s got a whole lot of carriage returns. How can you get rid of them quickly and effectively?

$ cat ~/.gcloud/user@google-project.json | tr -d '\r\n'
{  "type": "service_account",  "project_id": "google-project",  "private_key_id": "AAAAAAAAAAAAAAAAAAAAAAA",  "private_key": "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",  "client_email": "",  "client_id": "CCCCCCCCCCCCCC",  "auth_uri": "",  "token_uri": "",  "auth_provider_x509_cert_url": "",  "client_x509_cert_url": ""}

Double Quotes

Better, but some shells will choke on the double quotes. So we can go one step further.

$ cat ~/.gcloud/user@google-project.json | tr -d '\r\n' | sed 's/\"/\\"/g'
{  \"type\": \"service_account\",  \"project_id\": \"google-project\",  \"private_key_id\": \"AAAAAAAAAAAAAAAAAAAAAAA\",  \"private_key\": \"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\",  \"client_email\": \"\",  \"client_id\": \"CCCCCCCCCCCCCC\",  \"auth_uri\": \"\",  \"token_uri\": \"\",  \"auth_provider_x509_cert_url\": \"\",  \"client_x509_cert_url\": \"\"}