如何将失败模块的输出发送到文件

how to send output of fail module to file

我有以下部分用于 ansible fail 模块我想将此模块的输出重定向到文件

     - name:
       fail:
         msg: "SVRELOAD NOT DONE ON THIS PTS {{ ansible_hostname }}"
       when: last_restart_date.stdout != ansible_date_time.date
       register: failed_task

这是我的做法(有点不同的方法)。只是为了演示解决方案,我尝试下载一个不存在的包。我捕获了该消息,并写入了一个文件。你将不得不用格挡和救援来调整你的剧本。

剧本(带方块,救援)

---
- name: writing error to a file
  hosts: localhost
  become: true
  tasks:
  - name: block to create block-rescue-always
    block:
    - name: this module intentionally fails
      yum: name=does_not_exist state=latest
      register: failed_msg
    rescue:
    - name: write the error to a file
      debug: msg="failed with yum block"
    - name: create an error file
      file:
        path: /home/user1/ansible/error-msg.txt
        owner: user1
        group: user1
        mode: '0755'
        state: touch

    - name: write to a file with lineinfile
      lineinfile:
        path: /home/user1/ansible/error-msg.txt
        line: "{{ failed_msg }}"

这是文件中的响应 error-msg.txt

{'msg': "No package matching 'does_not_exist' is available", 'failed': True, 'changed': False, 'ansible_facts': {'pkg_mgr': 'apt'}}

如果您的错误文件已存在且具有写入权限,则您无需创建新文件。