I haven’t posted anything ansible related in a while, so here is a nifty little function I regularly use when I want to execute something on all (or a subset) of ansible hosts. It’s just a wrapper around ansible host -m script -a scriptname.sh but adds –tree so that the output is stored and can easily be parsed by jq
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ansible_run() { local ansible_directory="${HOME}/svn/ansible/" local command=${1} local target=${2:-all} local dir="${HOME}/ansible_output/${RANDOM:0:5}" local startdir= local script= startdir="$(pwd)" script="$(mktemp)" mkdir -p "${dir}" if [[ $? -eq 0 ]] ; then { echo "#!/usr/bin/env bash" echo "${command}" echo } > "${script}" cd "${ansible_directory}" && time ansible "${target}" -m script -a "${script}" --tree "${dir}" rm "${script}" echo -e "\n${dir}\n" fi rmdir --ignore-fail-on-non-empty "${dir}" cd "${startdir}" || exit } |
Usage example:
1 2 3 4 5 6 | $ ansible_run "iptables -S | grep -E '^-P (INPUT|FORWARD)'" ... /home/user/ansible_output/6599 $ cd ${HOME}/ansible_output/6599 $ jq -r .stdout ./* |