我需要一些有关此剧本的帮助。我使用断言模块断言磁盘空间小于 30%,并发送带有失败消息的松弛通知。 Assert模块循环遍历服务器中的所有FS(大约10个FS)。 slack 上发送的消息不符合预期。我想要实现的只是仅显示循环中失败的项目。仅显示断言失败项的消息。
tasks:
- name:
assert:
that: "{{ item.size_available > item.size_total | float * 0.30 }}"
msg: "Filesystem: {{ item.mount }} has less than 30% space. Consider increasing the FS size"
#success_msg: "Filesystem: {{ item.mount }} has more than 30% space. No action required"
register: fs_space
loop: "{{ ansible_mounts }}"
loop_control:
label: ""
ignore_errors: true
- debug:
msg: "HOST {{ ansible_hostname }}: {{ fs_space.results | json_query('[*].msg') }}
when: true in fs_space.results | json_query('[*].failed')
最终结果如下所示:
HOST XYZ: [u'All assertions passed', u'All assertions passed', u'All assertions passed', u'All assertions passed', u'All assertions passed', u'Filesystem: /usr has less than 30% space. Consider increasing the FS size', u'All assertions passed', u'All assertions passed', u'All assertions passed', u'All assertions passed']
但我需要的消息只是这样:
HOST XYZ: Filesystem: /usr has less than 30% space. Consider increasing the FS size'
答案1
问:”如果任何安装点无法满足断言,我希望任务终止。”
答:简化条件。例如
shell> cat playbook.yml
- hosts: localhost
vars:
my_mounts: [500, 600,700]
tasks:
- assert:
that: mounts_all == mounts_ok
vars:
mounts_all: "{{ my_mounts|length }}"
mounts_ok: "{{ my_mounts|select('gt', 400)|length }}"
给出
TASK [assert] ******************************************************
ok: [localhost] => {
"changed": false,
"msg": "All assertions passed"
}
如果您不想显示结果,请将回调静音。例如
shell> ANSIBLE_DISPLAY_OK_HOSTS=false ansible-playbook playbook.yml
有关回调的详细信息,请参见
shell> ansible-doc -t callback default
如果其中任何一项不满足条件,游戏就会失败。例如
- assert:
that: mounts_all == mounts_ok
vars:
mounts_all: "{{ my_mounts|length }}"
mounts_ok: "{{ my_mounts|select('gt', 600)|length }}"
给出
TASK [assert] *******************************************************
fatal: [localhost]: FAILED! => {
"assertion": "mounts_all == mounts_ok",
"changed": false,
"evaluated_to": false,
"msg": "Assertion failed"
}
问:”仅显示断言失败项的消息。”
A:如果要显示失败的挂载点,请添加调试任务。例如
- hosts: localhost
vars:
my_mounts:
- {dev: da0, size: 500}
- {dev: da1, size: 600}
- {dev: da2, size: 700}
tasks:
- debug:
msg: >
Filesystems: {{ mounts_fail }} failed.
Consider increasing the FS size.
when: mounts_fail|length > 0
vars:
mounts_fail: "{{ my_mounts|
selectattr('size', 'lt', 600)|
map(attribute='dev')|list }}"
- assert:
that: mounts_all == mounts_ok
vars:
mounts_all: "{{ my_mounts|length }}"
mounts_ok: "{{ my_mounts|
selectattr('size', 'gt', 600)|length }}"
给出
TASK [debug] *******************************************************
ok: [localhost] => {
"msg": "Filesystems: ['da0'] failed. Consider increasing the FS size.\n"
}
TASK [assert] ******************************************************
fatal: [localhost]: FAILED! => {
"assertion": "mounts_all == mounts_ok",
"changed": false,
"evaluated_to": false,
"msg": "Assertion failed"
}