---
# System prepended metadata

title: ' OCP container resource usage script'

---

---
date-created: 20240222
tags:
- ocp
- bash/script
---

# OCP container resource usage script

```bash=
output_file="report.md"
touch $output_file

# Start with an empty output file
> "$output_file"
# Print the Markdown table header to the file
echo "|container name| cpu request | CPU USAGE (POD) |  cpu limit | memory request | memory limit |  current memory usage (pod) |" >> "$output_file"
echo "|--------------|-------------|-----------|----------------|--------------|-------------------------|---------------------------|" >> "$output_file"
# Get namespaces, excluding those starting with "openshift"
namespaces=$(oc get namespaces --no-headers | awk '{print $1}' | grep -v '^openshift')
for namespace in $namespaces; do
    # Get all pods in the current namespace
    pods=$(oc get pods -n $namespace -o jsonpath="{.items[*].metadata.name}")
    for pod in $pods; do
        # Get pod metrics for current usage, ensure jq is available
        cpu_usage=$(oc get --raw "/apis/metrics.k8s.io/v1beta1/namespaces/$namespace/pods/$pod" | jq -r '.containers[0].usage.cpu')
        memory_usage=$(oc get --raw "/apis/metrics.k8s.io/v1beta1/namespaces/$namespace/pods/$pod" | jq -r '.containers[0].usage.memory')
        # Get container specs
        containers=$(oc get pod $pod -n $namespace -o jsonpath="{.spec.containers[*].name}")
        sleep 3
        for container in $containers; do
            # Get requests and limits
            cpu_request=$(oc get pod $pod -n $namespace -o jsonpath="{.spec.containers[?(@.name=='$container')].resources.requests.cpu}")
            echo "Container: $container | pod: $pod | cpu req: $cpu_request"
            cpu_limit=$(oc get pod $pod -n $namespace -o jsonpath="{.spec.containers[?(@.name=='$container')].resources.limits.cpu}")
            memory_request=$(oc get pod $pod -n $namespace -o jsonpath="{.spec.containers[?(@.name=='$container')].resources.requests.memory}")
            memory_limit=$(oc get pod $pod -n $namespace -o jsonpath="{.spec.containers[?(@.name=='$container')].resources.limits.memory}")
            # Append the container details in Markdown format to the file
            echo "| $pod |$container| $cpu_request | $cpu_usage | $cpu_limit | $memory_request | $memory_limit |  $memory_usage |" >> "$output_file"
            sleep 3
        done
    done
done

```