To debug environment variables for a pod in a MicroK8s cluster, you can use a script that retrieves the pod’s environment variables using kubectl exec
. This script allows you to inspect the environment variables of all containers in the pod or a specific container.
Here’s the script:
Script: debug-pod-env.sh
#!/bin/bash
# Function to display usage
usage() {
echo "Usage: $0 -n <namespace> -p <pod-name> [-c <container-name>]"
echo
echo " -n <namespace> Kubernetes namespace of the pod"
echo " -p <pod-name> Name of the pod"
echo " -c <container-name> (Optional) Name of the container in the pod"
echo
echo "Example: $0 -n default -p my-pod"
echo " $0 -n default -p my-pod -c my-container"
exit 1
}
# Check if kubectl is available
if ! command -v kubectl &>/dev/null; then
echo "kubectl is required but not installed. Please install kubectl."
exit 1
fi
# Parse command-line arguments
while getopts "n:p:c:" opt; do
case ${opt} in
n)
namespace=${OPTARG}
;;
p)
pod_name=${OPTARG}
;;
c)
container_name=${OPTARG}
;;
*)
usage
;;
esac
done
# Validate required arguments
if [[ -z "${namespace}" || -z "${pod_name}" ]]; then
usage
fi
# Fetch environment variables
echo "Fetching environment variables for pod: ${pod_name} in namespace: ${namespace}"
if [[ -z "${container_name}" ]]; then
echo "No container name specified. Fetching for all containers..."
kubectl -n "${namespace}" exec "${pod_name}" -- printenv
else
echo "Fetching environment variables for container: ${container_name}"
kubectl -n "${namespace}" exec "${pod_name}" -c "${container_name}" -- printenv
fi
Usage Instructions:
- Save the script: Copy the script into a file, e.g.,
debug-pod-env.sh
. - Make it executable: Run the following command:
chmod +x debug-pod-env.sh
- Run the script:
- For all containers in the pod:
./debug-pod-env.sh -n <namespace> -p <pod-name>
- For a specific container in the pod:
./debug-pod-env.sh -n <namespace> -p <pod-name> -c <container-name>
- For all containers in the pod:
Example:
If you want to debug a pod named my-app-pod
in the default
namespace:
./debug-pod-env.sh -n default -p my-app-pod
To debug the environment variables of a container named my-container
within the same pod:
./debug-pod-env.sh -n default -p my-app-pod -c my-container
Debug mongo database secrets
kubectl exec -it sample-node-app-6945c8c546 -- printenv | grep "MONGO"
./debug-pod-env.sh -n default -p sample-node-app-6945c8c546 | grep "MONGO"
This script leverages kubectl exec
to run the printenv
command inside the pod or container, allowing you to see the environment variables in real-time.