bigquery authenticating with service account from text\string and not file path

2.3k Views Asked by At

I am using this nodejs bigquery client

I have the service account json in string\text, I want to avoid to write it to temporary file due to security reasons.
Is there an option to do new BigQuery() and provide the service account as string and not as filepath?
Couldn't find this option anythere, in all the examples need to provide the filepath or export the GOOGLE_APPLICATION_CREDENTIALS variable.

Thanks.

1

There are 1 best solutions below

2
On BEST ANSWER

It is possible to use the values in your service account as string for authentication. You can use BigQueryOptions and pass a credentials object. Credentials object will need client_email and private_key which can be found in your service account json.

Using the sample code you linked in your question, BigQueryOptions can be implemented in this manner.

const creds = {
        client_email: '[email protected]',
        private_key: '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n'
};

const bigquery = new BigQuery(credentials=creds);

The whole code will be:

const {BigQuery} = require('@google-cloud/bigquery');

const creds = {
        client_email: '[email protected]',
        private_key: '-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n'
};

const bigquery = new BigQuery(credentials=creds);

async function query() {
  // Queries the U.S. given names dataset for the state of Texas.

  const query = `SELECT name
    FROM \`bigquery-public-data.usa_names.usa_1910_2013\`
    WHERE state = 'TX'
    LIMIT 100`;

  // For all options, see https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query
  const options = {
    query: query,
    // Location must match that of the dataset(s) referenced in the query.
    location: 'US',
  };

  // Run the query as a job
  const [job] = await bigquery.createQueryJob(options);
  console.log(`Job ${job.id} started.`);

  // Wait for the query to finish
  const [rows] = await job.getQueryResults();

  // Print the results
  console.log('Rows:');
  rows.forEach(row => console.log(row));
}
query()

Snippet of the output:

enter image description here