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:

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 10.0.0.200 host I use sudo with pass1, on the 10.0.0.201 host I used su with pass2.

[vhosts]
10.0.0.1    ansible_user=root

[physical]
10.0.0.200  ansible_user=xxx  ansible_become=yes  ansible_become_method=sudo  ansible_become_pass="{{ pass1 }}"
10.0.0.201  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

  hosts:
    - vhosts
    - physical

  vars_files:
    - 'vars/vault.yml'

  tasks:

    - 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

© holger 2015 - 2020 |