Telling Google Cloud CLI which browser profile to launch

This is such a niche topic but it's been bugging me for a year and a half at work and I finally figured out how to solve it, so I thought I'd make a post.

Suppose you are logged into two Chrome profiles, and you happen to use Google Cloud with both. When you run

gcloud auth login

in your terminal, Google Cloud will auto-launch your browser, using whatever profile was last active. This can be frustrating if you meant to log in with a specific profile but had the login screen open in another profile.

To launch your browser, Google Cloud's SDK uses the webbrowser Python library, which mentions the following in its documentation:

If the environment variable BROWSER exists, it is interpreted as the os.pathsep-separated list of browsers to try ahead of the platform defaults. When the value of a list part contains the string %s, then it is interpreted as a literal browser command line to be used with the argument URL substituted for %s; if the value is a single word that refers to one of the already registered browsers this browser is added to the front of the search list; if the part does not contain %s, it is simply interpreted as the name of the browser to launch.

I don't know why I never noticed the part in bold before. But since Google Chrome allows you to open a URL in a specified profile from the command line, this means we can do:

BROWSER='/Applications/Google Chrome.app/Contents/MacOS/Google\ Chrome --profile-directory="<PROFILE>" %s' \
  gcloud auth login

to open the Google login screen in profile <PROFILE>. Replace this with the appropriate profile directory name, which you can see by opening chrome://version/.