IAM Roles and Service Accounts
Intermediate10 minTrending
Create service accounts, assign IAM roles, and manage permissions for secure access to GCP resources.
Prerequisites
- -gcloud CLI installed
- -Project Owner or IAM Admin role
Steps
1
Create a service account
Creates a service account that applications use to authenticate to GCP APIs.
$ gcloud iam service-accounts create myapp-sa --display-name "My App Service Account" --description "Service account for myapp"
2
Grant a role to the service account
Assigns the Storage Object Viewer role, granting read-only access to Cloud Storage objects.
$ gcloud projects add-iam-policy-binding my-project-id --member "serviceAccount:myapp-sa@my-project-id.iam.gserviceaccount.com" --role "roles/storage.objectViewer"
Follow the principle of least privilege. Grant the narrowest role that meets the requirement.
3
Create and download a key file
Generates a JSON key file for authenticating as the service account.
$ gcloud iam service-accounts keys create key.json --iam-account myapp-sa@my-project-id.iam.gserviceaccount.com
Key files are long-lived credentials. Prefer Workload Identity Federation for production. Never commit key files to version control.
4
List IAM policy bindings
Displays all role bindings in the project in a readable table.
$ gcloud projects get-iam-policy my-project-id --flatten="bindings[].members" --format="table(bindings.role, bindings.members)"
5
Revoke a role
Removes the specified role from the service account.
$ gcloud projects remove-iam-policy-binding my-project-id --member "serviceAccount:myapp-sa@my-project-id.iam.gserviceaccount.com" --role "roles/storage.objectViewer"
Full Script
FAQ
Discussion
Loading comments...