I need to set an environment variable within my virtual machine on Google Compute Engine. The variable I need to set is called "GOOGLE_APPLICATION_CREDENTIALS"
and according to Google documentation I need to set its value to the path of a json file. I have two questions:
1: Can I set this variable within the Google Compute Engine interface on GCP?
2: Can I use System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Resources.googlecredentials.credentials);
? Whenever I try and set this variable on my local machine I use this technique, but I set the value to the path of the file (local directory). However, because I am now using a virtual machine, I was wondering, can I set the environment variable to the actual contents of a resource file? Advantageously, this allows me to embed the credentials into the actual app itself.
Cheers
Store your credentials in a file temporarily
$HOME/example/g-credentials.json
{
"foo": "bar"
}
Then upload it to your GCE projects metadata as a string
gcloud compute project-info add-metadata \
--metadata-from-file g-credentials=$HOME/example/g-credentials.json
You can view your GCE projects metadata on the cloud console by searching for metadata
or you can view it by using gcloud
gcloud compute project-info describe
Then set the env var/load the config in your VMs startup script
$HOME/example/startup.txt
#! /bin/bash
# gce project metadata key where the config json is stored as a string
meta_key=g-credentials
env_key=GOOGLE_APPLICATION_CREDENTIALS
config_file=/opt/g-credentials.json
env_file=/etc/profile
# command to set env variable
temp_cmd="export $env_key=$config_file"
# command to write $temp_cmd to file if $temp_cmd doesnt exist w/in it
perm_cmd="grep -q -F '$temp_cmd' $env_file || echo '$temp_cmd' >> $env_file"
# set the env var for only for the duration of this script.
# can delete this if you don't start processes at the end of
# this script that utilize the env var.
eval $temp_cmd
# set the env var permanently for any SUBSEQUENT shell logins
eval $perm_cmd
# load the config from the projects metadata
config=`curl -f http://metadata.google.internal/computeMetadata/v1/project/attributes/$meta_key -H "Metadata-Flavor: Google" 2>/dev/null`
# write it to file
echo $config > $config_file
# start other processes below ...
example instance
gcloud compute instances create vm-1 \
--metadata-from-file startup-script=$HOME/example/startup.txt \
--zone=us-west1-a
you could also edit the user's profile:
nano ~/.bashrc
or even system-wide with /etc/profile
, /etc/bash.bashrc
, or /etc/environment
and then add:
export GOOGLE_APPLICATION_CREDENTIALS=...
Custom Metadata can also be used, which is rather GCE
specific.