Skip to content

Instantly share code, notes, and snippets.

@tossmilestone
Last active July 19, 2024 15:30
Show Gist options
  • Save tossmilestone/e019dcfe536dcdfc0d8fbf7294a2af34 to your computer and use it in GitHub Desktop.
Save tossmilestone/e019dcfe536dcdfc0d8fbf7294a2af34 to your computer and use it in GitHub Desktop.
Watch the diff change of the kubernetes resource
#!/bin/bash
# Define the resource and namespace to be monitored
RESOURCE_TYPE=$1 # Can be replaced with other resource types, such as deployments, services, etc.
NAMESPACE=$2 # Can be replaced with the actual namespace
RESOURCE_NAME=$3 # If a specific resource name is specified, only monitor that resource; leave empty to monitor all resources of that type
# Get the initial resource YAML
PREVIOUS_YAML=$(kubectl get $RESOURCE_TYPE $RESOURCE_NAME -n $NAMESPACE -o yaml)$'\n'
echo "Start monitoring changes in $RESOURCE_TYPE $RESOURCE_NAME resources..."
kubectl get $RESOURCE_TYPE $RESOURCE_NAME -n $NAMESPACE -o yaml -w | while true; do
CURRENT_YAML=""
while IFS= read -r -t 3 line; do
if [[ $line == "---" ]]; then
break
fi
CURRENT_YAML+="$line"$'\n'
done
if [ -n "$CURRENT_YAML" ]; then
if [ "$CURRENT_YAML" != "$PREVIOUS_YAML" ]; then
echo "Detected changes in $RESOURCE_TYPE $RESOURCE_NAME resource:"
sdiff -s <(echo "$PREVIOUS_YAML") <(echo "$CURRENT_YAML")
PREVIOUS_YAML=$CURRENT_YAML
fi
fi
done
@tossmilestone
Copy link
Author

tossmilestone commented Jul 19, 2024

Usage:

./k8s-watch-diff.sh deploy default hello

watch the deployment hello in namespace default changes and output the diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment