banner
Aki

Aki

太阳能维修,月亮可更换,星星不闪包退换。
twitter

[Operations and Maintenance] K8S Resource Allocation Checklist

Purpose
Organize the distribution of k8s resources and view the allocated resource quotas in each namespace.

#!/bin/bash

# Get a list of all namespaces
namespaces=$(kubectl get namespaces -o jsonpath='{.items[*].metadata.name}')

# Iterate through each namespace
for namespace in $namespaces
do
    echo "Namespace: $namespace"

    # Get all pods in the namespace
    pods=$(kubectl get pods --namespace=$namespace -o jsonpath='{.items[*].metadata.name}')

    total_cpu_limit=0
    total_memory_limit=0

    # Iterate through each pod and accumulate its CPU and memory limits
    for pod in $pods
    do
        cpu_limit=$(kubectl get pod $pod --namespace=$namespace -o jsonpath='{.spec.containers[*].resources.limits.cpu}')
        memory_limit=$(kubectl get pod $pod --namespace=$namespace -o jsonpath='{.spec.containers[*].resources.limits.memory}')

        # Handle CPU limit
        if [[ $cpu_limit =~ ^[0-9]+m$ ]]; then
            cpu_limit=${cpu_limit%m}
        elif [[ $cpu_limit =~ ^[0-9]+$ ]]; then
            cpu_limit=$((cpu_limit * 1000))  # Convert to millicores
        else
            cpu_limit=0
        fi

        # Handle memory limit
        if [[ $memory_limit =~ ^[0-9]+Mi$ ]]; then
            memory_limit=${memory_limit%Mi}
        elif [[ $memory_limit =~ ^[0-9]+Gi$ ]]; then
            memory_limit=$((${memory_limit%Gi} * 1024))  # Convert to MiB
        elif [[ $memory_limit =~ ^[0-9]+$ ]]; then
            memory_limit=$((memory_limit / 1024))  # Assume it is KiB, convert to MiB
        else
            memory_limit=0
        fi

        # Accumulate CPU and memory limits
        total_cpu_limit=$((total_cpu_limit + cpu_limit))
        total_memory_limit=$((total_memory_limit + memory_limit))
    done

    echo "  Total CPU Limit: $total_cpu_limit mCPU"
    echo "  Total Memory Limit: $total_memory_limit MiB"
    echo
done

The final script will export an output.txt file in the root directory with a similar result:

Namespace: kube-public
  Total CPU Limit: 0 mCPU
  Total Memory Limit: 0 MiB

Namespace: kube-system
  Total CPU Limit: 0 mCPU
  Total Memory Limit: 340 MiB

Namespace: local
  Total CPU Limit: 0 mCPU
  Total Memory Limit: 0 MiB

Namespace: monitoring
  Total CPU Limit: 0 mCPU
  Total Memory Limit: 0 MiB
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.