Bird
Raised Fist0
GCPcloud~5 mins

Service accounts for applications in GCP - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Applications often need to access Google Cloud resources securely. Service accounts let applications prove who they are and get permission to use these resources without using personal user accounts.
When you want your app to read data from a Google Cloud Storage bucket safely.
When your app needs to write logs to Google Cloud Logging automatically.
When you want to run a virtual machine that accesses a database without sharing your personal login.
When you deploy a cloud function that needs to call other Google Cloud services securely.
When you want to limit what your app can do by giving it only the permissions it needs.
Config File - service-account-policy.json
service-account-policy.json
{
  "bindings": [
    {
      "role": "roles/storage.objectViewer",
      "members": [
        "serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com"
      ]
    }
  ]
}

This JSON file defines a policy that gives the service account named my-app-sa@my-project.iam.gserviceaccount.com permission to view objects in Google Cloud Storage.

The bindings section links the role roles/storage.objectViewer to the service account member.

Commands
This command creates a new service account named 'my-app-sa' with a friendly display name. This account will represent your application when accessing Google Cloud resources.
Terminal
gcloud iam service-accounts create my-app-sa --display-name "My App Service Account"
Expected OutputExpected
Created service account [my-app-sa].
--display-name - Sets a human-readable name for the service account.
This command grants the service account permission to view objects in Cloud Storage by adding a policy binding to the project.
Terminal
gcloud projects add-iam-policy-binding my-project --member="serviceAccount:my-app-sa@my-project.iam.gserviceaccount.com" --role="roles/storage.objectViewer"
Expected OutputExpected
Updated IAM policy for project [my-project].
--member - Specifies the service account to grant permissions.
--role - Specifies the permission role to assign.
This command creates a private key file for the service account. Your application will use this key to authenticate as the service account.
Terminal
gcloud iam service-accounts keys create my-app-sa-key.json --iam-account=my-app-sa@my-project.iam.gserviceaccount.com
Expected OutputExpected
created key [projects/my-project/serviceAccounts/my-app-sa@my-project.iam.gserviceaccount.com/keys/XXXXXXXXXXXXXXXXXXXX] of service account [my-app-sa@my-project.iam.gserviceaccount.com] to [my-app-sa-key.json]
--iam-account - Specifies which service account to create the key for.
This command activates the service account locally using the key file, so you can test commands as that service account.
Terminal
gcloud auth activate-service-account my-app-sa@my-project.iam.gserviceaccount.com --key-file=my-app-sa-key.json
Expected OutputExpected
Activated service account credentials for: [my-app-sa@my-project.iam.gserviceaccount.com]
--key-file - Specifies the private key file to use for authentication.
This command lists the active accounts to verify that the service account is now active.
Terminal
gcloud auth list
Expected OutputExpected
Credentialed Accounts: ACTIVE ACCOUNT * my-app-sa@my-project.iam.gserviceaccount.com user@example.com
Key Concept

If you remember nothing else from this pattern, remember: service accounts let your applications securely prove their identity and get only the permissions they need.

Common Mistakes
Using personal user credentials instead of a service account for applications.
This risks exposing personal credentials and does not allow fine-grained permission control for apps.
Always create and use a dedicated service account with only the needed permissions.
Not creating or downloading a service account key file for application authentication.
Without the key file, the application cannot authenticate as the service account.
Use 'gcloud iam service-accounts keys create' to generate and download the key file.
Assigning overly broad roles like owner to the service account.
This gives the app more permissions than needed, increasing security risks.
Assign only the minimum roles required for the app's tasks.
Summary
Create a service account to represent your application.
Grant the service account only the permissions it needs using IAM roles.
Generate and download a key file for the service account to authenticate your app.
Activate the service account locally to test permissions.
Verify the active account to confirm the service account is in use.

Practice

(1/5)
1. What is the main purpose of a service account in Google Cloud Platform (GCP)?
easy
A. To allow applications to authenticate and access GCP resources securely
B. To create user accounts for people to log in to GCP Console
C. To store data in Google Cloud Storage buckets
D. To monitor network traffic between virtual machines

Solution

  1. Step 1: Understand service account role

    A service account is a special account used by applications or virtual machines to authenticate and access Google Cloud resources securely without user intervention.
  2. Step 2: Differentiate from user accounts

    User accounts are for people to log in, while service accounts are for applications or services to act on behalf of users or themselves.
  3. Final Answer:

    To allow applications to authenticate and access GCP resources securely -> Option A
  4. Quick Check:

    Service account = app authentication [OK]
Hint: Service accounts are for apps, not people [OK]
Common Mistakes:
  • Confusing service accounts with user accounts
  • Thinking service accounts store data
  • Assuming service accounts monitor network
2. Which of the following is the correct way to assign a service account to a Compute Engine VM instance during creation?
easy
A. Use the --service-account flag with gcloud compute instances create
B. Add the service account email to the VM's firewall rules
C. Specify the service account in the VM's startup script
D. Create a user account with the same name as the service account

Solution

  1. Step 1: Identify how to assign service accounts to VMs

    The gcloud compute instances create command supports a --service-account flag to specify which service account the VM should use.
  2. Step 2: Eliminate incorrect options

    Firewall rules do not assign service accounts, startup scripts do not assign service accounts, and user accounts are unrelated to service account assignment.
  3. Final Answer:

    Use the --service-account flag with gcloud compute instances create -> Option A
  4. Quick Check:

    Assign service account with --service-account flag [OK]
Hint: Use --service-account flag when creating VM [OK]
Common Mistakes:
  • Trying to assign service account via firewall
  • Using startup scripts to assign service accounts
  • Confusing user accounts with service accounts
3. Consider this Python code snippet using Google Cloud client libraries:
from google.cloud import storage

client = storage.Client()
buckets = list(client.list_buckets())
print(len(buckets))

What must be true for this code to successfully list buckets?
medium
A. The user must be logged in to GCP Console in a browser
B. The environment must have a service account with Storage Viewer role configured
C. The code must run on a VM with no service account assigned
D. No authentication is needed to list buckets

Solution

  1. Step 1: Understand authentication requirement

    Google Cloud client libraries require authentication, usually via a service account or user credentials, to access resources like buckets.
  2. Step 2: Identify required permissions

    To list buckets, the service account or user must have at least the Storage Viewer role to read bucket metadata.
  3. Final Answer:

    The environment must have a service account with Storage Viewer role configured -> Option B
  4. Quick Check:

    Service account with Storage Viewer role needed [OK]
Hint: List buckets needs Storage Viewer role on service account [OK]
Common Mistakes:
  • Assuming user login in browser is enough
  • Running code without any service account
  • Thinking no auth is needed for bucket listing
4. You deployed an application on a GCP VM with a service account, but it fails to access Cloud Storage buckets. What is the most likely cause?
medium
A. The service account email is not the same as the VM name
B. The VM does not have an external IP address
C. The application code is missing the Cloud Storage client library import
D. The service account lacks the necessary IAM permissions for Cloud Storage

Solution

  1. Step 1: Check service account permissions

    If the application cannot access Cloud Storage, the most common reason is missing IAM permissions on the service account assigned to the VM.
  2. Step 2: Rule out other causes

    Lack of external IP does not block access if using private Google access; missing import causes code errors but not permission failures; service account email unrelated to VM name.
  3. Final Answer:

    The service account lacks the necessary IAM permissions for Cloud Storage -> Option D
  4. Quick Check:

    Missing IAM permissions cause access failure [OK]
Hint: Check IAM roles on service account first [OK]
Common Mistakes:
  • Assuming external IP is required for access
  • Blaming code imports without error evidence
  • Confusing service account email with VM name
5. You want to deploy a serverless application on Cloud Run that accesses a Cloud SQL database securely. Which approach correctly uses a service account to grant least privilege access?
hard
A. Assign the Cloud Run service account the Storage Admin role to access Cloud SQL
B. Use the default Compute Engine service account with Owner role for Cloud Run
C. Create a service account with only Cloud SQL Client role and assign it to the Cloud Run service
D. Create a user account with Cloud SQL Admin role and embed its credentials in the app

Solution

  1. Step 1: Identify least privilege principle

    Grant only the permissions needed. For Cloud SQL access, the Cloud SQL Client role is sufficient.
  2. Step 2: Assign correct service account to Cloud Run

    Create a dedicated service account with Cloud SQL Client role and assign it to the Cloud Run service to avoid over-permission.
  3. Step 3: Eliminate insecure or excessive options

    Using default service account with Owner role is too broad; Storage Admin role is unrelated; embedding user credentials is insecure.
  4. Final Answer:

    Create a service account with only Cloud SQL Client role and assign it to the Cloud Run service -> Option C
  5. Quick Check:

    Least privilege: Cloud SQL Client role on service account [OK]
Hint: Use least privilege role on dedicated service account [OK]
Common Mistakes:
  • Using overly broad Owner role
  • Assigning unrelated roles like Storage Admin
  • Embedding user credentials in app code