Search code examples
ansiblehandler

Ansible handlers get name value


I have a role and I want to restart a service when file changed for an item, so I try to make a variable for the handlers, but on ansible deployment, I get file ac

- name: Create jinja templating
  template:
    src: "/var/opt/config.json.j2"
    dest: "/var/opt/{{ item }}/config.json"
  with_list: "{{ variable }}"
  register: template_out
  notify:
    - my_handler

main/handlers.yml

- name: "Restart {{ item }}"
  shell: "service restart {{ item }}"
  with_items: "{{ template_out.results | selectattr('changed', 'equalto', true) | list }}"


(item={u'md5sum': u'e48695da5017f1a5558b66eafc1cdccf', u'uid': 0, u'dest': u'config.yml', u'owner': u'root', 'diff': [], u'size': 4272, u'src': u'/root/.ansible/tmp/ansible_mitogen_action_1073ea002b288ef0/source', 'ansible_loop_var': u'item', u'group': u'root', 'item': u'elcos', u'checksum': u'918eb1bda64b3c9cfb14fd9f6b526cb0492fbff4', u'changed': True, 'failed': False, u'state': u'file', u'gid': 0, u'mode': u'0644', u'invocation': {u'module_args': {u'directory_mode': None, u'force': True, u'remote_src': None, u'dest': u'config.yml', u'selevel': None, u'_original_basename': u'vector_conf_elcos/elcos.toml', u'delimiter': None, u'regexp': None, u'owner': None, u'follow': False, u'validate': None, u'local_follow': None, u'src': u'/root/.ansible/tmp/ansible_mitogen_action_1073ea002b288ef0/source', u'group': None, u'unsafe_writes': None, u'checksum': u'918eb1bda64b3c9cfb14fd9f6b526cb0492fbff4', u'seuser': None, u'serole': None, u'content': None, u'setype': None, u'mode': None, u'attributes': None, u'backup': False}}})

so how I can fetch only the name value and not whole output


Solution

  • ---
    - hosts: localhost
      gather_facts: false
    
      vars:
        variable:
          - memcached
          - apache
    
      tasks:
        - name: Create jinja templating
          template:
            src: "config.json.j2"
            dest: "{{ item }}_config.json"
          with_list: "{{ variable }}"
          register: template_out
          notify: "Restart Service"
    
      handlers:
        - name: Restart Service
          shell: "service restart {{ item }}"
          with_items: "{{ template_out.results
                          | selectattr('changed', 'equalto', true)
                          | map(attribute='item')
                          | list }}"
    

    I recommend using this handler to restart services:

        - name: Restart service
          service:
            name: "{{ item }}"
            state: restarted
          loop: "{{ service_restart.results
                    | selectattr('changed', 'equalto', true)
                    | map(attribute='item')
                    | list }}"