0
votes

I am using Google Java SDK to access Google Cloud Storage. I have created a service account for one of my projects and downloaded the JSON key file. I have decided to manually load up the JSON key as illustrated here instead or relying on environment variables:

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
        .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

In addition, I have multiple users and multiple projects per user:

          User1           |           User2
-----------------------------------------------------
        Project A         |         Project X
        Project B         |         Project Y
        Project C         |

When I create run my code it tries with a service account key for Project A, it attempts to access Project X. In the gcloud util, Project X was my active project gcloud config list. I couldn't see anywhere in my environment variables where I had set the active project. The only way I could get this to work was to switch my active project in gcloud gcloud config configurations activate [Project A Name]

1) Is there a way in the Java SDK to programmatically override the current project that is magically set somewhere by the gcloud util?

2) Where is the code pulling the current project from if not from what is listed in the JSON key file? What is the order of preference that the SDK uses to figure out the project to use?

2

2 Answers

0
votes

The answer to question 1 can be seen in this answer: https://stackoverflow.com/a/44122119/311525

The project can be overridden by using setProjectId(PROJECT_ID)

Storage storage = StorageOptions.newBuilder().setProjectId("your-project-id").setCredentials(credentials).build().getService();
0
votes

In order to have both the answers in one I'm referring to Scott's answer here:

The answer to question 1 can be seen in this answer: https://stackoverflow.com/a/44122119/311525

The project can be overridden by using setProjectId(PROJECT_ID)

Storage storage = StorageOptions.newBuilder().setProjectId("your-project-id").setCredentials(credentials).build().getService();

And the answer to the question 2 is that the code will pull the project from the JSON file but you have to set the project in gcloud to the one the service account has been generated from. In this example if you want to access Project A you need to set gcloud to project A.