Is there an python API function to read labels from kubernetes statefulsets? - kubernetes

I am trying to find an API function to read the keys and values of all the labels in a kubernetes statefulset. Can anyone point me to an example or documentation on how this can be done?

Have you taken a look at this library?
https://github.com/kubernetes-client/python
Utilizing the above library, the way that I would do to achieve what you want is:
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.AppsV1Api()
print("Listing StatefulSets' labels:")
ret = v1.list_stateful_set_for_all_namespaces(watch=False)
for i in ret.items:
print(i.metadata.labels)

Related

Kubernetes python API get instances of CRD

I'm currently using the Python APIs for Kubernetes and I have to:
Retrieve the instance of a custom resource name FADepl.
Edit the value of that instance.
In the terminal, I would simply list all FADepls with kubectl get fadepl and then edit the right one using kubectl edit fadepl <fadepl_name>. I checked the K8s APIs for Python but I can't find what I need. Is it something I can do with the APIs?
Thank you in advance!
You're right. Using get_namespaced_custom_object you can retrieve the instance. This method returns a namespace scoped custom object. By default it uses a synchronous HTTP request.
Since the output of that method returns an object, you can simply replace it using replace_cluster_custom_object.
Here you can find implementation examples.
See also whole list of API Reference for Python.
You can use list_cluster_custom_object method from kubernetes.client.CustomObjectsApi.
Let's say that I need to get all calico globalnetworksets instances which are a CRD from calico project.
So first, we need to retrieve some crd data using kubectl as follows:
# get api group, version and plural
> kubectl api-resources -o wide | grep globalnetworkset
globalnetworksets crd.projectcalico.org/v1 false GlobalNetworkSet
--------------- ------------------- --
`plural` api group v
With that in mind, we implement list_cluster_custom_object
from kubernetes.client import CustomObjectsApi
group = "crd.projectcalico.org"
v = "v1"
plural = "globalnetworksets"
global_network_sets = CustomObjectsApi.list_cluster_custom_object(group, v, plural)
I found the get_namespaced_custom_object call that should do the trick

kubectl vs json api for customdefinition or operator

is it possible to use json api instead of all kubectl commands.
Also how would be update a resource or custom definition in that case.
You could take a look at API client libraries.
To call the Kubernetes API from a programming language, you can use client libraries. Officially supported client libraries:
Kubernetes Go client library
Kubernetes Python client library
Kubernetes Java client library
Kubernetes JavaScript client library
To write applications using the Kubernetes REST API, you do not need to implement the API calls and request/response types yourself. You can use a client library for the programming language you are using.
Client libraries often handle common tasks such as authentication for you. Most client libraries can discover and use the Kubernetes Service Account to authenticate if the API client is running inside the Kubernetes cluster, or can understand the kubeconfig file format to read the credentials and the API Server address.
The two paths that support extending the API with custom resources are:
CustomResourceDefinition for basic CRUD needs.
aggregator for a full set of Kubernetes API semantics to
implement their own apiserver.
For example there is a way of creating crd resource with python and some code examples.
list all pods
from kubernetes import client, config
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
watch on namespace object:
from kubernetes import client, config, watch
# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()
v1 = client.CoreV1Api()
count = 10
w = watch.Watch()
for event in w.stream(v1.list_namespace, _request_timeout=60):
print("Event: %s %s" % (event['type'], event['object'].metadata.name))
count -= 1
if not count:
w.stop()
print("Ended.")
More examples can be found in examples folder.

How to use a multiple kubernetes resource file through kubernetes python client similar to kubectl apply -f

I have a kubernetes multi-resource file which contains different resources that are to be applied for e.g. deployment-definition, service-defintion, pv, pvc etc. Is there any way to use this single file through kubernetes python client to deploy all these resources at once ?
Though my scenario is a bit different. I have a file which use CRDs alongwith custom kubernetes resource objects for e.g. Deployment + ambassador's Mapping. How to achieve this using kubernetes python client?
With the client, you have to do them all separately. When you have multiple documents in a YAML file, kubectl just splits them for you and makes an API call for each.
I have a kubernetes multi-resource file
Is there any way to use this single file through kubernetes python client to deploy all these resources at once ?
Please check the content of examples directory.
from os import path
import yaml
from kubernetes import client, config
def main():
# Configs can be set in Configuration class directly or using helper
# utility. If no argument provided, the config will be loaded from
# default location.
config.load_kube_config()
with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f:
dep = yaml.safe_load(f)
k8s_beta = client.ExtensionsV1beta1Api()
resp = k8s_beta.create_namespaced_deployment(
body=dep, namespace="default")
print("Deployment created. status='%s'" % str(resp.status))
if __name__ == '__main__':
main()
Important note: it's a must to use triple dashes at the top of your yaml file and in-between resources, if it contains more than one resource.
.../utils/create_from_yaml.py and .../examples/create_deployment_from_yaml.py are worth checking as well.
I have a file which use CRDs alongwith custom kubernetes resource objects
as #coderanger told, the example can be found in .../docs/CustomObjectsApi.md
Hope that helps.
you can use config.new_client_from_config to manage multi clusters.
or use kube config from dict not local file.
from kubernetes import client, config
from kubernetes.client import Configuration, ApiClient
def new_client_from_dict(conf: dict, context: str):
"""
create client via conf dict
"""
client_config = type.__call__(Configuration)
config.load_kube_config_from_dict(config_dict=conf, context=context, persist_config=False,
client_configuration=client_config)
return ApiClient(configuration=client_config)
client1 = client.CoreV1Api(api_client=new_client_from_dict(CLUSTER1_KUBE_CONFIG, context='cluster1'))
client2 = client.CoreV1Api(api_client=new_client_from_dict(CLUSTER2_KUBE_CONFIG, context='cluster2'))
client1.list_namespaced_pod()
client2.list_namespaced_pod()

Filter Kubernetes API by pod name

I have a Kubernetes cluster running in minikube, I want to filter out all Logstash pods via Kubernetes API. Kubernetes API documentation is a bit confusing, I did some research and found out that I can use something like this, but I have been unsuccessful so far:
localhost:8000/api/v1/namespaces/default/pods?labelSelector=logstash
any ideas how to retrieve this? Any help would be really appreciated.
any ideas how to retrieve this?
Since labels are defined in <name>=<value> pairs you need to supply both, as described in the documentation (see the API section)
As an example, supposing you have:
namepace: default
labels on pods you want to select:
role=ops
application=logstash
kubectl proxy runs on localhost:8000
Then your api call would look like this:
curl localhost:8000/api/v1/namespaces/default/pods?labelSelector=role%3Dops,application%3Dlogstash

Kubernetes Spring Cloud Multiple Config Maps being used

As per the documentation at - https://github.com/spring-cloud-incubator/spring-cloud-kubernetes/#configmap-propertysource, it is possible to make ConfigMaps available during application bootstrapping through adding spring.cloud.kubernetes.config.name to the bootstrap.yaml/properties.
Is it possible to consume multiple ConfigMaps in this manner?
I believe it is possible to do this in the pod specification through the use of env-from - https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/. But it would be great to do this with the current setup that we have.
As you can see in ConfigMapPropertySource.java, only one ConfigMap will be used by this property source.
However, using envFrom, all entries in a ConfigMap can be provided as environment variables to the container and Spring Boot can also read environment variables, so maybe this will help you.
Maybe the spring.cloud.kubernetes.config.sources config is also an option here. Here you can specify multiple configmaps.
See https://cloud.spring.io/spring-cloud-static/spring-cloud-kubernetes/1.0.0.M2/multi/multi__configmap_propertysource.html