Google Cloud Platform: Logging in to GCP from commandline

Lior Ohana picture Lior Ohana · Nov 23, 2015 · Viewed 20.1k times · Source

I was sure it will be simple but couldn't find any documentation or resolution. I'm trying to write a script using gcloud to perform some operations in my GCP instances.

Is there anyway to login/authenticate using gcloud via command line only?

Thanks

Answer

Zachary Newman picture Zachary Newman · Nov 23, 2015

You have a couple of options here (depending on what exactly you're trying to do).

The first option is to log in using the --no-launch-browser option. This still requires interaction from a human user, but doesn't require a browser on the machine you're using:

> gcloud auth login --no-launch-browser
Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&prompt=select_account&response_type=code&client_id=32555940559.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fappengine.admin+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcompute&access_type=offline


Enter verification code: *********************************************
Saved Application Default Credentials.

You are now logged in as [[email protected]].
Your current project is [None].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID

The non-interactive option involves service accounts. The linked documentation explains them better than I can, but the short version of what you need to do is as follows:

  1. Create a service account in the Google Developers Console. Make sure it has the appropriate "scopes" (these are permissions that determine what this service account can do. Download the corresponding JSON key file.

  2. Run gcloud auth activate-service-account --key-file <path to key file>.

Note that Google Compute Engine VMs come with a slightly-different service account; the difference is described here.