For developing locally, most google cloud client libraries are configured to use the GOOGLE_APPLICATION_CREDENTIALS
environment variable to locate the credentials for the service account in use, and then authenticate that library. When deployed to GCP, they similarly don't require any manual authentication in the code, and instead use they environment to authenticate behind the scenes. This means that most client libraries, for example BigQuery, Cloud Storage, etc, just work in Cloud Functions, without needing any code for authentication. However, the googleapis Nodejs client library doesn't use GOOGLE_APPLICATION_CREDENTIALS
and seems to require manual authentication in the code. Below is a minimal example of how I am doing this locally. How could I run this code in a Google Cloud Function without needing to upload the service account credentials to the cloud function?
const { google } = require("googleapis");
const key = require("service_account_credentials.json");
const client = new google.auth.JWT(key.client_email, null, key.private_key, [
"https://www.googleapis.com/auth/spreadsheets",
]);
client.authorize(function (err, tokens) {
const gsapi = google.sheets({ version: "v4", auth: client });
const opt = {
spreadsheetId: "spreadsheetId",
range: "Sheet1!A:T",
};
gsapi.spreadsheets.values.get(opt).then(res => console.log(res));
});