Search code examples
windows-subsystem-for-linuxgcloudgcloud-cli

How can I get gcloud auth to open the windows browser via WSL?


When trying to authenticate with google cloud CLI, you are prompted to the OAuth2 flow that asks you to login with your google account and approve.

gcloud auth application-default login

However, this does not work via WSL on windows. It seems that the google CLI tool can't identify the browser that is configured to run on the host.

The flow itself can still work, as the CLI prints a URL that can be copied to the browser, but as a developer, I always prefer being lazy and save a bit more time whenever possible :)


Solution

  • TL;DR

    Install wslu and run the command with DISPLAY='ANYTHING'

    DISPLAY='X' gcloud auth application-default login
    

    Why does this work?

    There are two steps to solving this problem:

    1. We want to set a default browser to the linux distribution. This is one approach - https://superuser.com/a/1368878
    2. We want to get gcloud to work with our setting

    After digging around the python CLI implementation, I found this piece of code inside check_browser.py

    # These are environment variables that can indicate a running compositor on
    # Linux.
    _DISPLAY_VARIABLES = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET']
    
    ....
    
    current_os = platforms.OperatingSystem.Current()
    if (current_os is platforms.OperatingSystem.LINUX and
        not any(encoding.GetEncodedValue(os.environ, var) for var
                in _DISPLAY_VARIABLES)):
      launch_browser = False
    

    An easy solution that works for me is running the gcloud CLI with the environment variable DISPLAY='X':

    DISPLAY='X' gcloud auth application-default login
    

    You can also set an alias:

    alias gauth='DISPLAY="X" gcloud auth application-default login'
    

    Troubleshooting

    However, this might now work on all systems. Also the code might change in the future. If Anyone else is interested in tweaking with it in a different manner, I located the relevant file under:

    /usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/util/check_browser.py
    

    And you can playaround with it in python

    In [21]: from googlecloudsdk.command_lib.util.check_browser import *
    
    In [22]: ShouldLaunchBrowser(True)
    Out[22]: False