Best practices bootstrapping new Ansible servers with the root account

When booting up a new server, if root is the primary account created, what is the best practice to handle running as root the first time a playbook runs vs running it as ansible after my script sets up its service own account?


Whatever process you have to provision privileged service accounts. This is not Ansible specific, and may be a different implementation depending on operating system. Several approaches exist:

  • Create a user at instance install or first boot.
  • Join to a directory or other central identity that already contains the users.
  • Install and run ansible locally on managed nodes, bypassing the need for ssh. Possibly as root from cron. See ansible-pull for an example script.
  • ssh in as root. Controversial, many sshd configurations deny root login.

Create the ansible service account and install the ssh public key at install time.

I have this scripted in my kickstart scripts:

%post --erroronfail
# Set up ansible user
useradd -rm ansible
echo "ansible ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/ansible
chmod 440 /etc/sudoers.d/ansible
mkdir -m 700 /home/ansible/.ssh
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFsW/fNKMjMQjkYcQOqwD14UItgMBGIX7HHpP2YTvQkI ansible" > /home/ansible/.ssh/authorized_keys
chmod 600 /home/ansible/.ssh/authorized_keys
chown -R ansible.ansible /home/ansible/.ssh
%end