def network_kubernetes_from_context( reactor, context=None, path=None, environ=None, default_config_path=FilePath(expanduser(u"~/.kube/config")), ): """ Create a new ``IKubernetes`` provider based on a kube config file. :param reactor: A Twisted reactor which will be used for I/O and scheduling. :param unicode context: The name of the kube config context from which to load configuration details. Or, ``None`` to respect the current context setting from the configuration. :param FilePath path: The location of the kube config file to use. :param dict environ: A environment direction in which to look up ``KUBECONFIG``. If ``None``, the real process environment will be inspected. This is used only if ``path`` is ``None``. :return IKubernetes: The Kubernetes service described by the named context. """ if path is None: if environ is None: from os import environ try: kubeconfigs = environ[u"KUBECONFIG"] except KeyError: config = KubeConfig.from_file(default_config_path.path) else: config = _merge_configs_from_env(kubeconfigs) else: config = KubeConfig.from_file(path.path) if context is None: context = config.doc[u"current-context"] context = config.contexts[context] cluster = config.clusters[context[u"cluster"]] user = config.users[context[u"user"]] if isinstance(cluster[u"server"], bytes): base_url = URL.fromText(cluster[u"server"].decode("ascii")) else: base_url = URL.fromText(cluster[u"server"]) [ca_cert] = parse(cluster[u"certificate-authority"].bytes()) client_chain = parse(user[u"client-certificate"].bytes()) [client_key] = parse(user[u"client-key"].bytes()) agent = authenticate_with_certificate_chain( reactor, base_url, client_chain, client_key, ca_cert, ) return network_kubernetes( base_url=base_url, agent=agent, )
def uninstall(spec, logger, **kwargs): logger.info('uninstall') try: delete('tekton-pipelines', ["tekton-pipelines-controller", "tekton-pipelines-webhook", "tekton-triggers-controller", "tekton-triggers-webhook", "tekton-dashboard"], logger) try: subprocess.run(f"kubectl delete task.tekton.dev/kaniko -n {spec.get('namespace', 'default')}", shell=True, check=False, env=osenv) subprocess.run(f"kubectl delete task.tekton.dev/git-clone -n {spec.get('namespace', 'default')}", shell=True, check=False, env=osenv) except subprocess.CalledProcessError as e: logger.error(e.output) raise e api = HTTPClient(KubeConfig.from_file()) obj = { 'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': { 'name': spec.get('namespace'), } } Namespace(api, obj).delete() except ObjectDoesNotExist: pass
def main(): args = parse_args() if args.debug: log_level = logging.DEBUG elif args.verbose: log_level = logging.INFO elif args.quiet: log_level = logging.CRITICAL else: log_level = logging.WARNING setup_logging(log_level) api = HTTPClient(KubeConfig.from_file(os.environ['KUBECONFIG'])) resource_map = ( (CassandraDaemonSet, 'cassandra/k8s/daemonset.yaml'), (CassandraService, 'cassandra/k8s/service.yaml'), (CassandraService, 'cassandra/k8s/peer-service.yaml') ) pool = CassandraResourceFactory(api, resource_map) ctl = CassandraResourceController(pool) if args.action == 'create': ctl.create() if args.action == 'update': ctl.update() elif args.action == 'delete': ctl.delete() elif args.action == 'validate': ctl.validate()
def delete(namespace, names, logger): api = HTTPClient(KubeConfig.from_file()) for name in names: deploy = Deployment.objects(api, namespace=namespace).get(name=name) deploy.delete() logger.info(f'delete Deployment: {str(deploy)}') service = Service.objects(api, namespace=namespace).get(name=name) service.delete() logger.info(f'delete Service: {str(service)}')
def get_clusters(self): # Kubernetes Python client expects "vintage" string path config_file = str(self._path) if self._path else None config = KubeConfig.from_file(config_file) for context in config.contexts: if self._contexts and context not in self._contexts: # filter out continue # create a new KubeConfig with new "current context" context_config = KubeConfig(config.doc, context) client = HTTPClient(context_config) cluster = Cluster(context, client) yield cluster
def network_kubernetes_from_context(reactor, context, path=None): """ Create a new ``IKubernetes`` provider based on a kube config file. :param reactor: A Twisted reactor which will be used for I/O and scheduling. :param unicode context: The name of the kube config context from which to load configuration details. :param FilePath path: The location of the kube config file to use. :return IKubernetes: The Kubernetes service described by the named context. """ if path is None: path = FilePath(expanduser(u"~/.kube/config")) config = KubeConfig.from_file(path.path) context = config.contexts[context] cluster = config.clusters[context[u"cluster"]] user = config.users[context[u"user"]] base_url = URL.fromText(cluster[u"server"].decode("ascii")) [ca_cert] = parse(cluster[u"certificate-authority"].bytes()) client_chain = parse(user[u"client-certificate"].bytes()) [client_key] = parse(user[u"client-key"].bytes()) agent = authenticate_with_certificate_chain( reactor, base_url, client_chain, client_key, ca_cert, ) return network_kubernetes( base_url=base_url, agent=agent, )
def namespace(spec, old, new, logger, **kwargs): logger.info(f'namespace: {old=}, {new=}') api = HTTPClient(KubeConfig.from_file()) if new: obj = { 'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': { 'name': new, } } Namespace(api, obj).create() elif old: obj = { 'apiVersion': 'v1', 'kind': 'Namespace', 'metadata': { 'name': old, } } Namespace(api, obj).delete()
def _merge_configs_from_env(kubeconfigs): """ Merge configuration files from a ``KUBECONFIG`` environment variable. :param bytes kubeconfigs: A value like the one given to ``KUBECONFIG`` to specify multiple configuration files. :return KubeConfig: A configuration object which has merged all of the configuration from the specified configuration files. Merging is performed according to https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#merging-kubeconfig-files """ paths = list( FilePath(p) for p in kubeconfigs.split(pathsep) if p ) config = _merge_configs(list( KubeConfig.from_file(p.path) for p in paths )) return config
def api(kubeconfig): config = KubeConfig.from_file(str(kubeconfig)) return HTTPClient(config)
import time import os import yaml import json from datetime import datetime from time import sleep import kopf from pykube import KubeConfig, HTTPClient, Secret, Deployment, all from pykube.exceptions import PyKubeError, HTTPError, KubernetesError from pprint import pprint try: cfg = KubeConfig.from_service_account() except FileNotFoundError: cfg = KubeConfig.from_file() api = HTTPClient(cfg) @kopf.on.create('bazinga.io', 'v1', 'secretz') def create_secret(body, meta, spec, status, logger, **kwargs): secretName = spec.get('secretName') print(f"Create Secret.... {secretName}") data = _render_yaml(spec, meta) obj = Secret(api, data) try: obj.create() except HTTPError as e:
def create(self) -> HTTPClient: kube_config = KubeConfig.from_file(self.kube_config_path) self._kube_client = HTTPClient(kube_config) return self._kube_client
from flask import Flask, render_template from pykube import Deployment, HTTPClient, KubeConfig api = HTTPClient(KubeConfig.from_file('~/.kube/config')) app = Flask(__name__) @app.route('/') @app.route('/deployments/') def deployments_list(): deployments = Deployment.objects(api).filter(namespace='default') return render_template('deployment_list.html', deployments=deployments) @app.route('/deployments/<name>') def deployments_get(name): deployment = Deployment.objects(api).get(name=name) return render_template('deployment_get.html', deployment=deployment)