Ansible-将输出写入CSV文件时出现问题

时间:2020-09-03 12:16:10

标签: ansible

Ansible版本-2.9

在将输出写入到csv文件时遇到问题,它不能将输出一致地写入文件。

脚本具有一个包含三个服务器IP的清单文件,它将执行命令以检查每个服务器的磁盘空间并将输出写入csv文件。

有时将所有三个服务器详细信息写入文件,有时仅将一个或两个服务器详细信息写入文件。

  - hosts: localhost
    connection: local
    gather_facts: False
    vars:
      filext: ".csv"
    tasks:
      - name: get the username running the deploy
        local_action: command whoami
        register: username_on_the_host

      - name: get current dir
        local_action: command pwd
        register: current_dir

      - name: create dir
        file: path={{ current_dir.stdout }}/HCT state=directory

      - name: Set file path here
        set_fact:
            file_path: "{{ current_dir.stdout }}/HCT/HCT_check{{ filext }}"

      - name: Creates file
        file: path={{ file_path }}  state=touch

# Writing to a csv file

    - hosts:
      - masters
    become: false
    vars:
      disk_space: "Able to get disk space for the CM {{ hostname }} "
      disk_space_error: "The server {{ hostname  }} is down for some reason. Please check manually."
      disk_space_run_status: "{{disk_space}}"
      cur_date: "{{ansible_date_time.iso8601}}"

    tasks:
      - name: runnig command to get file system which are occupied 
        command: bash -c "df -h | awk '$5>20'"
        register: disk_space_output
        changed_when: false
        ignore_errors: True
        no_log: True

      - name: Log the task get list of file systems with space occupied 
        lineinfile:
           dest: "{{ hostvars['localhost']['file_path'] }}"
           line: "File system occupying disk space, {{ hostname }}, {{ ip_address }}, {{ cur_date }}"
           insertafter: EOF
           state: present
        delegate_to: localhost

请帮助解决此问题。

1 个答案:

答案 0 :(得分:0)

问题在于,这3台服务器并行执行了“记录任务占用空间的文件系统的任务列表”任务,因此您遇到了并发写入问题。

一种解决方案是在播放级别使用serial值的1关键字,这样,所有任务将一次为每个服务器执行。

- hosts:
  - masters
become: false
serial: 1
vars:
[...]

另一种解决方案是仅对一台服务器执行任务,但使用hostvars遍历所有服务器的结果:

  - name: Log the task get list of file systems with space occupied 
    lineinfile:
       dest: "{{ hostvars['localhost']['file_path'] }}"
       line: "File system occupying disk space, {{ hostvars[item].hostname }}, {{ hostvars[item].ip_address }}, {{ hostvars[item].cur_date }}"
       insertafter: EOF
       state: present
    run_once: True
    loop: "{{ ansible_play_hosts }}"  # Looping over all hosts of the play
    delegate_to: localhost