title: Ansible write result command to local file with loop
body: <p>I've write ansible-playbook to collect the result from many network devices. Below playbook is working fine. But if I have to collect result with lot of commands. Let say 20 commands, I've to create the many task to write the results into file in my playbook.</p>
  
  <p>For now, I manually create the tasks to write to logs into file. Below is example with 3 commands.</p>
  
  <pre><code>- name: run multiple commands and evaluate the output
    hosts: &lt;&lt;network-host&gt;&gt;
    gather_facts: no
    connection: local
  
    vars:
      datetime: "{{ lookup('pipe', 'date +%Y%m%d%H') }}"
      backup_dir: "/backup/"
  
    cli:
      host: "{{ ansible_host }}"
      username: &lt;&lt;username&gt;&gt;
      password: &lt;&lt;password&gt;&gt;
  
    tasks:
    - sros_command:
       commands:
         - show version
         - show system information
         - show port
       provider: "{{ cli }}"
    register: result
  
  - name: Writing output
    local_action:
      module: lineinfile
      dest: "{{ backup_dir }}/{{ inventory_hostname }}-{{ datetime }}.txt"
      line: "{{ inventory_hostname }}:# show version\n{{ result.stdout[0] }}"
      create: yes
    changed_when: False
  
  - name: Writing output
    local_action:
      module: lineinfile
      dest: "{{ backup_dir }}/{{ inventory_hostname }}-{{ datetime }}.txt"
      line: "{{ inventory_hostname }}:# show system information\n{{ result.stdout[1] }}"
      create: yes
    changed_when: False
  
  - name: Writing output
    local_action:
      module: lineinfile
      dest: "{{ backup_dir }}/{{ inventory_hostname }}-{{ datetime }}.txt"
      line: "{{ inventory_hostname }}:# show port\n{{ cmd_result.stdout[2] }}"
      create: yes
    changed_when: False
  </code></pre>
  
  <p>Is it possible to loop commands and result within one task? </p>
  
  <p>Please kindly advice.</p>
  
  <p>Thanks </p>