You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import logging
from kubernetes import client, config
from kubernetes.client.exceptions import ApiException
from kubernetes.config.config_exception import ConfigException
Function to add a tag (label) to all nodes in a Kubernetes cluster with error handling and logging
def add_tag_to_all_nodes(tag_key: str, tag_value: str):
try:
# Load the kubeconfig file
config.load_kube_config()
except ConfigException as e:
logging.error(f"Failed to load kubeconfig: {e}")
return
try:
# Initialize the Kubernetes client
v1 = client.CoreV1Api()
# Retrieve a list of all nodes in the cluster
nodes = v1.list_node().items
logging.info(f"Found {len(nodes)} nodes in the cluster.")
except ApiException as e:
logging.error(f"Failed to list nodes: {e}")
return
# Iterate over each node and add the specified tag (label)
for node in nodes:
try:
# Check if the label already exists; if not, add it
if node.metadata.labels:
if tag_key not in node.metadata.labels:
node.metadata.labels[tag_key] = tag_value
else:
node.metadata.labels = {tag_key: tag_value}
# Patch the node with the new label
v1.patch_node(node.metadata.name, body={"metadata": {"labels": node.metadata.labels}})
logging.info(f"Added label {tag_key}={tag_value} to node {node.metadata.name}.")
except ApiException as e:
logging.error(f"Failed to patch node {node.metadata.name}: {e}")
Example usage (Commented out to follow instructions)
import logging
from kubernetes import client, config
from kubernetes.client.exceptions import ApiException
from kubernetes.config.config_exception import ConfigException
Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
Function to add a tag (label) to all nodes in a Kubernetes cluster with error handling and logging
def add_tag_to_all_nodes(tag_key: str, tag_value: str):
try:
# Load the kubeconfig file
config.load_kube_config()
except ConfigException as e:
logging.error(f"Failed to load kubeconfig: {e}")
return
Example usage (Commented out to follow instructions)
add_tag_to_all_nodes("environment", "development")
The text was updated successfully, but these errors were encountered: