如何通过文件导入数据填充K8s ConfigMap并使用客户端API在Pod中消费
Hey there! Let me walk you through a clear, step-by-step approach to get this done—from writing your key-value pairs to consuming them in a Pod via the kubernetes-client API:
You have two common, easy-to-use formats to choose from: plain text (env-style) or JSON.
Plain Text (Env-Style)
Create a file (e.g., app-config.txt) where each key-value pair lives on its own line:
DB_HOST=db.example.com DB_PORT=5432 API_KEY=abc123 MAX_CONNECTIONS=10
JSON Format
Create a JSON file (e.g., app-config.json) with a standard object structure—great if you prefer structured data:
{ "DB_HOST": "db.example.com", "DB_PORT": "5432", "API_KEY": "abc123", "MAX_CONNECTIONS": "10" }
Use kubectl to turn your file into a ConfigMap in your cluster. Here are the most common commands depending on your file type:
From Plain Text Env File
This directly maps each line in your text file to a key-value pair in the ConfigMap's data field:
kubectl create configmap app-config --from-env-file=app-config.txt --namespace=default
From JSON File
Use --from-file to load the JSON file—note that the filename becomes a key in the ConfigMap, with the full JSON content as its value:
kubectl create configmap app-config --from-file=app-config.json --namespace=default
Verify the ConfigMap
Double-check that your data was imported correctly with this command:
kubectl get configmap app-config --namespace=default -o yaml
First, make sure your Pod has permission to read ConfigMaps. Assign a ServiceAccount with a Role that allows get access to ConfigMaps (the built-in view ClusterRole works for this).
Below are practical examples for two popular kubernetes-client SDKs:
Python kubernetes-client
- Install the SDK in your Pod's runtime environment:
pip install kubernetes
- Code to fetch and use the ConfigMap:
from kubernetes import client, config def load_cluster_config(): # Load in-cluster config (automatically picks up Pod's Kubernetes context) config.load_incluster_config() return client.CoreV1Api() def fetch_config_map(api, config_map_name, namespace): try: return api.read_namespaced_config_map(name=config_map_name, namespace=namespace) except client.ApiException as e: print(f"Failed to fetch ConfigMap: {e}") return None if __name__ == "__main__": core_api = load_cluster_config() app_config = fetch_config_map(core_api, "app-config", "default") if app_config: # Extract values from the ConfigMap's data field db_host = app_config.data.get("DB_HOST") db_port = app_config.data.get("DB_PORT") api_key = app_config.data.get("API_KEY") # Use the values in your application logic print(f"Connecting to database at {db_host}:{db_port}") print(f"Loaded API Key: {api_key}")
Java kubernetes-client
- Add the SDK dependency to your
pom.xml(for Maven projects):
<dependency> <groupId>io.kubernetes</groupId> <artifactId>client-java</artifactId> <version>18.0.0</version> <!-- Use the latest stable version --> </dependency>
- Code to fetch and use the ConfigMap:
import io.kubernetes.client.openapi.ApiClient; import io.kubernetes.client.openapi.ApiException; import io.kubernetes.client.openapi.Configuration; import io.kubernetes.client.openapi.apis.CoreV1Api; import io.kubernetes.client.openapi.models.V1ConfigMap; import io.kubernetes.client.util.Config; import java.io.IOException; public class ConfigMapConsumer { public static void main(String[] args) { try { // Load in-cluster configuration ApiClient apiClient = Config.fromCluster(); Configuration.setDefaultApiClient(apiClient); CoreV1Api coreApi = new CoreV1Api(); // Fetch the target ConfigMap from the default namespace V1ConfigMap configMap = coreApi.readNamespacedConfigMap("app-config", "default", null, null, null); // Extract values from the ConfigMap's data String dbHost = configMap.getData().get("DB_HOST"); String dbPort = configMap.getData().get("DB_PORT"); String apiKey = configMap.getData().get("API_KEY"); // Integrate the values into your app System.out.printf("Database connection: %s:%s%n", dbHost, dbPort); System.out.printf("API Key initialized: %s%n", apiKey); } catch (IOException | ApiException e) { e.printStackTrace(); } } }
Quick Side Note
If you don't need dynamic runtime fetching, you could also mount the ConfigMap as environment variables or a file volume in the Pod. But since you specifically asked for the kubernetes-client API approach, the examples above focus on that workflow.
内容的提问来源于stack exchange,提问作者Rakshith Venkatesh




