How to configure expiry (TTL) on kubeconfig tokens in Rancher
Article Number: 000020021
Situation
Task
In Rancher it is possible to configure an expiry (TTL) on Rancher-generated kubeconfig tokens for Rancher managed Kubernetes clusters. This article details how to configure kubeconfig token expiry as a Rancher administrator and how users can authenticate via kubectl when this is configured.
Pre-requisites
- A Rancher v2.x instance
- The
kubectlbinary andRancher CLIinstalled locally
Resolution
Disable automatic kubeconfig token generation and configure TTL
As a Rancher global admin, disable automatic kubeconfig token generation and configure the expiry time (TTL) for kubeconfig tokens, per the steps in the Rancher documentation here .
Authenticating via the Rancher CLI with kubectl
Once an admin has configured the kubeconfig TTL, users will need to download the Rancher CLI to authenticate against Rancher when using Rancher-generated kubeconfig files to connect to Rancher-managed clusters.
- Download the required Rancher CLI binary per the Rancher documentation .
- Ensure the
rancherCLI binary is executable and in your PATH. - Download a copy of the kubeconfig file for a cluster from the Rancher UI and add it to the default ~/.kube/config file or source it with
KUBECONFIG=/path/to/file. - Execute
kubectl get nodesand observe you will be prompted for your Rancher username and password. If you are using an authentication provider you will also be prompted to select this versus local authentication. You can prevent this prompt by adding the--auth-provider=<provider>argument in the kubeconfig file, per the following example:
args:
- token
- --auth-provider=openLdapProvider
- --server=rancher.example.com
kubeconfig-token-ttl-minutes) configured in Rancher.
6. You can verify the configured expiry time of the kubeconfig token within the Rancher UI, under API & Keys.
7. Once the token expires, you will be prompted to log in again upon executing kubectl commands against the cluster, per step 4.
N.B. By default the generated kubeconfig token is cached within the directory
.cachein the working directory from which you invokekubectl, when you are prompted to log in. As a result executingkubectlfrom a different directory, will re-prompt for authentication and generate a fresh token cache under.cache. To prevent this behavior, you can set the token cache location with the environment variableRANCHER_CONFIG_DIR, e.g.export RANCHER_CONFIG_DIR=~/.rancherto avoid being prompted for authentication when you change the working directory.