Applying a GCP service account to a local Kubernetes cluster involves a few steps to ensure that your Kubernetes pods can authenticate to GCP services using the service account. Here's a detailed guide to achieve this:
Step-by-Step Guide
1. Create a GCP Service Account
First, create a service account in your GCP project and download the JSON key file.
-
Create the Service Account:
gcloud iam service-accounts create my-service-account --display-name "My Service Account"
-
Assign Roles to the Service Account:
gcloud projects add-iam-policy-binding <YOUR-PROJECT-ID> \ --member="serviceAccount:my-service-account@<YOUR-PROJECT-ID>.iam.gserviceaccount.com" \ --role="roles/YOUR-ROLE"
Replace
<YOUR-PROJECT-ID>
with your GCP project ID androles/YOUR-ROLE
with the appropriate roles you need for your service account. -
Create and Download the Key File:
gcloud iam service-accounts keys create key.json \ --iam-account my-service-account@<YOUR-PROJECT-ID>.iam.gserviceaccount.com
2. Create a Kubernetes Secret with the Service Account Key
Next, create a Kubernetes secret that contains the service account key file.
-
Create the Secret:
kubectl create secret generic gcp-service-account \ --from-file=key.json=path/to/key.json
Replace
path/to/key.json
with the actual path to your downloaded service account key file.
3. Configure Your Pods to Use the Service Account
Modify your Kubernetes deployment or pod specification to mount the service account key as a volume and set the GOOGLE_APPLICATION_CREDENTIALS
environment variable.
-
Update Deployment YAML:
apiVersion: apps/v1 kind: Deployment metadata: name: my-app spec: replicas: 1 selector: matchLabels: app: my-app template: metadata: labels: app: my-app spec: containers: - name: my-app image: gcr.io/<YOUR-PROJECT-ID>/my-app:latest ### Keypoint Start env: - name: GOOGLE_APPLICATION_CREDENTIALS value: /var/secrets/google/key.json volumeMounts: - name: gcp-service-account mountPath: /var/secrets/google readOnly: true volumes: - name: gcp-service-account secret: secretName: gcp-service-account ### Keypoint End
In this example:
- Replace
gcr.io/<YOUR-PROJECT-ID>/my-app:latest
with the image you are using. - The environment variable
GOOGLE_APPLICATION_CREDENTIALS
is set to the path where the key file will be mounted. - The secret named
gcp-service-account
is mounted as a volume at/var/secrets/google
.
- Replace
-
Apply the Updated Deployment:
kubectl apply -f deployment.yaml
Summary
By following these steps, you can configure your local Kubernetes cluster to use a GCP service account. This setup involves creating a GCP service account, generating and downloading a key file, creating a Kubernetes secret with the key file, and configuring your pods to use the service account by mounting the secret and setting the appropriate environment variable. This allows your applications running in Kubernetes to authenticate with GCP services securely.
Top comments (0)