Ruin The assorted ramblings of Brendan Tobolaski

“Immediate” handler for Ansible

One of the things that I miss in Ansible is an equivalent of Chefʼs notifies :immediately. The problem that I was trying to solve is resizing the MySQLʼs binary logs (which turns out to be a bit more complicated). Basically, you install MySQL, then change the configuration file and finally restart MySQL which, causes MySQL to barf because the binary logs arenʼt the correct size.

The solution that sprang to mind for this was to delete the binary logs immediately after installation and changing the configuration file. Handlers canʼt quite do this. They only run at the end of the current playbook block. There also isnʼt a way to only run the handler if both things have changed. Ansibleʼs documentation isnʼt much help in this regard. The When statement documentation gets you fairly close but, not quite there.

Here is how you can do it. In my case, I register: mysql_installation in the MySQL installation and register: config_status in the template block for changing the configuration. Then on our “handler” task we add when: mysql_installation|changed and config_status|changed. Here is what it looks like all together:

- name: Install mysql
  apt: name=mysql
   register: mysql_installation

- name: Configure mysql
   template: src=my.cnf.j2
  notify: Restart mysql
  register: config_status

- name: Delete binary logs
  shell: service mysql stop && rm -rf /var/lib/mysql/ib_logfile* && service mysql start
  when: mysql_installation|changed and config_status|changed

There are better solutions to my original problem but, I think this technique could be useful for other things.