我试图将每台目标主机的几行打印到文件中。但是,文件中缺少这些行。这意味着,我的主机列表文件大约有 10 台服务器。有时我只得到 8 行或 6 行等等。有关主机的缺失行完全是随机的。以下是代码中的几行,Redhatx.Kernel
来自 vars_file。
当我检查时,详细模式确实显示了为缺失主机添加的一行。想知道我遗漏了什么,有什么预感吗?
- name: Run patch status check
set_fact:
patch_state: success
when:
- ansible_distribution == "RedHat"
- (facter_kernelrelease == "{{ Redhat6.Kernel }}" or
facter_kernelrelease == "{{ Redhat7.Kernel }}" or
facter_kernelrelease == "{{ Redhat8.Kernel }}")
register: result
- name: Patch status
set_fact:
patch_state: Failed
when: result is skipped
- name: CSV - Get the facts
set_fact:
csv_tmp: >
{{ ansible_fqdn }},{{ ansible_distribution }},{{ ansible_distribution_version }},{{ patch_state }}
- name: CSV - Write information into .csv file
lineinfile:
insertafter: EOF
dest: "{{ output_path }}/{{ filename }}"
line: "{{ csv_tmp }}"
state: present
delegate_to: localhost
答案1
避免并发写入文件。还有更多选项。
- 最简单的方法是设置风门至 1. 例如,
- name: CSV - Write information into .csv file
lineinfile:
insertafter: EOF
dest: "{{ output_path }}/{{ filename }}"
line: "{{ _line|join(',') }}"
state: present
delegate_to: localhost
throttle: 1
vars:
_line:
- "{{ ansible_fqdn }}"
- "{{ ansible_distribution }}"
- "{{ ansible_distribution_version }}"
- "{{ patch_state }}"
- 更有效的选择是仅运行一次任务并迭代ansible_play_hosts。 例如,
- name: CSV - Write information into .csv file
lineinfile:
insertafter: EOF
dest: "{{ output_path }}/{{ filename }}"
line: "{{ _line|join(',') }}"
state: present
loop: "{{ ansible_play_hosts }}"
delegate_to: localhost
run_once: true
vars:
_line:
- "{{ hostvars[item]['ansible_fqdn'] }}"
- "{{ hostvars[item]['ansible_distribution'] }}"
- "{{ hostvars[item]['ansible_distribution_version'] }}"
- "{{ hostvars[item]['patch_state'] }}"