kubeconfig

kubeconfig is a simple Python module for manipulating Kubernetes kubeconfig files.

from kubeconfig import KubeConfig

conf = KubeConfig()
conf.set_context('new-context', cluster='other-cluster', user='my-user')
conf.use_context('new-context')
print(conf.view())

Example usage cases

  • Generating configs for users
  • Tooling that manages switching between multiple clusters or users
  • Cycling credentials out in a config
  • Updating CA cert entries in your config

How it works

Rather than re-implement and maintain the kubeconfig detection, selection, and merging logic found in kubectl, this module calls on kubectl to do the config reading and writing.

This does make kubectl a hard dependency for this module, but also ensures behavior that is consistent with what you’d expect by using kubectl directly.

Getting started

For some quick examples of how to use kubeconfig, see Quickstart.

Installing kubeconfig

Prerequesites

Warning

This module currently requires Python 3.5 or greater. While we will likely make changes to knock this back to 3.4, there is no desire to add or maintain Python 2 compatibility.

Installation

The recommended installation method is through pip:

pip install kubeconfig

If you’d like to install directly from source:

git clone git@github.com:gtaylor/kubeconfig-python.git
cd kubeconfig-python
python setup.py install

Once you are set up, see the Quickstart for first steps.

Quickstart

After Installing kubeconfig, you are ready to start working with your configs.

Reading your Config

We’ll start by reading your current configs, with the result being returned as a dict:

from kubeconfig import KubeConfig

conf = KubeConfig()
print(conf.view())

Since we’re just calling kubectl under the covers, your KUBECONFIG environment variable will be referenced, and all kubeconfig merging rules will apply.

If you want to read a specific kubeconfig, you can pass that in as well:

conf = KubeConfig('path-to-your-config')

Creating or modifying credentials

Use KubeConfig.set_credentials to create or modify credentials:

from kubeconfig import KubeConfig

conf = KubeConfig()
kc.set_credentials(name='my-user, token='super-secret-token')

Creating or modifying a cluster

Use KubeConfig.set_cluster to create or modify clusters:

from kubeconfig import KubeConfig

conf = KubeConfig()
kc.set_cluster(
    name='my-cluster,
    server='https://my-k8s-api-server.xxx/'
    certificate_authority='/path/to/ca.crt',
)

Creating or modifying a context

Use KubeConfig.set_cluster to create or modify contexts:

from kubeconfig import KubeConfig

conf = KubeConfig()
kc.set_context(
    name='my-context,
    cluster='my-cluster'
    user='my-user',
)

Changing your current context

If you’d like to switch to another context in your config file, this is done via KubeConfig.use_context:

from kubeconfig import KubeConfig

conf = KubeConfig()
conf_doc = conf.view()
print('Current context:', conf.current_context())
conf.use_context('new-context')
# Re-read the config.
conf_doc = conf.view()
print('Current context:', conf.current_context())

kubeconfig

View or manipulate your kubeconfig file.

For example:

import kubeconfig

# We'll use kubectl's default kubeconfig resolution heuristics.
conf = kubeconfig.KubeConfig()
# See the full, merged contents of your effective kubeconfig.
print(conf.view())
# Change your default context.
conf.use_context('another-context')
# Check to see our changes.
print(conf.view())
class kubeconfig.KubeConfig(path=None)

This is the top-level class for manipulating your kubeconfig file. You may view or make changes using the exposed methods. Changes take effect immediately.

Note

All values read from your config file(s) will be decoded to Python strings. This happens as a result of our parsing the YAML.

Parameters:path (str) – If you’d like to work against a specific kubeconfig file instead of using your currently configured (or default), pass the full path in.
current_context()
Return type:str or None
Returns:Your config’s currently selected context (current-context), or None if not set.
delete_cluster(name)

Deletes a cluster entry from your config.

Parameters:name (str) – The name of the cluster to delete from your config.
Raise:KubectlCommandError when an invalid cluster name is specified.
delete_context(name)

Deletes a context entry from your config.

Parameters:name (str) – The name of the context to delete from your config.
Raise:KubectlCommandError when an invalid context name is specified.
rename_context(old_name, new_name)

Changes the name of a context in your config.

Parameters:
  • old_name (str) – The name of the context to rename.
  • new_name (str) – The desired new name for the context.
Raise:

KubectlCommandError when an invalid context name is specified for old or new.

set(name, value)

Sets an individual value in your config.

Parameters:
  • name (str) – The dot delimited name of the key to set.
  • value – The value to set on the key.
Raise:

KubectlCommandError when an invalid name is specified.

set_cluster(name, certificate_authority=None, embed_certs=None, insecure_skip_tls_verify=None, server=None)

Creates or updates a cluster entry in your config. In the case where you are updating an existing cluster, only the optional keyword args that you pass in will be updated on the entry.

Parameters:
  • name (str) – The name of the cluster to modify.
  • certificate_authority (str) – Path to a certificate authority file for verifying the certs on the cluster’s API server.
  • embed_certs (bool) – Combined with certificate_authority, setting this to True will cause the CA cert to be embedded directly in the written config. If False or unspecified, the path to the CA cert will be used instead.
  • insecure_skip_tls_verify (bool) – If True, we won’t do cert validation against the cluster’s API server.
  • server (str) – Full URI to the cluster’s API server.
set_context(name, cluster=None, namespace=None, user=None)

Creates or updates a context entry in your config. In the case where you are updating an existing context, only the optional keyword args that you pass in will be updated on the entry.

Parameters:
  • name (str) – The name of the context to modify.
  • cluster (str) – Determines the context’s cluster.
  • namespace (str) – Sets the default namespace for the context.
  • user (str) – The user to authenticate as for the context.
set_credentials(name, auth_provider=None, auth_provider_args=None, client_certificate=None, client_key=None, embed_certs=None, password=None, token=None, username=None)

Creates or updates a user entry under the users entry. In the case where you are updating an existing user, only the optional keyword args that you pass in will be updated on the entry.

Parameters:
  • name (str) – The name of the user to add or update.
  • auth_provider (str) – The auth provider name to use. For example, oidc, gcp, etc.
  • auth_provider_args (dict) – Some providers support extra config params, which can be passed in as a flat dict.
  • client_certificate (str) – Path to your X.509 client cert (if using cert auth).
  • client_key (str) – Path to your cert’s private key (if using cert auth).
  • embed_certs (bool) – Combined with client_certificate, setting this to True will cause the cert to be embedded directly in the written config. If False or unspecified, the path to the cert will be used instead.
  • username (str) – Your username (if using basic auth).
  • password (str) – Your user’s password (if using basic auth).
  • token (str) – Your private token (if using token auth).
unset(name)

Unsets an individual value in your kubeconfig file.

Parameters:name (str) – The dot delimited name of the key to unset.
Raise:KubectlCommandError when an invalid name is specified.
use_context(name)

Changes your default/active context.

Parameters:name (str) – The context to set as current.
Raise:KubectlCommandError when an invalid context name is specified.
view()
Return type:dict
Returns:A dict representing your full kubeconfig file, after all merging has been done.

kubeconfig.exceptions

exception kubeconfig.exceptions.KubeConfigError

Top-level base class for all module exceptions.

exception kubeconfig.exceptions.KubectlNotFoundError

Raised when the Kubectl executable is not found on the path.

exception kubeconfig.exceptions.KubectlCommandError(message)

Raised when kubectl exit(1)’s or returns an error line.