Search code examples
ansibleansible-factsansible-handlers

Ansible handler read local fact


I have an Ansible playbook to install a variable number of applications in a group of servers. To install the applications, a number of sequential tasks have to run, and since there may be several applications, I loop through them with with_items:

I also register any changes in a local fact in such a way that if three tasks are performed on application A, application A is flagged.

I am having problems with the handler. It should read these local facts and restart any application that has been flagged, but I am failing at achieving this. My handler just skips, but debug shows the local fact with the flag.

My playbook is similar to this:

---
- name: Ensure the application's jar file exists
  copy:
    src: '{{ item.appName }}/{{ item.jarName }}'
    dest: '{{ AppsRootFolder }}/{{ item.appName }}/{{ item.jarName }}'
  register: task
  with_items: '{{ deployApp }}'
  notify: Restart application

- name: Registering App for later restart
  set_fact:
    myapps_toberestarted_{{ item.item.appName }}: "{{ item.changed }}"
  with_items: "{{ task.results }}"
  when: "{{ item.changed }}"

- name: Ensure the application's conf file exists
  template:
    src: '{{ item.confName }}.j2'
    dest: '{{ AppsRootFolder }}/{{ item.appName }}/{{ item.confName }}'
  register: task
  with_items: '{{ deployApp }}'
  notify: Restart application

- name: Registering App for later restart
  set_fact:
    myapps_toberestarted_{{ item.item.appName }}: "{{ item.changed }}"
  with_items: "{{ task.results }}"
  when: "{{ item.changed }}"

The handler I need help with follows. It is skipping the "Restart application" task:

- name: Restart application
  debug: var=myapps_toberestarted_{{ item.appName }}
  with_items: "{{ deployApp }}"
  when: myapps_toberestarted_{{ item.appName }} == 'true'

And finaly my group_vars

AppsRootFolder: /opt/Apps
deployApp:
  - { appName: "API", jarName: "api.jar", confName: "api.conf" } 
  - { appName: "Demo", jarName: "demo.jar", confName: "demo.conf" } 
  - { appName: "Another", jarName: "another.jar", confName: "another.conf" } 

Solution

  • true/false (registered in task results' changed variable, hence also in item.changed) are Boolean values not strings, so you can define your conditional in the handler this way:

    when: myapps_toberestarted_{{ item.appName }}
    

    With == 'true' you are comparing it to a string which will always give a negative result.