Seksit Yathakarn
Seksit Yathakarn

Reputation: 5

Ansible write result command to local file with loop

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.

For now, I manually create the tasks to write to logs into file. Below is example with 3 commands.

- name: run multiple commands and evaluate the output
  hosts: <<network-host>>
  gather_facts: no
  connection: local

  vars:
    datetime: "{{ lookup('pipe', 'date +%Y%m%d%H') }}"
    backup_dir: "/backup/"

  cli:
    host: "{{ ansible_host }}"
    username: <<username>>
    password: <<password>>

  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

Is it possible to loop commands and result within one task?

Please kindly advice.

Thanks

Upvotes: 0

Views: 4086

Answers (2)

Seksit Yathakarn
Seksit Yathakarn

Reputation: 5

Below playbook is worked for me

- name: Writing output
  local_action:
    module: lineinfile
    dest: "{{ backup_dir }}/{{ inventory_hostname }}-{{ datetime }}.txt"
    line: "{{ inventory_hostname }}:# show {{ item.command }}\n{{ item.cmdoutput}}"
    create: yes
  changed_when: False
  with_items:
    - { command: "version", cmdoutput: "{{ cmd_result.stdout[0] }}" }
    - { command: "system information", cmdoutput: "{{ cmd_result.stdout[1] }}" }
    - { command: "port", cmdoutput: "{{ cmd_result.stdout[2] }}" }

Upvotes: 0

Sai
Sai

Reputation: 166

try this one task alone in place above three tasks..

- name: Writing output
  local_action:
    module: lineinfile
    dest: "{{ backup_dir }}/{{ inventory_hostname }}-{{ datetime }}.txt"
    line: "{{ inventory_hostname }}:# show {{ item.command }}\n{{ cmd_result.stdout{{ item.outnum }} }}"
    create: yes
  changed_when: False
  with_items:
      - { command: version, outnum: [0] }
      - { command: system information, outnum: [1] }
      - { command: port, outnum: [2] }

Upvotes: 2

Related Questions