How to run gcloud command line using a service account

Nataraj
2 min readJul 30, 2018

--

Step-by-step

1) Create a Service Account

gcloud iam service-accounts create gcpcmdlineuser --display-name "GCP Service Account"

gcloud iam service-accounts create gcpcmdlineuser

2) List the users

gcloud iam service-accounts list --filter gcpcmdlineuser@someproject.gserviceaccount.com

3) Download the service account key

gcloud iam service-accounts keys create ./somekey.json --iam-account <EMAIL ADDRESS>

gcloud iam service-accounts keys create gcpcmdlineuser.json --iam-account gcpcmdlineuser@someproject.iam.gserviceaccount.com

4) Associate a ROLE

gcloud iam roles create <ROLE NAME> --project <YOUR PROJECT ID> --file ./rolename.yaml

gcloud projects add-iam-policy-binding someprojecthere --member "serviceAccount:gcpcmdlineuser@someproject.iam.gserviceaccount.com" --role "roles/owner"

gcloud projects add-iam-policy-binding <PROJECT ID> --role <ROLE NAME> --member serviceAccount:<EMAIL ADDRESS>

5) Activate the service account

gcloud auth activate-service-account --project=someproject --key-file=gcpcmdlineuser.json

gcloud auth activate-service-account --key-file=gcpcmdlineuser.json

GCP CLI’s which might help

gcloud init --console-only

gcloud config set account gcpcmdline@someproject.iam.gserviceaccount.com

gcloud auth application-default login --no-launch-browser

gcloud compute instances list

gcloud auth list

gcloud auth revoke

gcloud info

From GCP Console

  1. Create a service account with GCP console
  2. Download the json key file
  3. Create a role and assign proper required permissions to the role.
  4. gcloud config set account gcli@someproject.iam.gserviceaccount.com
  5. gcloud auth activate-service-account — key-file=gcli.json — project=someprojectname

Role template could be as below

title: CLI Service Role
description: “CLI Service Role.”
stage: “ROLE”
includedPermissions:
— compute.autoscalers.get
— compute.autoscalers.list
— compute.autoscalers.update
— compute.instances.start
— compute.instances.startWithEncryptionKey
— compute.instances.stop
— compute.instances.get
— compute.instances.list
— compute.instanceGroupManagers.get
— compute.instanceGroupManagers.list
— compute.instanceGroupManagers.update
— compute.instanceGroupManagers.use
— compute.zones.get
— compute.zones.list
— monitoring.groups.get
— monitoring.groups.list
— monitoring.metricDescriptors.get
— monitoring.metricDescriptors.list
— monitoring.monitoredResourceDescriptors.get
— monitoring.monitoredResourceDescriptors.list
— monitoring.timeSeries.list
— resourcemanager.projects.get

--

--

Nataraj
Nataraj

Responses (6)