Skip to content

Instantly share code, notes, and snippets.

@samueljon
Created August 31, 2021 13:42
Show Gist options
  • Save samueljon/33067756dfac8cda4cae3925523b093e to your computer and use it in GitHub Desktop.
Save samueljon/33067756dfac8cda4cae3925523b093e to your computer and use it in GitHub Desktop.
#!/bin/bash
#########################################################
# Script Name : ansible_onboarding.sh
# Description : Adds Ansible user and sudo permissions.
# Args : none
# Author : Samúel Jón Gunnarsson
# Email : samuel@ok.is
# Version : 20200923-01
########################################################
function create_ansible_user(){
if id "ansible" >/dev/null 2>&1; then
echo "Ansible user exists. Not creating user"
else
echo "Ansible user does not exist. Creating user"
useradd -m ansible
fi
}
function add_authorized_keys_for_ansible(){
if id "ansible" >/dev/null 2>&1; then
if [ -d "/home/ansible/.ssh" ]
then
echo "Folder /home/ansible/.ssh exists. Continuing..."
else
echo "Creating /home/ansible/.ssh does not exist. Creating..."
mkdir /home/ansible/.ssh
fi
echo "Adding ssh key for ansible to authorized_keys"
chmod 700 /home/ansible/.ssh
echo "PUBLIC_LYKILL" >> /home/ansible/.ssh/authorized_keys
chmod 600 /home/ansible/.ssh/authorized_keys
chown -R ansible:ansible /home/ansible/.ssh
fi
}
function add_ansible_to_sudo(){
if id "ansible" >/dev/null 2>&1; then
if [ -f "/etc/sudoers.d/ansible" ]
then
echo "File /etc/sudoers.d/ansible exists. Overriding..."
else
echo "File /etc/sudoers.d/ansible does not exist. Creating..."
fi
echo "ansible ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/ansible
chmod 0440 /etc/sudoers.d/ansible
visudo -cf /etc/sudoers.d/ansible
if [ $? -ne 0 ]; then
echo "sudoers file not valid. Please check"
fi
fi
}
function check_include_dir_in_sudo(){
echo "Sudo.conf file check not implimented yet"
}
##########################
# Main logic starts
##########################
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
else
create_ansible_user
add_authorized_keys_for_ansible
add_ansible_to_sudo
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment