Understanding Handlers in Ansible

ansibleansible-playbook

Below is the tasks I have in my nginx role

# tasks file for nginx
- name: Backup and update nginx configuration file
  template:
     src: templates/proxy.conf.j2
     dest: "{{ nginx_conf }}"
     backup: true
     owner: root
     group: root
     mode: 0644

- name: Running nginx -t to validate the config
  shell: 'nginx -t'
  register: command_output
  become: true
  notify: Reload nginx

- debug:
   var: command_output.stderr_lines

And I have a separate directory called handlers, which has below content.

- name: Reloading nginx service only if the syntax is ok
  systemd:
    name: nginx.service
    state: reloaded'
    when: command_output.stderr | regex_search("syntax is ok")

Not sure, if the variable command_output will be read by the handlers.

Best Answer

It won't, because command_output does not exist at the handler. You could modify the error handling of the check task and define "changed" with your condition, but in this case I'd just use the validate attribute in the template task and skip the rest.

- name: Backup and update nginx configuration file
  template:
     src: templates/proxy.conf.j2
     dest: "{{ nginx_conf }}"
     backup: true
     owner: root
     group: root
     mode: 0644
     validate: nginx -t
     notify: Reload nginx

Note: The name of the handler needs to be changed to Reload nginx for this to work.