Using Service Accounts#

In this lab you’ll create a service account, assign a role to it and associate the account with a VM. This process is how VMs become authorized to perform actions on the Google Cloud control plane, such as retrieving data from a private storage bucket or creating new VMs. In the lecture you saw a demonstration of adding a service account using the GUI.

Project Tip

The code you create in this lab can be reused to create a service account for Project 2

Make a lab08 Directory#

In your git repository, create copy the base directory to create a new directory for this lab.

$ cp -R base lab08
$ cd lab08

Apply the Terraform Configuration and SSH#

Without making changes apply the Terraform configuration and SSH into the new machine:

$ terraform apply 
$ gcloud compute config-ssh

The gcloud compute config-ssh command will show you how to use ssh to connect to your VM. Enter that command to get a shell. Once at the shell try this:

you@cis-91$ gcloud compute instances list 

The command should fail! You don’t have access.

Update The Configuration#

This section contains resources to add you your file.

Service Account Resource#

Start by reading about the google_service_account resource. Then create a service account for the VM to use:

resource "google_service_account" "lab08-service-account" {
  account_id   = "lab08-service-account"
  display_name = "lab08-service-account"
  description = "Service account for lab 08"

Make the Service Account a Member#

When you create a service account from the GUI this is done automatically. At the API level you have to do this manually. Read about the google_project_iam group of resources. Now make the service account a member of the project:

resource "google_project_iam_member" "project_member" {
  role = "roles/compute.viewer"
  member = "serviceAccount:${}"

Add the Service Account to the VM#

The last step is to associate the account with your VM. This stanza has to be added to the google_compute_instance resource. Read more about the resource before you add this stanza.

  service_account {
    email  =
    scopes = ["cloud-platform"]

About scopes

The scopes definition in the service_account stanza can further limit the service account to certain actions. These limits are in addition to the roles granted to the service account. The cloud-platform scope allows all actions and means the service account is limited only by its roles.

Apply Changes#

After you make changes they need to be applied.

$ terraform apply 

Check Access#

Repeat the steps to SSH in to your VM and confirm the following command works:

you@cis-91$ gcloud compute instances list 

Commit and Push Your Changes#

Commit the changes to lab08 to your GitHub repository.

Turn In#

Turn in your file.


Don’t forget to terraform destroy your resources so you don’t get charged!