Stop Downloading Google Cloud Service Account Keys!

Service Accounts, OAuth2 and You

You should never need to generate and download a service account key to use a service account within Google Cloud infrastructure.

Short lived tokens FTW!

gcloud --impersonate-service-account=k8s@project.iam.gserviceaccount.com container clusters get-credentials my-cluster
WARNING: This command is using service account impersonation. All API calls will be executed as [k8s@project.iam.gserviceaccount.com]
gcloud config set auth/impersonate_service_account \
k8s@project.iam.gserviceaccount.com
gcloud container clusters get-credentials my-cluster
# Other gcloud commands :)
#!/bin/bashIMPERSONATE='gcloud config set auth/impersonate_service_account'impersonate() {
sa=$1
echo "Impersonating $sa"
$IMPERSONATE $sa
}
case $1 in
gke)
impersonate k8s@project.iam.gserviceaccount.com
;;
admin)
impersonate admin@other-project.iam.gserviceaccount.com
;;
clear)
gcloud config unset auth/impersonate_service_account
;;
*)
echo "Usage: Updates impersonated service account"
echo " gsa [gke|admin|clear]"
esac
$ gsa gke
Impersonating k8s@project.iam.gserviceaccount.com
Updated property [auth/impersonate_service_account].

$ gsa clear
Unset property [auth/impersonate_service_account].

What about Terraform?

export GOOGLE_OAUTH_ACCESS_TOKEN=$(gcloud auth print-access-token)
terraform apply
Example Makefile supporting impersonation with Terraform

Attribution and Logging

{
"principalEmail": "k8s@project.iam.gserviceaccount.com",
"serviceAccountDelegationInfo": [
{
"firstPartyPrincipal": {
"principalEmail": "ryan@example.com"
}
}
]
}
protoPayload.authenticationInfo.serviceAccountDelegationInfo.0.firstPartyPrincipal.principalEmail="ryan@example.com"
authenticationInfo: {
principalEmail: "k8s@project.iam.gserviceaccount.com"
serviceAccountKeyName: "//iam.googleapis.com/projects/project/serviceAccounts/k8s@project.iam.gserviceaccount.com/keys/caed69e352ae12ab17e1962de5bac31062495876"
}

Caveats

Next Steps

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store