I recently discovered the slurp module within Ansible when I was attempting to find new modules in Ansible 2.0. It is particularly interesting for me since I’ve been doing a bunch of stuff involving the contents of files on remote nodes for my OpenVPN playbook. So I decided to try using it in one of my latest playbooks and see how much better it is than doing command: cat <file>
.
Using it
My usecase for slurp was checking if a newly bootstrapped host was Fedora 22, and upgrading it to Fedora 23 if it was. The problem in this case was that recent versions of Fedora don’t come with Python 2, so we can’t use gather facts to find the version of Fedora (and need to install Python2 before we do anything).
The suggested method was to install python using the raw command, and then run the setup module to make the facts available.
But I was going to reboot the node right after the install in any case, so I didn’t feel like running the full setup module, so this was a perfect place to try the slurp module.
Using it is simple – there’s only one parameter: src, the file you want to get the contents of.
Similarly, using the results is also simple, with one exception: The content of the file is base64 encoded, so it must be decoded before use. Thankfully, Ansible/Jinja2 provides the b64decode
filter to easily get the contents into a usable form.
My final playbook ended up looking something like this:
gather_facts: no tasks: - name: install packages for ansible support raw: dnf -y -e0 -d0 install python python-dnf - name: Check for Fedora 22 slurp: src: /etc/fedora-release register: fedora - name: Upgrade to Fedora 23 command: dnf -y -e0 -d0 --releasever 23 distro-sync when: '"Fedora release 22" in fedora.content|b64decode'
Functionally, it’s pretty much identical to using the old command: cat <file>
, register
, and when: xyz in cmd.stdout
style to get & use the contents of files. All of those elements are still there, just renamed at most – register
is still being used unmodified.
The fact that I’m using a dedicated module for it though makes my playbook look a lot more Ansible-ish, which is something I like. (And the fact I don’t need to have a changed_when
entry is a strong plus for code cleanliness.)