How to Create a Service Account in GCP: Step-by-Step Guide
To create a service account in GCP, use the
gcloud iam service-accounts create command or the Google Cloud Console under IAM & Admin > Service Accounts. This creates an identity your applications can use to access GCP resources securely.Syntax
The basic command to create a service account using the gcloud CLI is:
gcloud iam service-accounts create [NAME]: Creates a new service account with the given name.--description: Optional text describing the service account.--display-name: Optional friendly name shown in the console.
Replace [NAME] with your desired service account ID.
bash
gcloud iam service-accounts create [NAME] --description="DESCRIPTION" --display-name="DISPLAY_NAME"
Example
This example creates a service account named my-app-sa with a description and display name. It shows how to run the command and the expected output.
bash
gcloud iam service-accounts create my-app-sa --description="Service account for my app" --display-name="My App Service Account"
Output
Created service account [my-app-sa].
Common Pitfalls
Common mistakes when creating service accounts include:
- Using invalid characters or uppercase letters in the service account name. It must be lowercase, digits, or hyphens only.
- Not specifying the correct project with
--project, which creates the account in the wrong project. - Forgetting to grant roles or permissions after creating the account, so it cannot access resources.
Always verify the project and assign roles after creation.
bash
Wrong: gcloud iam service-accounts create MyServiceAccount Right: gcloud iam service-accounts create my-service-account --project=my-project
Quick Reference
| Command | Description |
|---|---|
| gcloud iam service-accounts create [NAME] | Create a new service account |
| gcloud iam service-accounts list | List all service accounts in the project |
| gcloud projects add-iam-policy-binding [PROJECT_ID] --member="serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role="roles/ROLE" | Grant a role to the service account |
| gcloud iam service-accounts keys create key.json --iam-account=[NAME]@[PROJECT_ID].iam.gserviceaccount.com | Create and download a key for the service account |
Key Takeaways
Use the gcloud CLI or Cloud Console to create service accounts in GCP.
Service account names must be lowercase and can include digits and hyphens only.
Always specify the correct project to avoid creating accounts in the wrong place.
Assign roles to the service account after creation to grant access to resources.
Download keys only when necessary and keep them secure.