skip to Main Content

In my playbook I have two major tasks one task that change the gateway last digit for Debian machines and the second one applies to Redhat machines everything works fine but to be able to trace the machines on which the tasks were executed succesfully on a local file (kind of a log).

I tried to register the results of both tasks with a register

for Debian :

 name: change default gateway address
      replace:
        path: /etc/network/interfaces
        regexp: '(up route add default gw [d]*.[d]*.[d]*).[d]*$'
        replace: '1.254'
        backup: yes
      when: (ansible_facts['distribution'] == "Debian")
      register: debresult

for Redhat:


- name: change default gateway address on Redhat
      replace:
        path: /etc/sysconfig/network-scripts/ifcfg-eth0
        regexp: '(GATEWAY=[d]*.[d]*.[d]*).[d]*$'
        replace: '1.254'
        backup: yes
      when: (ansible_facts['distribution'] == "RedHat")
      register: redresult

and then I added a task to log the changed hosts :


    - name: log the changed hosts
      local_action:
        module : copy
        content: "{{ansible_facts.hostname}}{{debresult}}"
        content: "{{ansible_facts.hostname}}{{redresult}}"
        dest: /tmp/changed.txt

What I am trying to have is a log like this :

debianhostname {"msg": "", "success": true, "changed": true}
redhathostname {"msg": "", "success": true, "changed": true}

But the problem is that I only get the last output so how can have both entries in my file? is there a module that I can use ? I have tried the local_action with copy, set_fact but it did not work.

2

Answers


  1. Chosen as BEST ANSWER

    I managed to find a way to log the task details locally using as much as possible of ansible modules

     - name: log the changed hosts
          local_action:
            module : lineinfile
            line: "{{ ansible_facts['hostname'] }} {{item}}"
            dest: /tmp/changed.txt
          with_items:
            - "{{debresult}}"
            - "{{redresult}}"
    

    And @altair66 suggestion works fine also I get the same result.


  2. copy content will replace the file content with last result in your case. In the following code I used shell module and with_items to redirect to a file on localhost.

     - name: log the changed hosts
       shell: echo "{{ item }}" >> /tmp/changed.txt
       with_items: 
          - "{{ansible_facts.hostname}}{{debresult}}"
          - "{{ansible_facts.hostname}}{{redresult}}"
       delegate_to: "localhost"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search