Skip to content

Configuration

lightkube.config.kubeconfig.KubeConfig(*, clusters: Dict[str, Cluster], contexts: Dict[str, Context], users: Optional[Dict[str, User]] = None, current_context: Optional[str] = None, fname: Optional[StrOrPath] = None)

Class to represent a kubeconfig. See the specific constructors depending on your use case.

Attributes:

  • clusters (Dict[str, Cluster]) –

    Dictionary of cluster name -> Cluster instance.

  • contexts (Dict[str, Context]) –

    Dictionary of context name -> Context instance.

  • users (Dict[str, User]) –

    Dictionary of user name -> User instance.

Create the kubernetes configuration manually. Normally this constructor should not be called directly. Use a specific constructor instead.

Attributes:

  • clusters

    Dictionary of cluster name -> Cluster instance.

  • contexts

    Dictionary of context name -> Context instance.

  • users

    Dictionary of user name -> User instance.

  • current_context

    Name of the current context.

  • fname

    Name of the file where the configuration has been readed from.

Source code in src/lightkube/config/kubeconfig.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def __init__(
    self,
    *,
    clusters: Dict[str, Cluster],
    contexts: Dict[str, Context],
    users: Optional[Dict[str, User]] = None,
    current_context: Optional[str] = None,
    fname: Optional[StrOrPath] = None,
) -> None:
    """
    Create the kubernetes configuration manually. Normally this constructor should not be called directly.
    Use a specific constructor instead.

    Attributes:
      clusters: Dictionary of cluster name -> `Cluster` instance.
      contexts: Dictionary of context name -> `Context` instance.
      users: Dictionary of user name -> `User` instance.
      current_context: Name of the current context.
      fname: Name of the file where the configuration has been readed from.
    """
    self.current_context = current_context
    self.clusters = clusters
    self.contexts = contexts
    self.users = users or {}
    self.fname = Path(fname) if fname else None

clusters: Dict[str, Cluster] = clusters instance-attribute

contexts: Dict[str, Context] = contexts instance-attribute

current_context = current_context instance-attribute

fname = Path(fname) if fname else None instance-attribute

users: Dict[str, User] = users or {} instance-attribute

from_dict(conf: Dict, fname: Optional[StrOrPath] = None) -> KubeConfig classmethod

Creates a KubeConfig instance from the content of a dictionary structure.

Parameters

  • conf: Configuration structure, main attributes are clusters, contexts, users and current-context.
  • fname: File path from where this configuration has been loaded. This is needed to resolve relative paths present inside the configuration.
Source code in src/lightkube/config/kubeconfig.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@classmethod
def from_dict(cls, conf: Dict, fname: Optional[StrOrPath] = None) -> "KubeConfig":
    """Creates a KubeConfig instance from the content of a dictionary structure.

    **Parameters**

    * **conf**: Configuration structure, main attributes are `clusters`, `contexts`, `users` and `current-context`.
    * **fname**: File path from where this configuration has been loaded. This is needed to resolve relative paths
      present inside the configuration.
    """
    return cls(
        current_context=conf.get("current-context"),
        clusters=to_mapping(conf["clusters"], "cluster", factory=Cluster),
        contexts=to_mapping(conf["contexts"], "context", factory=Context),
        users=to_mapping(conf.get("users", []), "user", factory=User),
        fname=fname,
    )

from_env(service_account: StrOrPath = SERVICE_ACCOUNT, default_config: StrOrPath = DEFAULT_KUBECONFIG) -> KubeConfig classmethod

Attempts to load the configuration automatically looking at the environment and filesystem.

The method will attempt to load a configuration using the following order:

  • in-cluster config.
  • config file defined in KUBECONFIG environment variable.
  • configuration file present on the default location.

Parameters

  • service_account: Allows to override the default service account directory path. Default /var/run/secrets/kubernetes.io/serviceaccount.
  • default_config: Allows to override the default configuration location. Default ~/.kube/config.
Source code in src/lightkube/config/kubeconfig.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
@classmethod
def from_env(
    cls,
    service_account: StrOrPath = SERVICE_ACCOUNT,
    default_config: StrOrPath = DEFAULT_KUBECONFIG,
) -> "KubeConfig":
    """Attempts to load the configuration automatically looking at the environment and filesystem.

    The method will attempt to load a configuration using the following order:

    * in-cluster config.
    * config file defined in `KUBECONFIG` environment variable.
    * configuration file present on the default location.

    **Parameters**

    * **service_account**: Allows to override the default service account directory path.
      Default `/var/run/secrets/kubernetes.io/serviceaccount`.
    * **default_config**: Allows to override the default configuration location. Default `~/.kube/config`.
    """
    try:
        return KubeConfig.from_service_account(service_account=service_account)
    except exceptions.ConfigError:
        return KubeConfig.from_file(os.environ.get("KUBECONFIG", default_config))

from_file(fname: StrOrPath) -> KubeConfig classmethod

Creates an instance of the KubeConfig class from a kubeconfig file in YAML format.

Parameters

  • fname: Path to the kuberneted configuration.
Source code in src/lightkube/config/kubeconfig.py
164
165
166
167
168
169
170
171
172
173
174
175
176
@classmethod
def from_file(cls, fname: StrOrPath) -> "KubeConfig":
    """Creates an instance of the KubeConfig class from a kubeconfig file in YAML format.

    **Parameters**

     * **fname**: Path to the kuberneted configuration.
    """
    filepath = Path(fname).expanduser()
    if not filepath.is_file():
        raise exceptions.ConfigError(f"Configuration file {fname} not found")
    with filepath.open() as f:
        return cls.from_dict(yaml.safe_load(f.read()), fname=filepath)

from_one(*, cluster: Cluster, user: Optional[User] = None, context_name: str = 'default', namespace: Optional[str] = None, fname: Optional[StrOrPath] = None) -> KubeConfig classmethod

Creates an instance of the KubeConfig class from one cluster and one user configuration

Source code in src/lightkube/config/kubeconfig.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@classmethod
def from_one(
    cls,
    *,
    cluster: Cluster,
    user: Optional[User] = None,
    context_name: str = "default",
    namespace: Optional[str] = None,
    fname: Optional[StrOrPath] = None,
) -> "KubeConfig":
    """Creates an instance of the KubeConfig class from one cluster and one user configuration"""
    context = Context(
        cluster=context_name,
        user=context_name if user else None,
        namespace=namespace,
    )
    return cls(
        clusters={context_name: cluster},
        contexts={context_name: context},
        users={context_name: user} if user else None,
        current_context=context_name,
        fname=fname,
    )

from_server(url: str, namespace: Optional[str] = None) -> KubeConfig classmethod

Creates an instance of the KubeConfig class from the cluster server url

Source code in src/lightkube/config/kubeconfig.py
202
203
204
205
@classmethod
def from_server(cls, url: str, namespace: Optional[str] = None) -> "KubeConfig":
    """Creates an instance of the KubeConfig class from the cluster server url"""
    return cls.from_one(cluster=Cluster(server=url), namespace=namespace)

from_service_account(service_account: StrOrPath = SERVICE_ACCOUNT) -> KubeConfig classmethod

Creates a configuration from in-cluster service account information.

Parameters

  • service_account: Allows to override the default service account directory path. Default /var/run/secrets/kubernetes.io/serviceaccount.
Source code in src/lightkube/config/kubeconfig.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
@classmethod
def from_service_account(cls, service_account: StrOrPath = SERVICE_ACCOUNT) -> "KubeConfig":
    """Creates a configuration from in-cluster service account information.

    **Parameters**

     * **service_account**: Allows to override the default service account directory path.
       Default `/var/run/secrets/kubernetes.io/serviceaccount`.
    """
    account_dir = Path(service_account)

    token_file = str(account_dir.joinpath("token"))

    try:
        token = Path(token_file).read_text()
        namespace = account_dir.joinpath("namespace").read_text()
    except FileNotFoundError as e:
        raise exceptions.ConfigError(str(e)) from e

    host = os.environ["KUBERNETES_SERVICE_HOST"]
    port = os.environ["KUBERNETES_SERVICE_PORT"]
    if ":" in host:  # ipv6
        host = f"[{host}]"
    return cls.from_one(
        cluster=Cluster(
            server=f"https://{host}:{port}",
            certificate_auth=str(account_dir.joinpath("ca.crt")),
        ),
        user=User(token=token, token_file=token_file),
        namespace=namespace,
    )

get(context_name: Optional[str] = None, default: Optional[SingleConfig] = None) -> Optional[SingleConfig]

Returns a SingleConfig instance, representing the configuration matching the given context_name. Lightkube client will automatically call this method without parameters when an instance of KubeConfig is provided.

Parameters

  • context_name: Name of the context to use. If context_name is undefined, the current-context is used. In the case both contexts are undefined, and the default is provided, this method will return the default. It will fail with an error otherwise.
  • default: Instance of a SingleConfig to be returned in case both contexts are not set. When this parameter is not provided and no context is defined, the method call will fail.
Source code in src/lightkube/config/kubeconfig.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def get(self, context_name: Optional[str] = None, default: Optional[SingleConfig] = None) -> Optional[SingleConfig]:
    """Returns a `SingleConfig` instance, representing the configuration matching the given `context_name`.
    Lightkube client will automatically call this method without parameters when an instance of `KubeConfig`
    is provided.

    **Parameters**

    * **context_name**: Name of the context to use. If `context_name` is undefined, the `current-context` is used.
      In the case both contexts are undefined, and the default is provided, this method will return the default.
      It will fail with an error otherwise.
    * **default**: Instance of a `SingleConfig` to be returned in case both contexts are not set. When this
      parameter is not provided and no context is defined, the method call will fail.
    """
    if context_name is None:
        context_name = self.current_context
    if context_name is None:
        if default is None:
            raise exceptions.ConfigError("No current context set and no default provided")
        return default
    try:
        ctx = self.contexts[context_name]
    except KeyError as err:
        raise exceptions.ConfigError(f"Context '{context_name}' not found") from err
    return SingleConfig(
        context_name=context_name,
        context=ctx,
        cluster=self.clusters[ctx.cluster],
        user=self.users[ctx.user] if ctx.user else None,
        fname=self.fname,
    )

lightkube.config.kubeconfig.SingleConfig

Bases: NamedTuple

Represents a single configuration instance as the result of selecting a context

cluster: Cluster instance-attribute

context: Context instance-attribute

context_name: str instance-attribute

fname: Optional[Path] = None class-attribute instance-attribute

namespace: str property

Returns the namespace in the current context

user: Optional[User] = None class-attribute instance-attribute

abs_file(fname: StrOrPath) -> StrOrPath

Return the absolute path of a relative file path, relatively to the configuration file

Source code in src/lightkube/config/kubeconfig.py
58
59
60
61
62
63
64
65
66
def abs_file(self, fname: StrOrPath) -> StrOrPath:
    """Return the absolute path of a relative file path, relatively to the configuration file"""
    if Path(fname).is_absolute():
        return fname

    if self.fname is None:
        raise exceptions.ConfigError(f"{fname} is relative, but kubeconfig path unknown")

    return self.fname.parent.joinpath(fname)

lightkube.config.kubeconfig.Cluster(server: str = 'http://localhost:8080', certificate_auth: Optional[str] = None, certificate_auth_data: Optional[str] = None, insecure: bool = False) dataclass

Bases: DataclassDictMixIn

Attributes:

  • server (str) –

    the server name

certificate_auth: Optional[str] = field(metadata={'json': 'certificate-authority'}, default=None) class-attribute instance-attribute

certificate_auth_data: Optional[str] = field(metadata={'json': 'certificate-authority-data'}, default=None) class-attribute instance-attribute

insecure: bool = field(metadata={'json': 'insecure-skip-tls-verify'}, default=False) class-attribute instance-attribute

server: str = 'http://localhost:8080' class-attribute instance-attribute