Reputation: 1046
I am trying to get this sample working without success
I installed and initialized the client:
export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"
echo "deb https://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt-get update \
&& sudo apt-get -y install google-cloud-sdk \
&& sudo apt-get -y install google-cloud-sdk-app-engine-java \
&& sudo apt-get -y install google-cloud-sdk-app-engine-python \
gcloud init
Then I authenticated successfully:
gcloud auth activate-service-account [email protected] --key-file=DockerStorage-e7def0adcafb.json
Then I tried the quick start sample:
Storage storage = StorageOptions.getDefaultInstance().getService();
String bucketName = "my-first-bucket"; // "my-new-bucket";
Bucket bucket = storage.create(BucketInfo.of(bucketName));
System.out.printf("Bucket %s created.%n", bucket.getName());
BOOM unauthorized
Exception in thread "main" com.google.cloud.storage.StorageException: 401 Unauthorized
What did I miss?
Upvotes: 3
Views: 12563
Reputation: 546
At first, You have to a generate a Service account credential.
Generating a service account credential To generate a private key in JSON or PKCS12 format:
Then simply use the credential json file in you code.
StorageOptions storageOptions = StorageOptions.newBuilder()
.setProjectId("YOUR_PROJECT_ID")
.setCredentials(GoogleCredentials.fromStream(new
FileInputStream("path/YOUR_SERVICE_ACCOUNT_CRENDENTIAL.json"))).build();
Storage storage = storageOptions.getService();
Upvotes: 4
Reputation: 38409
Hrm...good question. Theoretically this should work If you don't otherwise specify auth, that library will first attempt to use the credentials file specified by the GOOGLE_APPLICATION_CREDENTIALS
environment variable, and if that's not set, it should go looking for your gcloud credentials.
I'm guessing that it can't find your gcloud credentials for some reason. By default, they'll be in the ".config/gcloud" directory under your home directory, but that can be overridden. Maybe check to see if there're some files there?
One thing worth trying is simply copying a service account's JSON file to that machine and specifying the path to it with the GOOGLE_APPLICATION_CREDENTIALS
environment variable. That shouldn't be necessary, but if that fails as well, something more interesting is going on.
Upvotes: 2