Skip to content

Instantly share code, notes, and snippets.

@gswallow
Last active December 27, 2015 02:29
Show Gist options
  • Save gswallow/7252081 to your computer and use it in GitHub Desktop.
Save gswallow/7252081 to your computer and use it in GitHub Desktop.
make running knife easier
#!/bin/bash
user="indigo_chef"
#pass='xxx'
################################################################################
# Parse arguments
################################################################################
ARGS=`getopt se:r:w $* 2> /dev/null`
# Bad arguments
if [ $? != 0 ]; then
echo "Usage: run -r role [ -r role ... ] -e environment [ -w ] [-s]"
echo " ( -w specifies to run knife winrm, not knife ssh )"
echo " ( -s for sudo )"
exit 2
fi
set -- $ARGS
roles=( )
env="_default"
for i; do
case "$i" in
-e|--env)
if [ -n "$2" ]; then
env=$2
shift;
fi
shift;
;;
-r)
if [ -n "$2" ]; then
if [ "${#roles[*]}" -gt "0" ]; then
roles=( "${roles[@]}" "OR role:$2" )
else
roles=( "${roles[@]}" "role:$2" )
fi
shift;
fi
shift;
;;
-s)
sudo=1
shift;
;;
-w)
platform="AND platform_family:windows*"
shift;
;;
--)
shift;
break;
;;
esac
done
################################################################################
# Construct the search query
################################################################################
role_query=""
if [ "${#roles[*]}" -gt "1" ]; then
role_query="AND ( ${roles[@]} )"
elif [ "${#roles[*]}" -gt "0" ]; then
role_query="AND ${roles[@]}"
fi
search_query="chef_environment:$env $role_query $platform"
################################################################################
# Construct the remote command (handle sudo)
################################################################################
if [ ! $pass ]; then
echo -n "Enter the password for $user: "
read -s pass
fi
if [ $sudo ]; then
if [ ! $platform ]; then
command="echo $pass | sudo -S $*"
fi
else
command="'$*'"
fi
################################################################################
# Do it!
################################################################################
if [ -n "$platform" ]; then
command="knife winrm '$search_query' '$command' -p 5986 -t ssl --no-ssl-peer-verification -x $user -P $pass -a ipaddress"
else
command="knife ssh '$search_query' '$command' -x $user -P $pass -a ipaddress"
fi
eval $command
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment