Authenticate Kubectl using Google IAM service account

2/21/2019

I have got a Google Cloud IAM service account key file (in json format) that contains below data.

{
"type": "service_account",
"project_id": "****",
"private_key_id":"****",
"private_key": "-----BEGIN PRIVATE KEY----blah blah -----END PRIVATE KEY-----\n",
"client_email": "*****",
"client_id": "****",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth/v1/certs",
"client_x509_cert_url": "****"
}

I can use this service account to access kubernetes API server by passing this key file to kube API client libraries.

But, I'm not finding any way to pass this service account to kubectl binary to have kubectl get authenticated to project for which this service account created for.

Is there any way that I can use to make Kubectl to use this service account file for authentication ?

-- bms
google-compute-engine
google-iam
google-kubernetes-engine
kubectl
kubernetes

1 Answer

2/21/2019

This answer provides some guidance: Access Kubernetes GKE cluster outside of GKE cluster with client-go? but it's not complete.

You need to do two things:

  1. set GOOGLE_APPLICATION_CREDENTIALS environment variable to path to your JSON key file for the IAM service account, and use kubectl while this variable is set, you should be authenticated with the token.

  2. (this may be optional, not sure) Create a custom KUBECONFIG that only contains your cluster IP and CA certificate, save this file, and use it to connect to the cluster.

Step 2 looks like this:

cat > kubeconfig.yaml <<EOF
apiVersion: v1
kind: Config
current-context: cluster-1
contexts: [{name: cluster-1, context: {cluster: cluster-1, user: user-1}}]
users: [{name: user-1, user: {auth-provider: {name: gcp}}}]
clusters:
- name: cluster-1
  cluster:
    server: "https://$(eval "$GET_CMD --format='value(endpoint)'")"
    certificate-authority-data: "$(eval "$GET_CMD --format='value(masterAuth.clusterCaCertificate)'")"
EOF

So with this, you should do

export GOOGLE_APPLICATION_CREDENTIALS=<path-to-key.json>
export KUBECONFIG=kubeconfig.yaml
kubectl get nodes
-- AhmetB - Google
Source: StackOverflow