Skip to content

Commit c2aaa86

Browse files
Merge pull request #2816 from anisayakmitra-in/example-configmap-usage
examples: add config_map example for CoreV1Api and Pod mounting
2 parents 46ad25d + f385553 commit c2aaa86

2 files changed

Lines changed: 154 additions & 0 deletions

File tree

‎examples/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ python examples/pod_logs.py
5050
- [cronjob_crud.py](cronjob_crud.py) — create, update and delete a cronjob
5151
- [ingress_create.py](ingress_create.py) — create a deployment, service and ingress
5252
- [node_labels.py](node_labels.py) — list nodes and update their labels
53+
- [config_map.py](config_map.py) — create a ConfigMap and consume it in a Pod (envFrom and volume mounts)
5354
- [patch_namespaced_config_map.py](patch_namespaced_config_map.py) — patch a config map
5455

5556
### Applying YAML

‎examples/config_map.py‎

Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
# Copyright 2026 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""
16+
Demonstrates how to create a V1ConfigMap and consume it in a V1Pod using
17+
typed CoreV1Api models.
18+
19+
This example illustrates:
20+
1. Creating a V1ConfigMap with scalar values and multi-line file data.
21+
2. Injecting ConfigMap data as environment variables via `env_from`
22+
and `V1ConfigMapEnvSource`.
23+
3. Mounting the ConfigMap as a volume into the container via
24+
`V1ConfigMapVolumeSource` and `V1VolumeMount`.
25+
26+
For more information, see:
27+
https://kubernetes.io/docs/concepts/configuration/configmap/
28+
"""
29+
30+
import time
31+
from kubernetes import client, config
32+
from kubernetes.client.rest import ApiException
33+
34+
CONFIGMAP_NAME = "demo-configmap"
35+
POD_NAME = "demo-configmap-pod"
36+
NAMESPACE = "default"
37+
38+
39+
def main():
40+
# Load kubeconfig from default location (~/.kube/config)
41+
config.load_kube_config()
42+
v1 = client.CoreV1Api()
43+
44+
# 1. Define the ConfigMap
45+
cm_metadata = client.V1ObjectMeta(
46+
name=CONFIGMAP_NAME,
47+
labels={"app": "demo-configmap"},
48+
)
49+
cm_data = {
50+
"player_initial_lives": "3",
51+
"ui_properties_file_name": "user-interface.properties",
52+
"game.properties": (
53+
"enemy.types=aliens,monsters\n"
54+
"player.maximum-lives=5\n"
55+
),
56+
}
57+
config_map = client.V1ConfigMap(
58+
api_version="v1",
59+
kind="ConfigMap",
60+
metadata=cm_metadata,
61+
data=cm_data,
62+
)
63+
64+
# 2. Define the Volume and VolumeMount for the Pod
65+
volume_name = "config-volume"
66+
volume = client.V1Volume(
67+
name=volume_name,
68+
config_map=client.V1ConfigMapVolumeSource(
69+
name=CONFIGMAP_NAME,
70+
),
71+
)
72+
volume_mount = client.V1VolumeMount(
73+
name=volume_name,
74+
mount_path="/etc/config",
75+
read_only=True,
76+
)
77+
78+
# 3. Define environment variable source from ConfigMap
79+
env_from = client.V1EnvFromSource(
80+
config_map_ref=client.V1ConfigMapEnvSource(
81+
name=CONFIGMAP_NAME,
82+
),
83+
)
84+
85+
# 4. Define the container using the volume mount and env_from
86+
container = client.V1Container(
87+
name="demo-app",
88+
image="busybox:latest",
89+
command=["sh", "-c", "echo ConfigMap mounted; sleep 3600"],
90+
volume_mounts=[volume_mount],
91+
env_from=[env_from],
92+
)
93+
94+
# 5. Define the PodSpec and V1Pod
95+
pod_spec = client.V1PodSpec(
96+
containers=[container],
97+
volumes=[volume],
98+
restart_policy="Never",
99+
)
100+
pod = client.V1Pod(
101+
api_version="v1",
102+
kind="Pod",
103+
metadata=client.V1ObjectMeta(
104+
name=POD_NAME,
105+
labels={"app": "demo-configmap"},
106+
),
107+
spec=pod_spec,
108+
)
109+
110+
try:
111+
# Create the ConfigMap
112+
print(f"Creating ConfigMap '{CONFIGMAP_NAME}'...")
113+
v1.create_namespaced_config_map(namespace=NAMESPACE, body=config_map)
114+
print("ConfigMap created successfully.")
115+
116+
# Create the Pod consuming the ConfigMap
117+
print(f"Creating Pod '{POD_NAME}' consuming ConfigMap...")
118+
v1.create_namespaced_pod(namespace=NAMESPACE, body=pod)
119+
print("Pod created successfully.")
120+
121+
# Wait for the pod to be scheduled / running
122+
for _ in range(10):
123+
p = v1.read_namespaced_pod(name=POD_NAME, namespace=NAMESPACE)
124+
if p.status.phase in ("Running", "Succeeded"):
125+
print(f"Pod is currently in phase: {p.status.phase}")
126+
break
127+
time.sleep(1)
128+
129+
except ApiException as e:
130+
if e.status == 409:
131+
print(f"Resource already exists: {e.reason}")
132+
else:
133+
print(f"API exception occurred: {e}")
134+
finally:
135+
# Clean up resources
136+
print("\nCleaning up resources...")
137+
try:
138+
v1.delete_namespaced_pod(name=POD_NAME, namespace=NAMESPACE)
139+
print(f"Pod '{POD_NAME}' deleted.")
140+
except ApiException:
141+
pass
142+
143+
try:
144+
v1.delete_namespaced_config_map(
145+
name=CONFIGMAP_NAME, namespace=NAMESPACE
146+
)
147+
print(f"ConfigMap '{CONFIGMAP_NAME}' deleted.")
148+
except ApiException:
149+
pass
150+
151+
152+
if __name__ == "__main__":
153+
main()

0 commit comments

Comments
 (0)