Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Remotely Authorize and Provision a Salt Minion
#!/bin/bash
# apt-get install sshpass
# http://docs.saltstack.com/en/latest/topics/tutorials/preseed_key.html
BOOTSTRAP=/srv/minion-bootstrap.sh
LOG_LOCATION=/tmp/minion-bootstrap.log
TMP=/tmp/salt
if [[ -z "$1" ]] || [[ -z "$2" ]] ; then
echo "./add-minion.sh <minion name> <minion address>"
exit 1
fi
NAME=$1
ADDRESS=$2
LOCAL_PUB=$TMP/$1.pub
LOCAL_PRI=$TMP/$1.pem
LOCAL_SEED=/etc/salt/pki/master/minions/$1
REMOTE_PUB=/etc/salt/pki/minion/minion.pub
REMOTE_PRI=/etc/salt/pki/minion/minion.pem
mkdir -p $TMP
cd $TMP
## Check if minion exists
if [ -f $LOCAL_SEED ]; then
echo "Minion '$NAME' exists. Delete it to continue."
echo "salt-key -d $NAME -y"
exit 1
fi
## Get ssh creds
read -e -p "User: " USER
read -s -e -p "Password (hidden): " PASSWORD
echo
read -e -p "Port: " -i "22" PORT
SUDO=" echo $PASSWORD | sudo -p '' -S "
if [ "$USER" = "root" ] ; then
echo "Is root, not using sudo."
SUDO=""
fi
SSH_COMMAND="sshpass -p $PASSWORD ssh $USER@$ADDRESS -oStrictHostKeyChecking=no -p $PORT -n"
echo "`date`" >> $LOG_LOCATION 2>&1
echo "Verifying ssh login."
if ! $SSH_COMMAND 'echo "SSH login Successful."' | grep "Successful" >> $LOG_LOCATION 2>&1 ; then
echo "Cannot log into server."
exit 1
fi
echo "Generating seed keys. "
salt-key --gen-keys=$NAME
echo "Accepting generated keys."
cp $LOCAL_PUB /etc/salt/pki/master/minions/$NAME
echo "Running pre-install."
PRE_SCRIPT[0]="mkdir -p /etc/salt/pki/minion"
PRE_SCRIPT[1]="rm -f /tmp/minion-bootstrap.sh "
PRE_SCRIPT[2]="rm -f /tmp/minion.pub"
PRE_SCRIPT[3]="rm -f /tmp/minion.pem"
for command in "${PRE_SCRIPT[@]}" ; do
echo "> Running: $command"
$SSH_COMMAND "$SUDO $command" >> $LOG_LOCATION 2>&1
done
echo "Copying bootstrap files."
CP_SCRIPT[0]="$BOOTSTRAP $USER@$ADDRESS:/tmp/minion-bootstrap.sh"
CP_SCRIPT[1]="$LOCAL_PUB $USER@$ADDRESS:/tmp/minion.pub"
CP_SCRIPT[2]="$LOCAL_PRI $USER@$ADDRESS:/tmp/minion.pem"
for command in "${CP_SCRIPT[@]}" ; do
echo "> Transferring: $command"
sshpass -p $PASSWORD scp -P $PORT $command >> $LOG_LOCATION 2>&1
done
echo "Running install."
MAIN_SCRIPT[0]="mv /tmp/minion.pub $REMOTE_PUB"
MAIN_SCRIPT[1]="mv /tmp/minion.pem $REMOTE_PRI"
MAIN_SCRIPT[2]="bash /tmp/minion-bootstrap.sh $NAME"
for command in "${MAIN_SCRIPT[@]}" ; do
echo "> Running: $command"
$SSH_COMMAND "$SUDO $command" >> $LOG_LOCATION 2>&1
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment