arrow_back

Configuring IAM Permissions with gcloud

Join Sign in

Configuring IAM Permissions with gcloud

1 hour 30 minutes 1 Credit

GSP647

Google Cloud self-paced labs logo

Overview

People new to Google Cloud need to understand IAM to fully understand how to configure the necessary permissions for their workloads. This lab looks at three common areas learners should understand with regards to IAM and gcloud: the installation and configuration of the gcloud environment, the use of multiple gloud configurations, and the use of services accounts.

In this lab you will use the gcloud CLI tool to set up and configure command features of Cloud Identity and Access Management (IAM).

What you'll learn

  • Install and configure the gcloud client

  • Create and switch between multiple IAM configurations

  • Identify and assign correct IAM permissions

  • Create and use a service account

Starting environment

You start with two user accounts and two projects; user1 is the "owner" of both projects and user2 is the "viewer" of only the first project. There is a Linux virtual machine (vm) running in the first project.

Starting environment illustration

What is IAM?

Google Cloud offers Cloud Identity and Access Management (IAM), which lets you manage access control by defining who (identity) has what access (role) for which resource.

With Cloud IAM you can grant granular access to specific Google Cloud resources and prevent unwanted access to other resources. Cloud IAM lets you adopt the security principle of least privilege, so you grant only the necessary access to your resources.

IAM Overview

Identities

In Cloud IAM, you grant access to members. Members can be of the following types:

  • Google account
  • Service account
  • Google group
  • G Suite domain
  • Cloud Identity domain

Learn more about these identity types from the Concepts related to identity Guide.

In this lab you will use Google accounts, service accounts, and Cloud Identity domain groups.

Roles

A role is a collection of permissions. You cannot assign a permission to the user directly; instead you grant them a role. When you grant a role to a user, you grant them all the permissions that the role contains.

There are three kinds of roles in Cloud IAM:

  • Primitive roles: The roles historically available in the Cloud Console will continue to work. These are the Owner, Editor, and Viewer roles.

  • Predefined roles: Predefined roles are the Cloud IAM roles that give finer-grained access control than the primitive roles. For example, the predefined role Pub/Sub Publisher (roles/pubsub.publisher) provides access to only publish messages to a Cloud Pub/Sub topic.

  • Custom roles: Roles that you create to tailor permissions to the needs of your organization when predefined roles don't meet your needs.

Learn more about roles from the Roles Guide.

What is gcloud?

The gcloud CLI is a part of the Cloud SDK. You must download and install the SDK on your system and initialize it before you can use the gcloud command-line tool. You can use this tool to perform many common platform tasks either from the command-line or in scripts and other automations.

By default, the SDK installs those gcloud CLI commands that are at the General Availability and Preview levels only. Additional functionality is available in SDK components named alpha and beta. These components allow you to use the gcloud CLI to work with Cloud Bigtable, Google Cloud Dataflow and other parts of the Cloud Platform at earlier release levels than General Availability.

Learn more about gcloud from the gcloud CLI overview Guide.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account. Note: For this lab, log in using Username 1.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

Task 1. Install and configure gcloud

Your first step is to connect to an existing Google Cloud compute instance then download, install, and configure the gcloud SDK.

The gcloud SDK has a number of utilities that enable administration of the environment. First you will configure authentication to provide the utility permission to perform actions. The authentication process differs based on the identity you use. In this example you will use your lab-provided identity (which is a user account). Once you are authenticated, you also need to configure the environment to define the project you will act upon.

Learn more about authorizing Cloud SDK tools from the Authorize the gcloud CLI Guide.

Connect to centos-clean

This lab already has a Compute Engine instance called centos-clean that simulates an environment that doesn't have gcloud installed. You will connect to this instance using the Cloud Console.

  1. Open the list of compute instances by going to Navigation Menu > Compute Engine > VM instances.

  2. On the line with the compute instance named centos-clean, click SSH.

Note: About Compute Engine instances: There are Windows and Linux types of instances. In this lab you will use the Linux instance type. You can easily connect to Linux instances using the Secure Shell (SSH) client via the web browser.

You are automatically connected to the instance. Google Cloud manages the authentication keys for you, keeping them safe and available for only those you allow access.

Task 2. Download and install the Cloud SDK

There are two basic ways to install the Cloud SDK on Linux, and both need Python 2.7 to be installed.

The easiest way to install the Cloud SDK is to install into a directory under your own logged in user. This allows you to install the latest version without the need to be an admin of the system. The disadvantage is that only your account is set up to use the installed SDK.

If you want all users of the system to have access to the installed Cloud SDK, you need admin rights to install into the shared software packages for the system.

In this lab you will install using the simpler and easier method. You can learn more about how to install packages on your system from the Install the gcloud CLI Guide.

  1. First test, if you don't have gcloud already installed. Inside the SSH session run:

gcloud

You will get an error message that the command was not found. Now you know gcloud is not installed or configured, you can go ahead and install it.

  1. Download and run the installer script inside the SSH session:

curl https://sdk.cloud.google.com | bash
  1. You will be prompted for changes to the defaults> you can safely press ENTER each time you get a prompt.
Note: This command downloads the latest installer script for Cloud SDK then executes the script (by passing it to a bash shell).
  1. Once you return to the command prompt, reload the shell by running:

exec -l $SHELL

This command will restart your Cloud Shell session and you will be able to use the newly installed gcloud command-line tool immediately.

Download and install Cloud SDK
  1. Start configuring your gcloud environment. Inside the SSH session run:

gcloud auth login --no-launch-browser

You will be presented with a number of prompts.

  1. For You must log in to continue. and Do you want to continue (Y/n)?, press ENTER.

  2. Click on the link under the prompt Go to the following link in your browser:.

Use the credentials for this lab to authenticate the gcloud environment. Because you are using a Compute Engine instance you would normally use a service account. Ignore the suggestion and continue because you are simulating your own workstation environment. You will look at using a service account later in this lab.

  1. The link will open a Sign in with Google web page. Click on the account provided for this lab (if you are unsure, please look to the top left on this page).

  2. Click Allow.

You are accepting that the Cloud SDK will have the same access as your Google account.

  1. When you see the prompt Please copy this code, switch to your application and paste it there:, click on the copy button, go back to the SSH session, and paste the code into the prompt Enter verification code:.

  2. If asked, Pick cloud project to use:. locate your current project (on your web console at the top you will see the Project ID) in the list, then type the number for your project to select it from the list of options.

The initialization will complete and you will see the zone and region are set for you. You will change both in the next task.

Initialize Cloud SDK

Manage Cloud SDK components

Not all components are installed when you install the Cloud SDK. You can use the gcloud components to list and install additional components as needed.

  1. Examine the currently installed components. Inside the SSH session run:

gcloud components list

You can see that there are many components not installed.

  1. Install the beta component. Inside the SSH session run:

gcloud components install beta
  1. Press ENTER when you see the prompt Do you want to continue (Y/n)?.

You will install the component that allows you to access beta commands. The process of installing additional components is very easy and simple.

Check that the beta component is installed.

Install Cloud SDK beta component

Configure the gcloud environment

Once you have the gcloud command-line tool installed and basically configured, make some changes by creating a compute instance.

  1. Inside the SSH session run:

gcloud compute instances create lab-1
  1. You can press ENTER to accept the default zone for this VM. If you have correctly set everything up, the command will create an instance.

But what size? And where? What image will be used?

There are a number of defaults the service uses. Some can be controlled in the gcloud configuration. For example, the location of the instance is controlled by the zone setting.

Create an instance with name as lab-1 in Project 1
  1. Check your current gcloud configuration. Inside the SSH session run:

gcloud config list

You will see a compute section, a core section, and an active configuration. You can change each of these, but for this lab you'll only change the zone. Look at the zone your VM was created in.

  1. Now list all the zones available to use by running the following inside the SSH session run:

gcloud compute zones list
  1. Select one of the other zones in the same region as you. For example, if your zone is us-west2-a, you could select us-west2-b.

  2. Change your current zone for another zone in the same region. Inside the SSH session run the following, replacing ZONE with the zone you selected:

gcloud config set compute/zone ZONE
  1. Verify the zone change was made. Inside the SSH session run:

gcloud config list

You see the stated zone reflects the change you made.

You can change other settings using the gcloud config set command. Those changes are permanent; they are written to your home directory.

The default configuration is stored in ~/.config/gcloud/configurations/config_default.

If you want to use a zone other than the default zone when creating an instance, you can use --zone switch. For example, gcloud compute instances create lab-1 --zone us-central1-f

Update the default zone
  1. Verify the zone was written to the configuration file. Inside the SSH session run:

cat ~/.config/gcloud/configurations/config_default

You can see the configuration is just stored as text and can be backed up or copied.

You have now successfully installed and configured gcloud and installed the beta component.

Task 3. Create and switch between multiple IAM configurations

You have now set up one account. In situations when you need to work on different teams or access different accounts, you can also manage that with gcloud config.

In your next task you learn how to create a second configuration and switch between both of them.

Create a new IAM configuration

In this lab you have a second Google account you can log on with. This account has read-only (viewer) access to the first project. You will create a new configuration for that user.

  1. Start a new gcloud configuration for the second user account. Inside the SSH session run:

gcloud init --no-launch-browser
  1. Select option 2, Create a new configuration.

  2. configuration name: Type user2.

  3. Log in with a new account: select option 2 - you're logging in with the other provided user name.

  4. Press ENTER when you see the prompt Do you want to continue (Y/n)?

  5. Click on the link displayed.

  6. Click Use another account

  7. Copy the second user account from this page (left side), and paste into the email or phone prompt.

  8. Copy the same password that you started the lab with, and paste into the enter your password prompt.

  9. Click Accept.

  10. Click Allow.

You are accepting that the Cloud SDK will have the same access as your Google account.

  1. When you see the prompt Please copy this code, switch to your application and paste it there:, click on the copy button then go back to the SSH session and paste the code into the prompt Enter verification code:.

  2. On Pick cloud project to use: locate your current project (on your web console at the top you will see the project ID) and then type in the number that corresponds to the project.

The initialization will complete and you will see the zone and region are set for you.

Check gcloud user2 configuration was created

Test the new account

This new account has viewer only access to the project, so you can test that you are indeed using this account by trying to view and then create some resources.

  1. Check that you can view details in the first project. Inside the SSH session run:

gcloud compute instances list

The second user account has viewer access so you will see centos-clean and lab-1 instances listed.

  1. Check that you cannot create an instance in the first project, as your assigned role is primitive viewer. Inside the SSH session run:

gcloud compute instances create lab-2

Because the second user account has only viewer access, they are not allowed to create an instance, so this command will fail. It will take a little time to fail.

  1. Change back to your first user's configuration (default). Inside the SSH session run:

gcloud config configurations activate default

You are now back to using your original user account credentials. Later you will need to switch between these two accounts as you learn about roles and permissions.

Task 4. Identify and assign correct IAM permissions

You have been provided two user accounts for this project. The first user has complete control of both projects and can be thought of as the admin account. The second user has viewer only access to the two projects. Call the second user a devops user and that user identity represents a typical devops level user.

Next you will use gcloud to configure access to one project for the devops user by creating a custom role for the project that permits creation of buckets and instances.

Examine roles and permissions

  1. To view all the roles, run the following inside the SSH session run:

gcloud iam roles list | grep "name:"

The list of roles is returned. The addition of grep "name:" to the command reduces the amount of data returned to just the names of the roles.

Inspect one of these roles to see the permissions assigned to the role. To view the permissions use gcloud iam roles describe. Try looking at the simple role roles/compute.instanceAdmin.

  1. Examine the compute.instanceAdmin predefined role. Inside the SSH session run:

gcloud iam roles describe roles/compute.instanceAdmin

You can see roles/compute.instanceAdmin has many permissions, but these are the minimum needed for later:

  • compute.instances.create
  • compute.instances.delete
  • compute.instances.start
  • compute.instances.stop
  • compute.instances.update
  • compute.disks.create
  • compute.subnetworks.use
  • compute.subnetworks.useExternalIp
  • compute.instances.setMetadata
  • compute.instances.setServiceAccount

To review the full list of roles and the permissions assigned, refer to the IAM permissions reference Guide.

Assign the viewer role to the second user, in the second project

Now that you know that roles contain permissions, how do you assign a role (and therefore all the associated permissions), to a user account?

There are two ways to attach a role:

  • To the user and an organization
  • To a user and a project

Next you will attach the primitive role of "viewer" to the second user onto the second project.

Test that the second user doesn't have access to the second project.

  1. Switch gcloud configuration back to the second user (user2). Inside the SSH session run:

gcloud config configurations activate user2

Now you're back to user2.

  1. Set PROJECTID2 to the second project. Find the second project id from the left side of the lab guide. Inside the SSH session run the following, replacing <second project id> with the second project's Project ID:

echo "export PROJECTID2=<second project id>" >> ~/.bashrc . ~/.bashrc gcloud config set project $PROJECTID2 Note: This command appends the `bashrc` file, so be careful.

You will get a warning: WARNING: You do not appear to have access to project [your 2nd project id] or it does not exist.

Note: When prompted, Do you want to continue (Y/n)?, type N and press ENTER.

This means that you don't have access to the PROJECTID2 project, which you will fix shortly.

  1. Switch back to the default gcloud configuration. Inside the SSH session run:

gcloud config configurations activate default

You need to switch back to the first user, which has the permission to grant access to the second user.

  1. Set the value of USERID2 to the second user name and bind the role of viewer to the second user onto the second project.
Note: Find the second user name on the left of this page, in the following command replace `SECOND_USER_ACCOUNT` with the second user's email.
  1. First, Install jq:
sudo yum -y install epel-release sudo yum -y install jq
  1. Inside the SSH session run:

echo "export USERID2=SECOND_USER_NAME" >> ~/.bashrc . ~/.bashrc gcloud projects add-iam-policy-binding $PROJECTID2 --member user:$USERID2 --role=roles/viewer

Once you have run the command you will see (you might need to scroll up), the text that looks something like:

Updated IAM policy for project [qwiklabs-gcp-336e4f5b8aff1c01]. bindings: ... - members: - serviceAccount:qwiklabs-gcp-01-a262cff86157@qwiklabs-gcp-01-a262cff86157.iam.gserviceaccount.com - user:student-01-1b9999e9cc77@qwiklabs.net - user:student-01-c831155b330a@qwiklabs.net role: roles/viewer Restricting Username 2 to roles/viewer in Project 2

Task 5. Test that user2 has access

  1. Switch your gcloud configuration to user2. Inside the SSH session run:

gcloud config configurations activate user2
  1. Change the configuration for user2 to the second project. Inside the SSH session run:

gcloud config set project $PROJECTID2

You should not see an error message this time.

  1. Verify you have viewer access. Inside the SSH session run:

gcloud compute instances list

You will see 0 instances in this project.

  1. Try to create an instance in the second project as the second user. Inside the SSH session run:

gcloud compute instances create lab-2

This command will fail because user2 only has viewer access to the project.

  1. Switch your gcloud configuration to default. Inside the SSH session run:

gcloud config configurations activate default

You are now back to using your original user account credentials.

Create a new role with permissions

Next, create the new role with the set of permissions needed for the devops team.

  • Create a custom role called devops that has the permissions to create an instance. Inside the SSH session run:

gcloud iam roles create devops --project $PROJECTID2 --permissions "compute.instances.create,compute.instances.delete,compute.instances.start,compute.instances.stop,compute.instances.update,compute.disks.create,compute.subnetworks.use,compute.subnetworks.useExternalIp,compute.instances.setMetadata,compute.instances.setServiceAccount"

This command creates a custom role in the project called devops with the permissions to create and manage instances.

The full name of the role is listed, note the role is in the project so the path is in the pattern of projects/PROJECT/roles/ROLENAME.

Create a new role with permissions for the devops team

Bind the role to the second account to both projects

You now have the role created and need to bind the user and the role to the project. You will use gcloud projects add-iam-policy-binding to perform the binding. To make this command easier to execute, set a couple of environment variables first; the project id and the user account.

  1. Bind the role of iam.serviceAccountUser to the second user onto the second project. Inside the SSH session run:

gcloud projects add-iam-policy-binding $PROJECTID2 --member user:$USERID2 --role=roles/iam.serviceAccountUser

You need permissions to create an instance with a service account attached. The role iam.serviceAccountUser has those permissions, so use this pre-defined role.

Check user2 is bound to project2 and the role roles/iam.serviceAccountUser
  1. Bind the custom role devops to the second user onto the second project. You can find the second user account on the left of this page. Make sure you set USERID to the second user account.

Inside the SSH session run:

gcloud projects add-iam-policy-binding $PROJECTID2 --member user:$USERID2 --role=projects/$PROJECTID2/roles/devops

Once you have run the command you will see (you might need to scroll up), the text that looks something like the example below:

Updated IAM policy for project [qwiklabs-gcp-336e4f5b8affxxxx]. bindings: - members: - user:gcpstaginguser80_student@qwiklabs.net role: projects/qwiklabs-gcp-336e4f5b8affxxxx/roles/devops Bound Username 2 to devops role

Test the newly assigned permissions.

  1. Switch your gcloud configuration to user2. Inside the SSH session run:

gcloud config configurations activate user2

Now you're back to user2.

  1. Try to create an instance called lab-2. Inside the SSH session run:

gcloud compute instances create lab-2

Now the instance creation works for user2.

Create an instance with name as lab-2 in Project 1
  1. Verify the instance exists. Inside the SSH session run:

gcloud compute instances list

Your environment

After these last changes your environment will look like this.

Lab progress illustration

Task 6. Using a service account

You have seen how to authenticate and use gcloud to access Google Cloud services with roles. Now you'll look at a typical approach.

You have an application that will use the Application Programming Interfaces (APIs) to read and write to Cloud Storage buckets. You don't want to have to authenticate every time you launch a new server, that would be both painful and not in the spirit of using the cloud! So, you will use service accounts.

A service account is a special Google account that belongs to your application or a virtual machine (VM) instead of to an individual end user. Your application uses the service account to call the Google API of a service so that the users aren't directly involved.

Learn more about service accounts from the Service accounts Guide.

Now you will create a service account, use that service account with a compute instance, then test that the service account allows the access you need.

Create a service account

  1. Switch your gcloud configuration to default, user2 doesn't have the rights to set up and configure service accounts. Inside the SSH session run:

gcloud config configurations activate default
  1. Set the project to PROJECTID2 in your configuration. Inside the SSH session run:

gcloud config set project $PROJECTID2

Make sure you are targeting the right project.

  1. Create the service account. Inside the SSH session run:

gcloud iam service-accounts create devops --display-name devops Check the created devops service account
  1. Get the service account email address. Inside the SSH session run:

gcloud iam service-accounts list --filter "displayName=devops" Note: The filter shows only the line you are interested in. Notice that the email address contains the role name and the project id.
  1. Put the email address into a local variable called SA. Inside the SSH session run:

SA=$(gcloud iam service-accounts list --format="value(email)" --filter "displayName=devops")

This command sets the SA local variable to the email address of the service account. Pretty useful right?

  1. Give the service account the role of iam.serviceAccountUser. Inside the SSH session run:

gcloud projects add-iam-policy-binding $PROJECTID2 --member serviceAccount:$SA --role=roles/iam.serviceAccountUser

This role allows the service account to assign a service account to a compute instance.

Check devops service account is bound to project2 and the role roles/iam.serviceAccountUser

Task 7. Using the service account with a compute instance

  1. Give the service account the role of compute.instanceAdmin. Inside the SSH session run:

gcloud projects add-iam-policy-binding $PROJECTID2 --member serviceAccount:$SA --role=roles/compute.instanceAdmin

This role allows the service account to manage compute instances.

Check devops service account is bound to project2 and the role roles/compute.instanceAdmin
  1. Create an instance with the devops service account attached. You also have to specify an access scope that defines the API calls that the instance can make. Inside the SSH session run:

gcloud compute instances create lab-3 --service-account $SA --scopes "https://www.googleapis.com/auth/compute"

Access scopes are the legacy method of specifying permissions for your instance. Access scopes are not a security mechanism. Instead, they define the default OAuth scopes used in requests from the gcloud tool or the client libraries. They have no effect when making requests not authenticated through OAuth, such as gRPC or the SignBlob APIs.

You must set up access scopes when you configure an instance to run as a service account.

A best practice is to set the full cloud-platform access scope on the instance, then securely limit the service account's API access with IAM roles.

Access scopes apply on a per-instance basis. You set access scopes when creating an instance and the access scopes persist only for the life of the instance.

Access scopes have no effect if you have not enabled the related API on the project that the service account belongs to. For example, granting an access scope for Cloud Storage on a virtual machine instance allows the instance to call the Cloud Storage API only if you have enabled the Cloud Storage API on the project.

Check lab-3 has the service account attached

Task 8. Test the service account

  1. Connect to the newly created instance using gcloud compute ssh. Inside the SSH session run:

gcloud compute ssh lab-3

Press ENTER when asked if you want to continue.

Press ENTER twice to skip making a password.

  1. The default image used already contains gcloud configuration. Inside the SSH session run:

gcloud config list

You will see the configuration has the service account

  1. Create an instance. This tests that you have the necessary permissions via the service account:

gcloud compute instances create lab-4

You can press ENTER to accept the default zone for this VM.

  1. Check roles attached are working. Inside the SSH session run:

gcloud compute instances list

Because the service account has permissions, you can see the instances listed.

Your environment now looks like this

Final lab environment illustration

Congratulations!

You have completed the following tasks using the Cloud SDK tool, gcloud:

  • Installed and configured the gcloud client
  • Created and switched between multiple IAM configurations
  • Identified and assigned correct IAM permissions
  • Created and used a service account

Finish your quest

This self-paced lab is part of the Using the Cloud SDK Command Line Quest. A quest is a series of related labs that form a learning path. Completing this quest earns you a badge to recognize your achievement. You can make your badge or badges public and link to them in your online resume or social media account. Enroll in this quest or any quest that contains this lab and get immediate completion credit. See the Google Cloud Skills Boost catalog to see all available quests.

Take your next lab

Continue your quest with Using gsutil to perform Operations on Buckets and Objects or try one of these suggestions:

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated September 15, 2022

Lab Last Tested September 15, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.