gke - how to create a federated service account for your cluster - using gke to access gcp resources

 First we need to goto service account to create a service account called gke-ai-sa by going here. In this blog, we just going to cover gke autopilot and made the assumption that you're using GKE with WIP enabled. 

Then we provide a name, lets called it gke-ai-sa.




Click "create and continThen we setup some roles 

Click "Done".

Next, we goto our cluster and create a namespace 

kubectl create namespace gke-ai-namespace

and then create a service account 

kubectl create serviceaccount gpu-k8s-sa --namespace=gke-ai-namespace

And finally the federation process

gcloud iam service-accounts add-iam-policy-binding gke-ai-sa@PROJECT_ID.iam.gserviceaccount.com --role roles/iam.workloadIdentityUser --member "serviceAccount:PROJECT_ID.svc.id.goog[gke-ai-namespace/gpu-k8s-sa]"

And annotate it

kubectl annotate serviceaccount gpu-k8s-sa --namespace gke-ai-namespace iam.gke.io/gcp-service-account=gke-ai-sa@PROJECT_ID.iam.gserviceaccount.com


gcloud projects add-iam-policy-binding projectId --member="serviceAccount:gke-ai-sa@project-id.iam.gserviceaccount.com" --role="roles/storage.bucketViewer"

You can find more roles: here https://cloud.google.com/storage/docs/access-control/iam-roles

We can test this out by impersonating the service account. So here we will impersonate gke-ai-sa 

gcloud iam service-accounts add-iam-policy-binding \
  projects/PROJECT_ID/serviceAccounts/gke-ai-sa@project-id.iam.gserviceaccount.com\
  --member="user:you@example.com" \
  --role="roles/iam.serviceAccountTokenCreator"

And to see if the service account can list buckets in gcloud, we can run the following commands 

gcloud storage buckets list --impersonate-service-account=gke-ai-sa@project-id.iam.gserviceaccount.com


Next, we will create a pod 


apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: NAMESPACE
spec:
  serviceAccountName: KSA_NAME
  containers:
  - name: test-pod
    image: google/cloud-sdk:slim
    command: ["sleep","infinity"]
    resources:
      requests:
        cpu: 500m
        memory: 512Mi
        ephemeral-storage: 10Mi

And once the pod is up and running, then we can 

kubectl exec -it pods/test-pod --namespace=NAMESPACE -- /bin/bash

Once the pod is running then we can use curl command to test out our pod to ensure our service account has been successfully federated.

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \

    "https://storage.googleapis.com/storage/v1/b/BUCKET/o"


Additional references

https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#authenticating_to




    




Comments

Popular posts from this blog

gemini cli getting file not defined error

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

vllm : Failed to infer device type