CareerByteCode
ByteBlogby CareerByteCode

Google Cloud IAM for Beginners: Roles, Members and Least Privilege

What you build: a project where each person has only what they need, in your own Google Cloud account. Every step, command and screenshot explained for beginners.

Google Cloud IAM for Beginners: Roles, Members and Least Privilege

✍️ Translate this blog into Hindi, Tamil or Telugu

In this lab you learn Google Cloud IAM by testing it, not by reading about it. You create a bucket with one file, create a robot member called dev-reader, give it a read-only role on that one bucket, and then act as dev-reader to see what is really allowed and what is denied. Then you write a custom role with exactly one permission and test again. You finish by deleting everything.

Who it is for: beginners who keep seeing "Permission denied" and want to understand why. Time: about 1 hour. Cost: free tier (IAM itself is free; the lab stores two tiny files in Cloud Storage for a few minutes).

Every command below was run for real by the CareerByteCode Team on a fresh Google Cloud project, and every output and screenshot is the real result we got (account and project details are blurred). We ran the commands from a terminal with the Google Cloud CLI; Cloud Shell in your browser has the same tools, so you can copy and paste each command there.

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →

Part A: IAM in plain English

IAM (Identity and Access Management) answers one question: WHO can do WHAT on WHICH resource?

WHO, WHAT, WHICH
A member gets a role on a resource; the test shows what is allowed and what is denied
  • Member (WHO): a Google account (user:), a group, or a service account (serviceAccount:), which is a robot account for apps and scripts.
  • Permission: one action, written service.resource.verb, for example storage.objects.get (read a file).
  • Role (WHAT): a named set of permissions. Google gives you predefined roles like Storage Object Viewer; you can also make custom roles.
  • Resource (WHICH): where the role applies: a whole project, or one bucket, one secret, one VM.
  • Binding: one line in an IAM policy that says "this member has this role on this resource".
  • Least privilege: give only the permissions needed, on the smallest resource, for as long as needed.

Real-life example: an office key card. The card (member) is programmed for some doors (role) on one floor (resource). It opens the meeting room but not the server room. If a new hire only needs the meeting room, you do not give them the master key "just in case".

Two more ideas you will see in action:

  • Deny by default: if no binding allows an action, it is denied.
  • Impersonation: with the Service Account Token Creator role you can run a command as a service account. We use it to test exactly what dev-reader can do, from your own terminal.

Before you start

  1. A Google Cloud account (the free trial works) and a project with billing linked, where you are Owner (a new project you created).
  2. Open Cloud Shell (the >_ icon at the top of the Google Cloud console).
  3. Save your project id (put your own id between the quotes):
export PROJECT_ID="your-project-id"

Part B: the lab

Step 1: who are you in this project?

Why: before giving roles, know your own. The filter keeps only the bindings for your own account (gcloud config get-value account prints it, so the command never needs your email typed in).

gcloud config set project $PROJECT_ID
gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" \
  --filter="bindings.members:user:$(gcloud config get-value account)" --format="table(bindings.role)"
Updated property [core/project].
ROLE
roles/owner

You are Owner: you can do almost everything, including changing IAM.

Step 2: create the resource, a bucket with one file

Why: we need something to protect. --uniform-bucket-level-access means only IAM decides access (no old per-file lists).

gcloud storage buckets create gs://$PROJECT_ID-iam-lab --location=us-east1 --uniform-bucket-level-access
echo "Quarterly report: all numbers are made up for the lab." > report.txt
gcloud storage cp report.txt gs://$PROJECT_ID-iam-lab/
gcloud storage ls gs://$PROJECT_ID-iam-lab/
Creating gs://your-project-id-iam-lab/...
Copying file://report.txt to gs://your-project-id-iam-lab/report.txt
  
..........
gs://your-project-id-iam-lab/report.txt
Your role and the bucket
Steps 1 and 2: you are Owner; the bucket holds report.txt (ids blurred)

Step 3: create a member, a service account called dev-reader

Why: in real life this could be a developer's script or an app. A new service account has no roles, so it can do nothing yet. The short wait gives the new account time to appear everywhere.

gcloud iam service-accounts create dev-reader --display-name="IAM lab: read-only developer"
sleep 15
gcloud iam service-accounts list --filter="email:dev-reader*" --format="value(email)"
Created service account [dev-reader].
Service account email: dev-reader@your-project-id.iam.gserviceaccount.com
dev-reader@your-project-id.iam.gserviceaccount.com

Step 4: look inside a role before you give it

Why: never give a role you have not read. Storage Object Viewer has only "get" and "list" permissions: read files and list them. Nothing that writes or deletes.

gcloud iam roles describe roles/storage.objectViewer --format="yaml(title,includedPermissions)"
includedPermissions:
- resourcemanager.projects.get
- resourcemanager.projects.list
- storage.folders.get
- storage.folders.list
- storage.managedFolders.get
- storage.managedFolders.list
- storage.objects.get
- storage.objects.list
title: Storage Object Viewer
The member and the role
Steps 3 and 4: dev-reader exists; Storage Object Viewer only gets and lists

Step 5: give dev-reader the viewer role on ONE bucket

Why: the binding is on the bucket, not the project. If you add more buckets later, dev-reader still cannot see them.

gcloud storage buckets add-iam-policy-binding gs://$PROJECT_ID-iam-lab \
  --member="serviceAccount:dev-reader@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/storage.objectViewer" --format="value(etag)" > /dev/null
gcloud storage buckets get-iam-policy gs://$PROJECT_ID-iam-lab --format="table[box](bindings.role,bindings.members)" --flatten="bindings"
+----------------------------------+--------------------------------------------------------------------------+
|               ROLE               |                                 MEMBERS                                  |
+----------------------------------+--------------------------------------------------------------------------+
| roles/storage.legacyBucketOwner  | ['projectEditor:your-project-id', 'projectOwner:your-project-id']  |
| roles/storage.legacyBucketReader | ['projectViewer:your-project-id']                                     |
| roles/storage.legacyObjectOwner  | ['projectEditor:your-project-id', 'projectOwner:your-project-id']  |
| roles/storage.legacyObjectReader | ['projectViewer:your-project-id']                                     |
| roles/storage.objectViewer       | ['serviceAccount:dev-reader@your-project-id.iam.gserviceaccount.com'] |
+----------------------------------+--------------------------------------------------------------------------+
The bucket policy
Step 5: the bucket policy now has roles/storage.objectViewer for dev-reader, next to the default owner and reader roles

The legacy... lines are the defaults every bucket gets (project owners, editors and viewers). The new line is ours.

Step 6: allow yourself to act as dev-reader

Why: to test dev-reader's access from your own terminal, you need the Service Account Token Creator role on that one account. IAM changes can take a minute or two to reach every Google server, so the command waits 60 seconds.

gcloud iam service-accounts add-iam-policy-binding dev-reader@$PROJECT_ID.iam.gserviceaccount.com \
  --member="user:$(gcloud config get-value account)" \
  --role="roles/iam.serviceAccountTokenCreator" --format="value(etag)" > /dev/null && echo "token creator granted"
sleep 60
Updated IAM policy for serviceAccount [dev-reader@your-project-id.iam.gserviceaccount.com].
token creator granted

In our run, 60 seconds was not enough: the first test said Failed to impersonate ... Permission 'iam.serviceAccounts.getAccessToken' denied. About 40 seconds later it worked. If you see that message, wait a minute and run Step 7 again.

Step 7: ALLOW test, dev-reader can read the file

gcloud storage cat gs://$PROJECT_ID-iam-lab/report.txt \
  --impersonate-service-account=dev-reader@$PROJECT_ID.iam.gserviceaccount.com 2>&1 | grep -v "^WARNING"
Quarterly report: all numbers are made up for the lab.
Reading works
Steps 6 and 7: acting as dev-reader, the file reads fine

Break it: the DENY tests

Now try things the role does not allow. First, upload a file:

echo "a change" > change.txt
gcloud storage cp change.txt gs://$PROJECT_ID-iam-lab/ \
  --impersonate-service-account=dev-reader@$PROJECT_ID.iam.gserviceaccount.com 2>&1 | grep -v "^WARNING" | tail -2
ERROR: [dev-reader@your-project-id.iam.gserviceaccount.com] does not have permission to access b instance [your-project-id-iam-lab] (or it may not exist): dev-reader@your-project-id.iam.gserviceaccount.com does not have storage.objects.create access to the Google Cloud Storage object. Permission 'storage.objects.create' denied on resource '//storage.googleapis.com/projects/_/buckets/your-project-id-iam-lab/objects/change.txt' (or it may not exist). This command is authenticated as you@example.com which is the active account specified by the [core/account] property. Impersonation is used to impersonate dev-reader@your-project-id.iam.gserviceaccount.com.
..........
📝⭐ Recommended by CareerByteCode · Certification examGoogle Analytics Certification (GA4) PracticeTake the examTake the exam →

The message names the exact permission that is missing: storage.objects.create. Next, list virtual machines in the project:

gcloud compute instances list \
  --impersonate-service-account=dev-reader@$PROJECT_ID.iam.gserviceaccount.com 2>&1 | grep -v "^WARNING" | tail -3
 - Required 'compute.instances.list' permission for 'projects/your-project-id'

Listed 0 items.
Denied
dev-reader cannot upload (no storage.objects.create) and cannot list VMs (no compute.instances.list)

Both are denied, and that is exactly what we want: deny by default, allow only what we gave.

Fix it with least privilege: a custom role with one permission

Suppose dev-reader must also upload new reports, but must never delete or overwrite. The predefined Storage Object Creator role is close; a custom role lets you be exact. Our role has one permission, storage.objects.create:

gcloud iam roles create labUploader --project=$PROJECT_ID \
  --title="Lab uploader" --description="Can add new files, nothing else" \
  --permissions=storage.objects.create --stage=GA --format="yaml(name,title,includedPermissions)"
Created role [labUploader].
includedPermissions:
- storage.objects.create
name: projects/your-project-id/roles/labUploader
title: Lab uploader

Give it on the same bucket and upload again:

gcloud storage buckets add-iam-policy-binding gs://$PROJECT_ID-iam-lab \
  --member="serviceAccount:dev-reader@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="projects/$PROJECT_ID/roles/labUploader" --format="value(etag)" > /dev/null
sleep 30
gcloud storage cp change.txt gs://$PROJECT_ID-iam-lab/ \
  --impersonate-service-account=dev-reader@$PROJECT_ID.iam.gserviceaccount.com 2>&1 | grep -v "^WARNING" | tail -1
gcloud storage ls gs://$PROJECT_ID-iam-lab/
..........
gs://your-project-id-iam-lab/change.txt
gs://your-project-id-iam-lab/report.txt
Custom role
The custom role has one permission; after the binding, dev-reader can upload change.txt

Proof: change.txt is in the bucket. dev-reader can now read and add files on this one bucket, and still cannot delete, cannot see other buckets and cannot see any VM.

Real lesson from our run: the first time we gave the new custom role, Google answered Role ... does not exist in the resource's hierarchy because the role was only seconds old. One minute later the same command worked. New roles and accounts need a short time to spread.

Clean up (delete everything)

Why: remove the bucket (with both files), the service account (this also removes its bindings) and the custom role.

gcloud storage rm --recursive gs://$PROJECT_ID-iam-lab --quiet 2>&1 | tail -1
gcloud iam service-accounts delete dev-reader@$PROJECT_ID.iam.gserviceaccount.com --quiet 2>&1 | tail -1
gcloud iam roles delete labUploader --project=$PROJECT_ID --format="value(deleted)"
echo "buckets left: $(gcloud storage buckets list --format="value(name)" | wc -l)"
echo "lab service accounts left: $(gcloud iam service-accounts list --filter="email:dev-reader*" --format="value(email)" | wc -l)"
..........
deleted service account [dev-reader@your-project-id.iam.gserviceaccount.com]
True
buckets left: 0
lab service accounts left: 0
Clean up
0 buckets and 0 lab service accounts left; the custom role is deleted

A deleted custom role waits 7 days before it is removed for good, and you cannot reuse its id during that time. That is normal.

FAQ

Owner, Editor, Viewer: should I use them? These "basic roles" are very wide. Use them only in your own test projects. For people and apps, use predefined or custom roles on the smallest resource.

What is the difference between a user and a service account? A user is a person who signs in. A service account is for software; it has no password and is used by apps, VMs and pipelines.

Why give the role on the bucket and not the project? A project role applies to every bucket, now and later. A bucket role applies to that bucket only.

How do I see why access was denied? Read the error: it names the missing permission and the resource. The Google Cloud console also has a Policy Troubleshooter (IAM & Admin > Troubleshooter), and the error message links to it.

Why does a new role or account sometimes not work at once? IAM changes spread to all Google servers within seconds to a few minutes. Wait and try again.

Can I give access for a limited time? Yes, with IAM conditions (for example an end date on a binding). That is a good next step after this lab.

Troubleshooting

You seeWhyFix
Failed to impersonate ... iam.serviceAccounts.getAccessToken deniedThe Token Creator role has not spread yet, or was not givenWait 1 to 2 minutes; check Step 6 ran without errors
Role (projects/.../roles/labUploader) does not exist in the resource's hierarchyThe custom role is only seconds oldWait a minute and run the binding again
does not have storage.objects.create accessThe member has no create permission on that bucketExpected in the DENY test; for real use, give a role that has it
Required 'compute.instances.list' permissionThe member has no Compute roleExpected; dev-reader is for storage only
The bucket is not foundTypo in the bucket name, or it was deletedCheck gcloud storage ls
Step 10 fails because the role id was deleted recentlyYou ran Step 10 again within 7 days of deleting itPick a new role id, for example labUploader2

What next

Prepared by the CareerByteCode Team from our tested lab, with AI help for the write-up.

Read next →Secret Manager: Store Passwords and API Keys Safely⏱ 10 min

⭐ Keep learning with CareerByteCode

Hand-picked to go deeper on this topic
News, guides and updates from the CareerByteCode team
🏅 Contributor writer

The CareerByteCode team writes about what is new on careerbytecode.in: courses, labs, exams, events and the community, which is free to join for influencers and content creators in tech.

Get CareerByteCode Team's next blog by email

One email a week when they publish. Add the weekly Best of ByteBlog too. No spam, unsubscribe with one click.

We email you once to confirm. By subscribing you agree to the privacy policy.

💬 Comments (0)

Top · Newest

Sign in to comment

More from CareerByteCode Team

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →