运行ansible-playbook时如何每次生成新输出文件而非覆盖原有文件
调整方法
原配置使用lineinfile模块搭配insertafter: EOF参数,默认行为就是向目标文件末尾追加内容,所以每次运行都会把新输出附加到旧文件中。按以下两步调整即可实现每次运行生成全新独立文件:
- 替换写入模块:将
lineinfile模块更换为copy模块,copy模块会直接把内容写入目标文件,默认覆盖当前路径下的同文件名文件,不会追加内容 - 保证文件名唯一:确保文件名中使用的时间戳变量
DTG每次运行playbook时都会生成最新值,这样不同次运行的输出会存到不同路径/不同文件名的文件中,不会覆盖旧的运行结果
修改后的完整配置示例
- hosts: cpe_4221 gather_facts: False connection: network_cli # 若你已在外部定义了每次运行更新的DTG变量,可删除以下pre_tasks部分 pre_tasks: - name: 生成当前运行时间戳 ansible.builtin.command: date +"%Y%m%d-%H%M%S" register: DTG_result delegate_to: localhost run_once: true - name: 全局赋值DTG变量 ansible.builtin.set_fact: DTG: "{{ DTG_result.stdout }}" delegate_to: localhost run_once: true tasks: - name: show run ios_command: commands: - show platform hardware qfp active datapath utilization - show processes cpu | e 0.00 - show platform software status control-processor brief - show platform hardware qfp active statistics drop - show crypto ipsec sa register: showoutput - name: save output to local directory ansible.builtin.copy: dest: "/tmp/Traffic-Test-4221/{{ DTG }}/{{ inventory_hostname }}-{{ DTG }}-showoutput.txt" content: "{{ showoutput.stdout | join('\n') }}" force: yes delegate_to: localhost
核心调整点说明
- 用
copy模块的content参数直接传入要写入的输出内容,替代原lineinfile的追加逻辑 - 新增的前置任务会在每次playbook运行时生成唯一的时间戳作为DTG变量,不同次运行的输出会存到对应时间戳命名的目录下,完全独立不会互相覆盖
force: yes参数保证同一次运行中如果重复执行写入任务,会直接覆盖本次运行的输出,不会产生追加内容
内容的提问来源于stack exchange,提问作者Joyce A
相关产品推荐
相关产品推荐

