ConfigMaps allow you to decouple configuration artifacts from image content to keep containerized applications portable. In this notebook we would learn how to create a ConfigMap and also how to use its data in Pods as seen in https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/
In [ ]:
from kubernetes import client, config
from kubernetes.client.rest import ApiException
In [ ]:
config.load_kube_config()
In [ ]:
api_instance = client.CoreV1Api()
cmap = client.V1ConfigMap()
In [ ]:
cmap.metadata = client.V1ObjectMeta(name="special-config")
cmap.data = {}
cmap.data["special.how"] = "very"
cmap.data["special.type"] = "charm"
In [ ]:
api_instance.create_namespaced_config_map(namespace="default", body=cmap)
In [ ]:
pod = client.V1Pod()
spec = client.V1PodSpec()
pod.metadata = client.V1ObjectMeta(name="dapi-test-pod")
In [ ]:
container = client.V1Container()
container.name = "test-container"
container.image = "gcr.io/google_containers/busybox"
container.command = ["/bin/sh", "-c", "env"]
In [ ]:
container.env = [client.V1EnvVar(name="SPECIAL_LEVEL_KEY"), client.V1EnvVar(name="SPECIAL_TYPE_KEY")]
container.env[0].value_from = client.V1EnvVarSource()
container.env[0].value_from.config_map_key_ref = client.V1ConfigMapKeySelector(name="special-config", key="special.how")
container.env[1].value_from = client.V1EnvVarSource()
container.env[1].value_from.config_map_key_ref = client.V1ConfigMapKeySelector(name="special-config", key="special.type")
spec.restart_policy = "Never"
spec.containers = [container]
pod.spec = spec
In [ ]:
api_instance.create_namespaced_pod(namespace="default",body=pod)
In [ ]:
log = ""
try:
log = api_instance.read_namespaced_pod_log(name="dapi-test-pod", namespace="default")
except ApiException as e:
if str(e).find("ContainerCreating") != -1:
print("Creating Pod container.\nRe-run current cell.")
else:
print("Exception when calling CoreV1Api->read_namespaced_pod_log: %s\n" % e)
for line in log.split("\n"):
if line.startswith("SPECIAL"):
print(line)
In [ ]:
api_instance.delete_namespaced_config_map(name="special-config", namespace="default", body=cmap)
In [ ]:
api_instance.delete_namespaced_pod(name="dapi-test-pod", namespace="default", body=client.V1DeleteOptions())
In [ ]: