GKE Workload Identity

GKE Workload Identity

Diagnoses and configures Workload Identity Federation for GKE so Pods can authenticate to Google Cloud APIs, covering service account bindings, IAM roles and metadata server health.

Skill files2 files

references/

SKILL.md384 lines
1
---
2
name: gke-workload-identity
3
metadata:
4
version: "1.0.3"
5
category: Security
6
description: >-
7
Configures and diagnoses Workload Identity Federation for GKE authentication failures for Pods
8
(403 "iam.serviceAccounts.getAccessToken" / permission denied, "could not find
9
default credentials", or GKE metadata server unreachable) by verifying
10
cluster and node-pool Workload Identity configuration, the Kubernetes
11
ServiceAccount (KSA) to IAM binding (direct principal binding and legacy Google
12
ServiceAccount impersonation), target-resource IAM roles, and gke-metadata-server
13
health. Use when setting up KSA/GSA bindings (`roles/iam.workloadIdentityUser`,
14
`iam.gke.io/gcp-service-account`) or when a Pod cannot authenticate to Google Cloud APIs. Don't use for in-cluster
15
Kubernetes RBAC errors (API-server authorization), general workload crashes
16
(use gke-workload-troubleshooting), or Pod Security Standards and NetworkPolicies
17
(use gke-workload-security).
18
---
19
20
# GKE Workload Identity Federation Troubleshooting Skill
21
22
Use this skill to systematically diagnose why a Pod using **Workload Identity
23
Federation for GKE** cannot authenticate to Google Cloud APIs. Typical symptoms:
24
25
- `HTTP/403 ... Permission 'iam.serviceAccounts.getAccessToken' denied on
26
resource`
27
- `google.auth.exceptions ... could not find default credentials` /
28
`ComputeEngineCredentials cannot find the metadata server`
29
- API calls that unexpectedly use the node's default Compute Engine service
30
account instead of the workload's identity.
31
32
## Attribution
33
34
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
35
MUST read [Usage Attribution](references/attribution.md). For commands executed
36
directly in the terminal (never in generated scripts, Terraform, or user code),
37
prefix `gcloud` with
38
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gke-workload-identity)"`
39
and append `agent-skills/1.0 (skill:gke-workload-identity)` to `User-Agent` headers.
40
41
## Read-only boundary
42
43
This skill is **diagnostic and non-interactive**. It only **reads** cluster,
44
IAM, and logging state and **proposes** fixes as commands or GitOps manifest
45
changes for a human to apply. It must **never** create or modify IAM bindings,
46
KSA annotations, node pools, or clusters automatically. When evidence is missing
47
or the fix requires a privileged change, summarize findings and hand off to a
48
human (see Step 7).
49
50
## Output discipline (apply to every conclusion)
51
52
When you report a diagnosis, always:
53
54
1. **Name the single most-likely root cause** (not an open-ended list of
55
possibilities).
56
2. **Explicitly rule out** the other plausible causes, citing the evidence that
57
excludes them. In particular, when the cause is node-pool configuration,
58
state plainly that it is **not** a KSA annotation or IAM binding problem;
59
when the cause is a missing role on a target resource, state that Workload
60
Identity itself is **not** misconfigured.
61
3. **Give the exact remediation as a proposed change for a human** — a concrete
62
`gcloud` command (or GitOps manifest edit) with the real identifiers filled
63
in — and never apply it automatically.
64
65
--------------------------------------------------------------------------------
66
67
## Diagnostic Workflow
68
69
### Step 0: Context discovery & time window
70
71
Collect (from the user or the failing resource): `PROJECT_ID`, `PROJECT_NUMBER`,
72
`CLUSTER`, cluster `LOCATION`, `NAMESPACE`, the **KSA** the Pod runs as, the
73
**node and node pool** the Pod is scheduled on (used in Step 2), the **target
74
resource / API** being called, and the **exact error string**. Define a time
75
window around the first observed failure for log queries.
76
77
```bash
78
# Resolve the project number (used in the direct-binding principal identifier).
79
gcloud projects describe "{PROJECT_ID}" --format="value(projectNumber)"
80
81
# Confirm which KSA the workload runs as.
82
kubectl get pod "{pod_name}" -n "{namespace}" \
83
-o jsonpath='{.spec.serviceAccountName}'
84
85
# Identify the node the Pod runs on, then the node pool that node belongs to
86
# (Step 2 checks the node pool's Workload Identity mode).
87
NODE=$(kubectl get pod "{pod_name}" -n "{namespace}" -o jsonpath='{.spec.nodeName}')
88
kubectl get node "$NODE" \
89
-o jsonpath='{.metadata.labels.cloud\.google\.com/gke-nodepool}'
90
```
91
92
--------------------------------------------------------------------------------
93
94
### Step 1: Capture the exact error signature
95
96
Read the workload's own logs and the `gke-metadata-server` logs to classify the
97
failure.
98
99
```bash
100
kubectl logs "{pod_name}" -n "{namespace}" --all-containers --prefix
101
kubectl describe pod "{pod_name}" -n "{namespace}"
102
```
103
104
Equivalent via Cloud Logging (preferred for historical events). Open it as a
105
**Logs Explorer deep link** — URL-encode the query and append the project and
106
time window:
107
`https://console.cloud.google.com/logs/query;query={URL_ENCODED_QUERY};timeRange={start}%2F{end}?project={project_id}`
108
(encode `/` as `%2F`, or use `;duration=PT1H` for a rolling hour):
109
110
```
111
resource.type="k8s_container"
112
resource.labels.namespace_name="{namespace}"
113
resource.labels.pod_name="{pod_name}"
114
severity>=WARNING
115
```
116
117
**Classify the signature:**
118
119
- `iam.serviceAccounts.getAccessToken` denied / `HTTP/403` → the workload is
120
using the **GSA impersonation** path. This is expected for the legacy setup,
121
but if you intend to use **direct binding**, it means the KSA still carries
122
a leftover `iam.gke.io/gcp-service-account` annotation (or the client SDK is
123
configured to impersonate) and is unintentionally impersonating a GSA; go to
124
Step 3.
125
- `403 PERMISSION_DENIED` on the **target API/resource** (no `getAccessToken`
126
in the error) → the resolved identity lacks the required IAM role on that
127
resource; go to Step 4.
128
- `could not find default credentials` / `cannot find the metadata server` →
129
metadata-server connectivity or a startup race; go to Step 5.
130
- Calls succeed but as the **node default service account** → Workload
131
Identity is not in effect for this node pool; go to Step 2.
132
133
--------------------------------------------------------------------------------
134
135
### Step 2: Verify Workload Identity is enabled (cluster + node pool)
136
137
Both the cluster and the **node pool the Pod runs on** must have Workload
138
Identity enabled. A node pool with `GCE_METADATA` (instead of `GKE_METADATA`)
139
causes Pods to fall back to the node's default Compute Engine service account.
140
141
```bash
142
# Cluster must have a workload identity pool (PROJECT_ID.svc.id.goog).
143
gcloud container clusters describe "{cluster}" --location "{location}" \
144
--format="value(workloadIdentityConfig.workloadPool)"
145
146
# Node pool must have workloadMetadataConfig.mode = GKE_METADATA.
147
gcloud container node-pools describe "{node_pool}" --cluster "{cluster}" \
148
--location "{location}" \
149
--format="value(config.workloadMetadataConfig.mode)"
150
```
151
152
- Empty workload pool → Workload Identity is **not enabled on the cluster**.
153
- Node-pool mode is `GCE_METADATA` (or empty) → the node pool is **not** using
154
the GKE metadata server; this is the usual cause of "runs as the node
155
default service account". Remediation: enable
156
`--workload-metadata=GKE_METADATA` on the node pool (propose to a human;
157
immediately affects running workloads and might disrupt workloads using the
158
node service account). This is a **node-pool configuration** problem — not a
159
KSA annotation or IAM binding problem — so do not change KSA annotations or
160
bindings to fix it. When the symptom is "runs as the node default service
161
account", say so explicitly: the root cause is the node pool's
162
`workloadMetadataConfig.mode`, and the KSA annotation and IAM bindings are
163
**ruled out** as the cause. Propose the exact fix, e.g.:
164
165
```bash
166
gcloud container node-pools update "{node_pool}" --cluster "{cluster}" \
167
--location "{location}" --workload-metadata=GKE_METADATA
168
```
169
170
--------------------------------------------------------------------------------
171
172
### Step 3: Verify the KSA → identity binding
173
174
There are two supported models. **Prefer direct binding** (current default);
175
treat GSA impersonation as the **legacy** path.
176
177
> **How the two models fail differently:** with **direct binding** the KSA
178
> principal accesses resources directly, so failures show up as a plain `403
179
> PERMISSION_DENIED` on the target API (fix in Step 4). A `403
180
> iam.serviceAccounts.getAccessToken` instead means an **impersonation** attempt
181
> — intended under the legacy path, or *unintended* if a leftover
182
> `iam.gke.io/gcp-service-account` annotation remains on a KSA that was meant to
183
> use direct binding.
184
185
**(a) Direct KSA binding (no GSA impersonation).** The KSA principal is granted
186
roles directly. Construct the principal identifier and search for its bindings:
187
188
```
189
principal://iam.googleapis.com/projects/{PROJECT_NUMBER}/locations/global/workloadIdentityPools/{PROJECT_ID}.svc.id.goog/subject/ns/{NAMESPACE}/sa/{KSA_NAME}
190
```
191
192
**(b) Legacy: KSA + GSA impersonation.** The KSA must be annotated to point at a
193
GSA, and the KSA must hold `roles/iam.workloadIdentityUser` on that GSA.
194
195
```bash
196
# The KSA annotation must reference the intended GSA.
197
kubectl get serviceaccount "{ksa_name}" -n "{namespace}" \
198
-o jsonpath='{.metadata.annotations.iam\.gke\.io/gcp-service-account}'
199
200
# The GSA's IAM policy must bind the KSA member to workloadIdentityUser.
201
gcloud iam service-accounts get-iam-policy \
202
"{gsa_name}@{project_id}.iam.gserviceaccount.com" \
203
--format=json
204
# Expect a binding: role roles/iam.workloadIdentityUser,
205
# member serviceAccount:{PROJECT_ID}.svc.id.goog[{NAMESPACE}/{KSA_NAME}]
206
```
207
208
> If the annotation is present but the binding is missing, the binding was
209
> likely removed — check the `setIamPolicy` audit logs around the failure time
210
> to find the responsible principal.
211
212
--------------------------------------------------------------------------------
213
214
### Step 4: Verify IAM permissions on the target resource
215
216
Even with a correct binding, the identity (the KSA principal for direct binding,
217
or the GSA for legacy) must hold the role required by the API call (for example
218
`roles/storage.objectViewer`). The standard IAM Policy Troubleshooter has
219
limited support for Workload Identity principals; use Cloud Asset Inventory to
220
search all IAM policies for the principal instead.
221
222
```bash
223
# Direct binding: search for the KSA principal's bindings across the project.
224
gcloud asset search-all-iam-policies \
225
--scope="projects/{PROJECT_ID}" \
226
--query='policy:"{PROJECT_ID}.svc.id.goog"'
227
228
# Legacy: search for the GSA's bindings on the target resource's project.
229
gcloud asset search-all-iam-policies \
230
--scope="projects/{TARGET_PROJECT_ID}" \
231
--query='policy:"{gsa_name}@{project_id}.iam.gserviceaccount.com"'
232
```
233
234
If no binding grants the required role on the target resource, **that missing
235
role is the root cause** (and Workload Identity itself is **not**
236
misconfigured). Present the fix as a **proposed change for a human to apply** —
237
the exact `add-iam-policy-binding` with the real principal and role — never
238
applying it automatically. For example, for direct binding on a project-level
239
resource:
240
241
```bash
242
gcloud projects add-iam-policy-binding "{TARGET_PROJECT_ID}" \
243
--member="principal://iam.googleapis.com/projects/{PROJECT_NUMBER}/locations/global/workloadIdentityPools/{PROJECT_ID}.svc.id.goog/subject/ns/{NAMESPACE}/sa/{KSA_NAME}" \
244
--role="{REQUIRED_ROLE}" # e.g. roles/storage.objectViewer
245
```
246
247
--------------------------------------------------------------------------------
248
249
### Step 5: GKE metadata server & connectivity
250
251
Applies when the signature is `could not find the metadata server`, `cannot find
252
the metadata server`, or a connection/timeout error. The `gke-metadata-server`
253
DaemonSet (in `kube-system`) brokers the token exchange on each node; requests
254
to `169.254.169.254` are redirected to it, so a Pod fails closed if it cannot
255
reach a healthy metadata-server Pod on its node.
256
257
**(a) Check gke-metadata-server Pod health on the workload's node.**
258
259
```bash
260
# The DaemonSet Pods must be healthy on the workload's node.
261
kubectl get pods -n kube-system -l k8s-app=gke-metadata-server -o wide
262
263
# A gke-metadata-server Pod can be OOM-evicted when the cluster has many
264
# (>3,000) Kubernetes service accounts. Look for CrashLoopBackOff, then confirm
265
# the eviction was OOMKilled.
266
kubectl get pods -n kube-system | grep CrashLoopBackOff
267
kubectl describe pod {gke_metadata_server_pod} --namespace=kube-system | grep OOMKilled
268
```
269
270
**(b) Inspect the `gke-metadata-server` logs** (historical, via Cloud Logging;
271
open as a Logs Explorer deep link, see Step 1):
272
273
```
274
resource.type="k8s_container"
275
resource.labels.namespace_name="kube-system"
276
labels."k8s-pod/k8s-app"="gke-metadata-server"
277
severity>=WARNING
278
```
279
280
**(c) Connectivity test** from the affected Pod — it must reach the metadata
281
server and (for some client libraries) resolve its DNS name:
282
283
```bash
284
# Token endpoint via the hardcoded metadata IP (a healthy path returns a token).
285
kubectl exec {pod_name} -n {namespace} -- \
286
curl -sS -H 'Metadata-Flavor: Google' \
287
'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token'
288
```
289
290
Possible causes:
291
292
- **Startup race**: the metadata server needs a few seconds after a Pod
293
starts. Applications that authenticate immediately may fail; the fix is
294
application-side retries or an `initContainer` that waits for the metadata
295
server, not a cluster change.
296
- **DNS**: some client libraries resolve `metadata.google.internal`; broken
297
in-cluster DNS surfaces as `cannot find the metadata server`. As a
298
workaround, set `GCE_METADATA_HOST=169.254.169.254` to skip DNS resolution.
299
- **Network policy / egress**: a cluster network policy must allow egress to
300
`169.254.169.254/32` on port `80` (GKE Dataplane V2), or
301
`169.254.169.252/32` on port `988`. A default-deny egress rule that blocks
302
HTTPS to the public Security Token Service (`sts.googleapis.com:443`)
303
produces `504 Gateway Timeout` or `context deadline exceeded`.
304
- **`gke-metadata-server` crashing / high restarts**: see (a) — reduce the
305
number of Kubernetes service accounts (<3,000) to restore functionality.
306
307
--------------------------------------------------------------------------------
308
309
### Step 6: "Invalid form of account ID" edge case (legacy GSA impersonation)
310
311
> **Applies only to the legacy GSA impersonation setup** (a KSA annotated with
312
> `iam.gke.io/gcp-service-account`), not to direct principal binding.
313
314
Signature: an operation that requires an IAM **service account email** (for
315
example, manually creating a Cloud Storage signed URL) fails with:
316
317
```
318
ERROR: Invalid form of account ID SERVICEACCOUNT_NAME.svc.id.goog.
319
Should be [Gaia ID | Email | Unique ID | ] of the account
320
```
321
322
Cause: for a KSA linked to a GSA via annotation, the GKE metadata server by
323
default returns `SERVICEACCOUNT_NAME.svc.id.goog` as the identifier, which is
324
not a valid IAM service account email. This is **not** a missing IAM binding and
325
does **not** require reverting the setup.
326
327
Fix (propose to a human): add the
328
`iam.gke.io/return-principal-id-as-email="true"` annotation to the Pod's KSA so
329
the metadata server returns the identity in the expected form:
330
331
```bash
332
kubectl annotate serviceaccount "{ksa_name}" --namespace "{namespace}" \
333
iam.gke.io/return-principal-id-as-email="true"
334
```
335
336
--------------------------------------------------------------------------------
337
338
### Step 7: Remediation boundary & escalation
339
340
- Present the **root cause + evidence** (the exact error, the missing binding
341
/ annotation / node-pool mode, or the metadata-server state). Include a
342
**Cloud Logging deep link** (see Step 1) to the supporting entries.
343
- Propose the fix as a **command or GitOps manifest change** for a human to
344
apply — never modify IAM, KSAs, or node pools automatically.
345
346
**Escalate** (instead of proposing more self-service diagnostics) when either:
347
348
- the relevant logs are **unavailable** (excluded by a filter, or past the log
349
bucket's retention); or
350
- the identity/binding is correct, the target-resource IAM is correct, and the
351
metadata server is healthy, yet the failure persists (undetermined root
352
cause).
353
354
In those cases: state the limitation plainly, summarize the findings gathered
355
(cluster/node-pool config, bindings, annotations, metadata-server state, and any
356
`setIamPolicy` audit logs), and route to GKE support / engineering escalation.
357
Do **not** fabricate a diagnosis when evidence is missing.
358
359
--------------------------------------------------------------------------------
360
361
## References
362
363
This skill is derived from public Google Cloud documentation:
364
365
- [Troubleshoot GKE authentication issues](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/authentication.md.txt)
366
— the Workload Identity Federation section: WI-enabled check, KSA
367
annotation, `roles/iam.workloadIdentityUser`,
368
`iam.serviceAccounts.getAccessToken` 403,
369
`iam.gke.io/return-principal-id-as-email`, metadata-server DNS and the
370
[`gke-metadata-server` Pod is crashing](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/authentication.md.txt#metadata-server-crashes)
371
guidance.
372
- [About Workload Identity Federation for GKE](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/workload-identity.md.txt)
373
— identities, the GKE metadata server, and why Pods don't inherit the node
374
identity.
375
- [Configure applications to use Workload Identity Federation for GKE](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/workload-identity.md.txt)
376
— node-pool `--workload-metadata=GKE_METADATA`, the direct-binding
377
`principal://...` identifier, and the legacy
378
`serviceAccount:PROJECT_ID.svc.id.goog[NAMESPACE/KSA_NAME]` member format.
379
- [Search IAM policies (Cloud Asset Inventory)](https://docs.cloud.google.com/asset-inventory/docs/search-allow-policies)
380
— `gcloud asset search-all-iam-policies` for auditing a principal's
381
bindings.
382
- [View GKE logs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt)
383
— Cloud Logging queries for workload and system logs.
384

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…