2

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.

user2482703
  • 151
  • 2
  • 13

1 Answers1

4

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: 'your_service_account@project-id.iam.gserviceaccount.com',
        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: 'your_service_account@project-id.iam.gserviceaccount.com',
        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

Ricco D
  • 6,873
  • 1
  • 8
  • 18
  • I tried your suggestion but i got 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.' are you sure you dont have the GOOGLE_APPLICATION_CREDENTIALS variable exported? – user2482703 Nov 28 '21 at 09:41
  • 2
    i think i made it work by adding the projectId. Thanks! – user2482703 Nov 28 '21 at 10:00