Conditional Handlers in Ansible
One on my Raspberry Pi systems, becky, suddenly broken down in the past few days. To be specific, the Raspberry Pi itself is perfectly fine, but the Samsung SD card got corrupted and locked itself into a read-only mode. Permanently.
So, this presented a nice opportunity for a fresh start – I downloaded and installed 2020 Raspbian OS image and thanked myself for having just recently completed Ansible playbooks for most of becky’s services.
One interesting thing I noticed: because I was configuring SSH service from the very beginning, Ansible had to restart SSH daemon a few times. I have this confgured using Ansble handlers. But there was one problem: in Raspbian SSH is managed by the ssh service, while in CentOS/Debian it’s controlled by sshd service. So my “restart sshd” handler failed.
Here’s the handler:
- name: Restart SSH service
service:
name: ssh
state: restarted
and here’s the error:
TASK [Restart SSH service] **********************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Failed to restart service ssh: Unit ssh.service not loaded."}
The answer is predictable: you make handlers conditional just like you would do for any other task.
- name: Restart SSH service
when: ansible_os_family == 'Debian'
service:
name: ssh
state: restarted
and now it works:
ansible-playbook -i hosts ssh.yml
TASK [Restart SSH service] **********************************************************************************************************************
ok: [localhost]
PLAY RECAP *************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0