rauthenticationgoogle-bigquerybigrquery

Authentication for Bigquery using bigrquery from an R Markdown document


I am having problems using bigrquery to connect to a GCP service account from within an R Markdown document that I knit. When I attempt from the console, authentication works fine. Both

library(bigrquery)
bq_auth()

and

library(bigrquery)
bq_auth(email="my-service-account-email@myproject.iam.gserviceaccount.com")

launch a browser with a dialog that lets me pick and authenticate using the specified account as expected. But in the R Markdown, any attempt like

options("httr_oob_default" = TRUE)
bq_auth(email="my-service-account-email@myproject.iam.gserviceaccount.com")

or even using the full list like this

bq_auth(
  email = "my-service-account-email@myproject.iam.gserviceaccount.com",
  path = NULL,
  scopes = c("https://www.googleapis.com/auth/bigquery"),
  cache = gargle::gargle_oauth_cache(),
  use_oob = gargle::gargle_oob_default(),
  token = NULL
)

leads to the error

Error: Can't get Google credentials.
Are you running bigrquery in a non-interactive session? Consider:
  * Call `bq_auth()` directly with all necessary specifics.

Can anyone see what I am missing? Thanks in advance.


Solution

  • You can download the JSON file of your Google Cloud service account, then use it as a path that the “bq_auth” function can recognize. Here's the steps:

    1. Google Cloud Console (console.cloud.google.com)
    2. Navigation Menu
    3. IAM & Admin Service
    4. Accounts
    5. Create Service Account (create one)
    6. Create Key, and save to "/path/to/jsonfilename.json"
    7. Authenticate in your R Markdown code: bigrquery::bq_auth(path = "/path/to/jsonfilename.json")

    Note: you'll need to make sure to set the service account to have access to BigQuery. I set mine to "BigQuery Admin" and it worked, but that might be too broad

    Borrowed this answer from Elaine See's post on medium: https://medium.com/@elaine.yl.see/easiest-way-to-use-bigquery-in-r-8af466cd55ca