MarkEdmondson1234 / googleCloudRunner

Easy R scripts on Google Cloud Platform via Cloud Run, Cloud Build and Cloud Scheduler
https://code.markedmondson.me/googleCloudRunner/
Other
81 stars 26 forks source link

Feature request: Allow project to be extracted from JSON if not set #117

Open muschellij2 opened 3 years ago

muschellij2 commented 3 years ago

If you have GCE_AUTH_FILE then it should be able to extract the project_id, which may be less prone to errors (e.g. difference between project_name and project_id) than forcing people to set the ID:

I'm suggesting editing: https://github.com/MarkEdmondson1234/googleCloudRunner/blob/b4a2b1f3062f7f57ca4b0205f58dfa0342b17212/R/init.R#L70

I think it could be something like this:

cr_project_get <- function(){

  if(!is.null(.cr_env$project)){
    return(.cr_env$project)
  }

  if(Sys.getenv("GCE_DEFAULT_PROJECT_ID") != ""){
    .cr_env$project <- Sys.getenv("GCE_DEFAULT_PROJECT_ID")
  }

  # check the auth file 
  if (!is.na(Sys.getenv("GCE_AUTH_FILE", unset = NA))) {
    if (assertthat::is.readable(Sys.getenv("GCE_AUTH_FILE"))) {
      out = try({
        jsonlite::read_json(json_file)
      }, silent = TRUE)
      if (!inherits(out, "tyr-error")) {
        .cr_env$project <- out$project_id
      }
    }
  }

  if(is.null(.cr_env$project)){
    stop("No projectId set - use cr_project_set() or env arg GCE_DEFAULT_PROJECT_ID",
         call. = FALSE)
  }
  .cr_env$project
}

This would swap out the ordering likely from https://github.com/MarkEdmondson1234/googleCloudRunner/blob/b4a2b1f3062f7f57ca4b0205f58dfa0342b17212/R/setup.R#L38

MarkEdmondson1234 commented 3 years ago

Not necessarily as I for instance have a service email that is added to several GCP projects. It could perhaps be a helpful default though as perhaps I'm using it in an edge case.

muschellij2 commented 3 years ago

It may be good to add GOOGLE_APPLICATION_CREDENTIALS as that's the recommended way to set up for gloud SDK according to: https://cloud.google.com/docs/authentication/getting-started#setting_the_environment_variable