# Service Accounts — Google Cloud Platform

Source: https://www.skillbyai.com/en/gcp/i-sa

> Run workloads as service accounts without downloading keys.

## Identities for code

A **service account** is an identity for an application or VM rather than a person, with an email such as `orders-api@shop-dev-123456.iam.gserviceaccount.com`. You **attach** a service account to a Compute Engine VM, Cloud Run service, Cloud Run function or GKE workload, and the platform's metadata server supplies short-lived tokens automatically. Give each workload **its own service account** with only the roles it needs, rather than relying on the broad default Compute Engine service account. **Service account keys** (downloadable JSON files) are long-lived secrets that are easy to leak; avoid them, and enforce the organization policy that blocks key creation. If a person or pipeline needs to act as a service account, use **impersonation**, which requires the *Service Account Token Creator* role and produces short-lived credentials, all recorded in audit logs.

## A dedicated identity for a Cloud Run service

The service gets only the access it needs; no key file exists anywhere.

```bash
gcloud iam service-accounts create orders-api --display-name="Orders API"

SA=orders-api@shop-dev-123456.iam.gserviceaccount.com
gcloud projects add-iam-policy-binding shop-dev-123456 \
  --member="serviceAccount:$SA" --role="roles/pubsub.publisher"

gcloud run deploy orders-api --image=asia-south1-docker.pkg.dev/shop-dev-123456/apps/orders:1.0 \
  --service-account="$SA" --region=asia-south1

# a human testing as that identity (needs Token Creator on the SA)
gcloud storage ls --impersonate-service-account="$SA"
```

## A staff ID card, not a photocopied key

An attached service account is like a staff ID the building checks every time: it can be revoked instantly. A downloaded key is a photocopied key; once it leaves the building you cannot tell who is using it.

**Quiz:** What is the safest way for a Cloud Run service to call other Google Cloud APIs?

- [ ] Embed a service account JSON key in the image
- [x] Attach a dedicated service account with narrowly scoped roles
- [ ] Use the project Owner's personal credentials
- [ ] Make the target API public

*Answer:* Attach a dedicated service account with narrowly scoped roles. An attached, dedicated service account gets short-lived tokens automatically and limits the blast radius.
