TExcelTAD
Home › Azure & Google Cloud for AWS Users › Managed Identities and Service Accounts

Managed Identities and Service Accounts

Code running in the cloud needs credentials to call other services: a VM reading a bucket, a function writing to a queue. The rule on every cloud is the same: don't put secrets in the code; let the platform hand the workload short-lived tokens. AWS does it with roles and instance profiles. Azure uses managed identities; Google Cloud uses service accounts attached to resources.

On AWS this is… an IAM role with a trust policy for ec2.amazonaws.com, attached through an instance profile (or a Lambda execution role, an ECS task role), with temporary credentials from the instance metadata service. See IAM Users, Groups and Roles.

Side by side

AWS Azure Google Cloud
The identity IAM role managed identity (a service principal managed by Azure) service account (name@project.iam.gserviceaccount.com)
Lifetime options role exists independently system-assigned (created and deleted with one resource) or user-assigned (standalone, attach to many) standalone resource; attach to many
Attach to a VM instance profile identity on the VM serviceAccount on the instance
Token source in the VM IMDS 169.254.169.254 (IMDSv2) IMDS 169.254.169.254/metadata/identity/oauth2/token metadata server metadata.google.internal
Grant it access policies on the role Azure RBAC role assignments to its principal ID IAM bindings naming serviceAccount:…
Who may attach it? iam:PassRole permission to assign the user-assigned identity (Managed Identity Operator) roles/iam.serviceAccountUser on the service account
SDK default chain default credential provider chain DefaultAzureCredential Application Default Credentials

The "who may attach it" row is the privilege-escalation check on every cloud. If a developer can attach a powerful identity to a VM they control, they have that identity's power. AWS guards it with iam:PassRole, Azure with rights on the user-assigned identity, Google Cloud with iam.serviceAccounts.actAs (in roles/iam.serviceAccountUser).

A service account is also a resource

On Google Cloud a service account is two things at once:

  • a principal: it can be granted roles (serviceAccount:shop-api@… in a bucket's policy);
  • a resource: it has its own allow policy that says who can use it (serviceAccountUser), impersonate it for tokens (serviceAccountTokenCreator), or let Kubernetes workloads act as it (workloadIdentityUser).

Impersonation is the GCP way to test as a service account without any key:

bash
gcloud storage ls gs://shop-prod-invoices \
    --impersonate-service-account=shop-api@shop-api-prod-4821.iam.gserviceaccount.com

Creating and attaching

Azure, sample session: a user-assigned identity, a role for it, and a VM that uses it.

bash
az identity create -g rg-shop-dev-app -n id-shop-api
PRINCIPAL_ID=$(az identity show -g rg-shop-dev-app -n id-shop-api --query principalId -o tsv)
ST_ID=$(az storage account show -g rg-shop-dev-data -n stshopdev01 --query id -o tsv)

az role assignment create --assignee-object-id "$PRINCIPAL_ID" --assignee-principal-type ServicePrincipal \
    --role "Storage Blob Data Reader" --scope "$ST_ID"

az vm create -g rg-shop-dev-app -n vm-api-1 --image Ubuntu2404 --size Standard_D2s_v5 \
    --assign-identity "$(az identity show -g rg-shop-dev-app -n id-shop-api --query id -o tsv)" \
    --admin-username azureuser --generate-ssh-keys --zone 1

Google Cloud, sample session: a service account, a role on a bucket, and a VM that runs as it.

bash
gcloud iam service-accounts create shop-api --display-name="shop API"
SA=shop-api@shop-dev-4821.iam.gserviceaccount.com

gcloud storage buckets add-iam-policy-binding gs://shop-dev-invoices \
    --member="serviceAccount:$SA" --role="roles/storage.objectViewer"

gcloud compute instances create api-1 --zone=europe-west1-b --machine-type=e2-medium \
    --image-family=debian-12 --image-project=debian-cloud \
    --service-account="$SA" --scopes=cloud-platform

--scopes=cloud-platform looks alarming but is the recommended setting: access scopes are a legacy, coarse second filter on VMs, and Google advises granting the full scope and controlling access with IAM roles on the service account.

Getting a token from inside the workload

You rarely do this by hand (SDKs do it), but seeing it once demystifies the "magic":

bash
# inside an Azure VM
curl -s -H "Metadata: true" \
  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://storage.azure.com/"

# inside a Compute Engine VM
curl -s -H "Metadata-Flavor: Google" \
  "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token"

Sample output (shortened):

text
{"access_token":"eyJ0eXAiOi...","expires_in":"86399","resource":"https://storage.azure.com/","token_type":"Bearer",...}
{"access_token":"ya29.c.b0Aaek...","expires_in":3599,"token_type":"Bearer"}

Both metadata endpoints require a special header, which blocks simple server-side request forgery attacks the way IMDSv2's session token does on AWS.

Model: what can a workload reach?

Who-can-reach-what is a graph: the workload's identity, the roles bound to it, and anything it can impersonate. This model follows impersonation edges, the way an attacker would:

python · try it yourself
can_impersonate = {   # service account -> service accounts it holds TokenCreator/actAs on
    "sa:ci-runner": ["sa:deployer"],
    "sa:deployer":  ["sa:prod-admin"],
    "sa:shop-api":  [],
}
roles = {
    "sa:ci-runner":  ["artifactregistry.writer"],
    "sa:deployer":   ["run.developer"],
    "sa:prod-admin": ["owner"],
    "sa:shop-api":   ["storage.objectViewer", "cloudsql.client"],
}

def reachable(start):
    seen, todo = [], [start]
    while todo:
        sa = todo.pop(0)
        if sa not in seen:
            seen.append(sa)
            todo.extend(can_impersonate.get(sa, []))
    return seen

for workload in ["sa:shop-api", "sa:ci-runner"]:
    path = reachable(workload)
    effective = sorted({r for sa in path for r in roles[sa]})
    print(f"{workload}: via {' -> '.join(path)}")
    print(f"    effective roles: {effective}")
sa:shop-api: via sa:shop-api
    effective roles: ['cloudsql.client', 'storage.objectViewer']
sa:ci-runner: via sa:ci-runner -> sa:deployer -> sa:prod-admin
    effective roles: ['artifactregistry.writer', 'owner', 'run.developer']

The CI runner has only a registry role on paper, but a chain of impersonation grants makes it a project owner. Review who can use service accounts and managed identities, not just what roles they hold.

Keys: don't

Both clouds still let you create long-lived credentials for these identities: service account JSON keys on Google Cloud, client secrets or certificates on Entra app registrations. They are the equivalent of IAM user access keys. Use attached identities inside the cloud and federation from outside (next lesson), and block key creation with policy (iam.disableServiceAccountKeyCreation on Google Cloud).

Go further: Workload Identity compares instance roles, managed identities and pod identity, and explains the node-identity trap.

Test yourself

What is the difference between system-assigned and user-assigned managed identities?

  1. System-assigned ones can't get tokens
  2. A system-assigned identity lives and dies with one resource; a user-assigned one is standalone and can be attached to many
  3. User-assigned ones need a client secret
  4. There is none

Which Google Cloud role lets a principal attach a service account to a VM it creates (the PassRole equivalent)?

  1. roles/iam.serviceAccountUser
  2. roles/viewer
  3. roles/compute.viewer
  4. roles/iam.securityReviewer

Why does --scopes=cloud-platform not mean the VM can do everything?

  1. Scopes are ignored
  2. Access is still limited by the IAM roles granted to the attached service account
  3. It only works in one zone
  4. It requires a key