我在一个在各种服务器上安装更新的 ansible 脚本中使用以下任务。这些任务适用于 CentOS 机器:
- name: Check for outstanding reboot
shell: needs-restarting > /dev/null || echo Reboot required
when: ansible_distribution_major_version|int < 7
register: result
- name: Check for outstanding reboot
shell: needs-restarting -r > /dev/null || echo Reboot required
when: ansible_distribution_major_version|int >= 7
register: result
- name: Report reboot
debug: msg="{{ result.stdout_lines }}"
结果:
TASK [Check for outstanding reboot] ***********************************************************************************
skipping: [host1]
skipping: [host2]
skipping: [host5]
changed: [host3]
changed: [host4]
TASK [Check for outstanding reboot] ***********************************************************************************
skipping: [host3]
skipping: [host4]
changed: [host2]
changed: [host1]
changed: [host5]
TASK [Report reboot] **************************************************************************************************
fatal: [host3]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout_lines'\n\nThe error appears to have been in '/path/to/updates.yml': line 52, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n register: result\n - name: Report reboot\n ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'dict object' has no attribute 'stdout_lines'"}
ok: [host1] => {
"msg": [
"Reboot required"
]
}
fatal: [host4]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout_lines'\n\nThe error appears to have been in '/path/to/updates.yml': line 52, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n register: result\n - name: Report reboot\n ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'dict object' has no attribute 'stdout_lines'"}
ok: [host2] => {
"msg": [
"Reboot required"
]
}
ok: [host5] => {
"msg": [
"Reboot required"
]
}
to retry, use: --limit @/path/to/updates.retry
如您所见,两个检查任务都将结果存储在一个名为“result”的变量中,但只有第二个任务中的主机变量(带有ansible_distribution_major_version|int >= 7
)被填充,从而导致错误消息。似乎第二个检查任务取消了前一个任务的结果。
是否可以保留两个任务的结果?还是我必须复制报告任务并将版本检查添加到两者?我宁愿把报告放在一个地方。
Ansible 版本是 2.4.4.0
发生这种情况是因为即使任务被跳过,Ansible 也会存储结果:
Ansible 注册变量用户指南
因此,不,不可能保留这两个任务的结果。
正如您已经建议的那样,我会复制报告任务并将版本检查添加到两者。