gcloud: is it possible to change the default project based on the current folder?

616 Views Asked by At

I'm working on several gcloud projects and I'm tired of having to type out --project XYZ every time I need to call a command, or worse having the command execute on the wrong project if I forget to add that in.

1

There are 1 best solutions below

0
On BEST ANSWER

Yes, by using gcloud configurations together with direnv.

Create a configuration (this will also activate it):

  • gcloud config configurations create <cool_new_config>
  • gcloud config set project <project>

Install direnv. Hook it into your shell. With bash I used ~/.bash_profile instead of directed ~/.bashrc.

Navigate to the project folder where you want the switch to occur.

  • create a file named .envrc
  • add line export CLOUDSDK_ACTIVE_CONFIG_NAME=<cool_new_config>
  • whitelist file with direnv allow

Verify functionality:

  • open a new terminal window
  • active the default/prior configuration
  • navigate to folder
  • confirm with gcloud config configurations list

Optional: rebuild the rest of the configuration

  • view all configurations: gcloud config configurations list
  • describe old configuration gcloud config configurations describe <default>
  • login: gcloud auth login
  • set region: gcloud config set compute/region <us-central1>
  • set zone: gcloud config set compute/zone <us-central1-a>
  • etc.