December 18, 2017

Three Ways of Becoming Root in Ansible

To gain a basic understanding on Ansible, I recently decided to play a little with it. What I wanted to achieve is a simple update-playbook for my three servers. One question I stumbled upon more or less immediatly was: how do I actually become root on the different systems?

In case of my Debian box this was straight forward as I can ssh to that box as root using my ssh key. In case of the two Ubuntu boxes, root login is not permitted via ssh. Furthermore, I use different passwords on these machines. So I needed a way to somehow specify this in Ansible. And of cause I don not like to have plaintext passwords in any files.

A colleague told me about Ansible vaults. This pointed me into the right direction and after some research I found a solution. First things first, the project structure:


├── inventory       <-- specifies machines and per-machine settings
├── update.yml      <-- contains the update-playbook
└── vars
    └── vault.yml   <-- contains encrypted passwords

File: inventory

The inventory specifies per-machine settings. In my case I used it to tell ansible which method it sould use to become root and to reference the password in the encrypted vault it should use. On the host I use sudo with pass1, on the host I used su with pass2.

[vhosts]    ansible_user=root

[physical]  ansible_user=xxx  ansible_become=yes  ansible_become_method=sudo  ansible_become_pass="{{ pass1 }}"  ansible_user=xxx  ansible_become=yes  ansible_become_method=su    ansible_become_user=root  ansible_become_pass="{{ pass2 }}"

File: update.yml

The playbook itself is not very intersting. It just contains some commands for updating the packet cache and installing updated packages.

- name: update all hosts

    - vhosts
    - physical

    - 'vars/vault.yml'


    - name: Update apt cache
      apt: update_cache=yes

    - name: Upgrade packages
      apt: upgrade=dist

    - ...

Now to the vault itself. You basically invoke ansible-vault create vars/vault.yml. This opens your favorite text editor in the shell. Here you can specify the passwords (and of cause other variables) which are encrypted when you safe the file and exit the editor.

File: vault.yml (decrypted)

pass1: supersecretpasswordA
pass2: supersecretpasswordB

You can finally invoke the playbook with ansible-playbook update.yml -i inventory --ask-vault-pass

© ho1ger 2015 - 2022