Run commands impersonating another user or ServiceAccount

kubernetes impersonate user group serviceaccount

2 min read | by Jordi Prats

To be able to test permissions it can be convenient to have our own user being able to impersonate other users (and ServiceAccounts as well). To do we we'll have to use the impersonate verb as follows:

- apiGroups: [""]
  resources: ["users", "groups", "serviceaccounts"]
  verbs: ["impersonate"]

Once we have it in place, we'll be able to run commands as other users with the --as and --as-group options

Impersonate a ServiceAccount

This can be the most common usage; being able to test the permissions we grant to a ServiceAccount, to do so we'll have to specify it using the following format:


So, the kubectl command would look like follows for a ServiceAccount named test-service-account in the pet2cattle namespace:

$ kubectl --as system:serviceaccount:pet2cattle:test-service-account ...

Impersonate a given user (with a specific group)

To be able to test the permissions a given user (belonging to a specific group) we'll have to combine the --as option for setting the user, with --as-group to specify the group:

$ kubectl --as demo-user --as-group demo-group ...

Posted on 22/11/2022