简体   繁体   中英

Need to append output to a file

In the below code will be running repeatedly up-to 8 times, Output will be different each time. I need to save that output in a file without deleting the previously added output to the same file.

But here, it deletes the previous output and adds the new output to that file.

So the output will be only of the last one.

Can you please help me find the solution for this.

  - name: save output to config backup directory
    copy:
      content: " {{ output.stdout[0] }}{{output.stdout[1] }}"
      dest: /home/hhh.ghydggxxxx.xx/paxxxx/playbook-xx/vlan351/port_output/{{inventory_hostname}}.txt
    delegate_to: localhost

You can add the ansible variable: {{ ansible_date_time.epoch }} at the end of filename, in your case, something like:

- name: save output to config backup directory 
  copy: 
    content: "{{ output.stdout[0] }}{{ output.stdout[1] }}" 
    dest: /home/hhh.ghydggxxxx.xx/paxxxx/playbook-xx/vlan351/port_output/{{inventory_hostname}}-{{ ansible_date_time.epoch }}.txt 
  delegate_to: localhost

Or use another "date_time" var:

"ansible_date_time": {"date": "2019-09-05", "day": "05", "epoch": "1567681843", "hour": "13", "iso8601": "2019-09-05T11:10:43Z", "iso8601_basic": "20190905T131043506678", "iso8601_basic_short": "20190905T131043", "iso8601_micro": "2019-09-05T11:10:43.506928Z", "minute": "10", "month": "09", "second": "43", "time": "13:10:43", "tz": "CEST", "tz_offset": "+0200", "weekday": "jueves", "weekday_number": "4", "weeknumber": "35", "year": "2019"}

Try something like this one,

- name: Add contents to a file and appends the data in file
  lineinfile:
    path: /root/testfile
    line: "{{ output.stdout }}"
    create: yes

This task adds the line ie, output.stdout to the file and it always appends data to the file without overwriting the content.

The create special attribute is used to create the file if it is not present.

Configure it according to your use case. I have created the below sample,

- name: save output to config backup directory
  lineinfile:
    line: " {{ output.stdout[0] }}{{output.stdout[1] }}"
    path: "/home/hhh.ghydggxxxx.xx/paxxxx/playbook-xx/vlan351/port_output/{{inventory_hostname}}.txt"
    create: yes
  delegate_to: localhost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM