Skip to content

Instantly share code, notes, and snippets.

@aivanise
Created November 4, 2021 13:38
Show Gist options
  • Save aivanise/60d5d83ff3dad8d644766311bc9a3446 to your computer and use it in GitHub Desktop.
Save aivanise/60d5d83ff3dad8d644766311bc9a3446 to your computer and use it in GitHub Desktop.
#!/bin/bash
# exec a command across lxc cluster
Usage() {
cat <<EOHELP
run a command across a LXD cluster
Usage: $(basename $0) -s -f filter -u uservar=value -p project command
-s short version, run in parralel, print a hostname before every output line and do not log
-f jq filter in jq's select() syntax, e.g. -f '.location == "lxd1"' or -f '.config."user.managed" == "true"'
https://stedolan.github.io/jq/manual/#select(boolean_expression)
-p run for project instead for default
-u xx=yy shortcut for -f '.config."user.xx" == "yy"'
-l host shortcut for -f '.location == "host"'
-n dry run, only list the hosts
-h This usage...
EOHELP
exit 1
}
while getopts "nvshf:u:p:l:" opt; do
case $opt in
v) VERBOSE=y ;;
s) SHORT=y ;;
n) DRYRUN=y ;;
p) PROJECT="--project ${OPTARG}" ;;
f) FILTER="$FILTER | select(${OPTARG})" ;;
u) val=${OPTARG#*=}; key=${OPTARG%=*}; FILTER="$FILTER | select(.config.\"user.$key\" == \"$val\")" ;;
l) FILTER="$FILTER | select(.location == \"$OPTARG\")" ;;
h|\?) Usage ;;
esac
done
shift $(expr $OPTIND - 1 )
[[ $# -eq 0 ]] && ! [[ "$DRYRUN" ]] && Usage
defremote=$(fgrep default-remote ~/.config/lxc/config.yml | cut -d: -f 2 | tr -d ' ')
url=$(lxc query /1.0 | jq '.config."cluster.https_address"' | tr -d \")
[[ "$VERBOSE" == "y" ]] && echo cluster: $url filter: $FILTER what: $@
LIST=$(lxc ls -c n $PROJECT --format json | jq -r ".[] $FILTER | .name")
if [[ "$DRYRUN" == "y" ]]; then
echo $LIST
elif [[ "$SHORT" == "y" ]]; then
for lx in ${LIST}; do (lxc exec $PROJECT $lx -- /bin/bash -c "$*" 2>&1 | awk -vlx=$lx '{ print lx ":", $0 }') & done
wait
else
for lx in ${LIST}; do
printf "\n#=== %s ===#\n%s\n" $lx "$(lxc exec $PROJECT $lx -- /bin/bash -c "$*" 2>&1)" | tee -a /tmp/lxrun.$(date '+%Y-%m-%d')_log.txt
done
printf "\nlxrun log file: /tmp/lxrun.$(date '+%Y-%m-%d')_log.txt\n"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment