Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Just some code #1

Open
jvalbuena opened this issue Mar 12, 2024 · 0 comments
Open

Just some code #1

jvalbuena opened this issue Mar 12, 2024 · 0 comments

Comments

@jvalbuena
Copy link
Owner

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

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)

add_tag_to_all_nodes("environment", "development")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant