Workload Identity
Workload Identity allows you to assign a specific Google Cloud Service Account to a specific application, so that each application can get its own service account identity/permissions using Machine Credential.

Create Service Accounts

Create a Kubernetes Service Account (KSA)

1
kubectl create serviceaccount helloworld \
2
--dry-run -oyaml > k8s/helloworld-sa.yaml
3
4
kubectl apply -f k8s/helloworld-sa.yaml
Copied!

Create a Google Cloud Service Account (GSA)

1
gcloud iam service-accounts create helloworld
2
3
PROJECT_ID=$(gcloud config get-value project)
4
gcloud projects add-iam-policy-binding ${PROJECT_ID} \
5
--member serviceAccount:[email protected]${PROJECT_ID}.iam.gserviceaccount.com \
6
--role roles/pubsub.publisher
Copied!

Bind Service Accounts

Bind the Kubernetes Service Account (KSA) to Google Cloud Service Account (GSA)

Binding from Google Cloud

1
PROJECT_ID=$(gcloud config get-value project)
2
gcloud iam service-accounts add-iam-policy-binding \
3
--role roles/iam.workloadIdentityUser \
4
--member "serviceAccount:${PROJECT_ID}.svc.id.goog[default/helloworld]" \
5
[email protected]${PROJECT_ID}.iam.gserviceaccount.com
Copied!

Binding from Kubernetes

1
PROJECT_ID=$(gcloud config get-value project)
2
kubectl annotate -f k8s/helloworld-sa.yaml \
3
iam.gke.io/gcp-service-account=[email protected]${PROJECT_ID}.iam.gserviceaccount.com
4
5
kubectl apply -f k8s/helloworld-sa.yaml
Copied!

Use the Kubernetes Service Account

k8s/nginx-sa-deployment.yaml
1
apiVersion: apps/v1
2
kind: Deployment
3
metadata:
4
name: nginx-sa
5
labels:
6
app: nginx-sa
7
spec:
8
replicas: 1
9
selector:
10
matchLabels:
11
app: nginx-sa
12
template:
13
metadata:
14
labels:
15
app: nginx-sa
16
spec:
17
# Specify the KSA to use
18
serviceAccountName: helloworld
19
containers:
20
- image: nginx
21
name: nginx
Copied!
To try it out, first exec into the Pod:
1
POD_NAME=$(kubectl get pods -lapp=nginx-sa -o jsonpath='{.items[0].metadata.name}')
2
3
kubectl exec -ti ${POD_NAME} -- /bin/bash
Copied!
Inside the Pod, see metadata server:
1
curl -H"Metadata-Flavor: Google" \
2
http://metadata/computeMetadata/v1/instance/service-accounts/default/email
Copied!
Last modified 1yr ago