This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash -e | |
# runInPods.sh | |
# @description run any statement in all k8s pods with name matching a regex within a given context (kubectl config view ). | |
# @author Nestor Urquiza | |
# @date 20180929 | |
# | |
# @example1 For my-project, in my-cluster, in pods named '*nodejs*', run the 'ps -ef | grep node' command | |
# ./runInPods.sh -c gke_my-project_us-east1-b_my-cluster -r nodejs -s "ps -ef | grep node" | |
# | |
# options | |
while [[ $# -gt 1 ]]; do | |
key="$1" | |
case $key in | |
-c|--context) | |
context="$2" | |
shift | |
;; | |
-r|-regex) | |
regex="$2" | |
shift | |
;; | |
-s|--statement) | |
statement="$2" | |
shift | |
;; | |
*) | |
# unknown | |
;; | |
esac | |
shift | |
done | |
# functions | |
function fail() { | |
echo $1 | |
echo $USAGE | |
exit 1 | |
} | |
# main | |
USAGE="Usage: `basename $0` (-c, --context --- from 'kubectl config view') [-r, --regex --- defaults to all)] (-s, --statement --- any valid command)" | |
if [ "$context" == "" ]; then | |
fail "Context is mandatory. Find available contexts by running 'kubectl config view'" | |
fi | |
if [ "$regex" == "" ]; then | |
regex=. | |
fi | |
if [ "$statement" == "" ]; then | |
fail "Statement is mandatory. Use any linux command you want to run in the matching pod(s)'" | |
fi | |
kubectl config use-context $context | |
command="cat <(" | |
for line in $(kubectl get pods | \ | |
grep "$regex" | grep Running | awk '{print $1}'); do | |
command="kubectl exec -i $line -- $statement" | |
echo "Running $statement in $line" | |
eval "$command" | |
done |
No comments:
Post a Comment