我是ansible的新手,目前正在进行一项游戏,该游戏将查看远程机器的磁盘空间是否已达到70%的阈值。如果他们已经达到它应该抛出错误。
我找到了一个很好的例子:Using ansible to manage disk space
但在此示例中,安装名称是硬编码的。我的要求是动态传递它们。所以我写下面的代码似乎不起作用:
name: test for available disk space
assert:
that:
- not {{ item.mount == '{{mountname}}' and ( item.size_available <
item.size_total - ( item.size_total|float * 0.7 ) ) }}
with_items: '{{ansible_mounts}}'
ignore_errors: yes
register: disk_free
name: Fail the play
fail: msg="disk space has reached 70% threshold"
when: disk_free|failed
当我使用时,此剧可以使用:
item.mount == '/var/app'
有没有办法动态输入mountname?我可以输入多个装载名称吗?
我在rhel上使用ansible 2.3
提前致谢:)
答案 0 :(得分:4)
试试这个:
name: Ensure that free space on {{ mountname }} is grater than 30%
assert:
that: mount.size_available > mount.size_total|float * 0.3
msg: disk space has reached 70% threshold
vars:
mount: "{{ ansible_mounts | selectattr('mount','equalto',mountname) | list | first }}"
that
是一个原始的Jinja2表达式,不要在其中使用大括号。
如果fail
因邮件失败,您为什么要使用单独的assert
任务?
答案 1 :(得分:2)
我正在运行Ansible 2.5,并且能够通过添加with_items
来获得Konstantin Suvorov's解决方案以使用一个稍微的mod。下面的示例代码:
- name: Ensure that free space on the tested volume is greater than 15%
assert:
that:
- mount.size_available > mount.size_total|float * 0.15
msg: Disk space has reached 85% threshold
vars:
mount: "{{ ansible_mounts | selectattr('mount','equalto',item.mount) | list | first }}"
with_items:
- "{{ ansible_mounts }}"
答案 2 :(得分:1)
对于无法使用selectattr
的用户(如我),这是使用when
和with_items
选择要检查的挂载点的第一个答案的变体。
name: 'Ensure that free space on {{ mountname }} is grater than 30%'
assert:
that: item.size_available > item.size_total|float * 0.3
msg: 'disk space has reached 70% threshold'
when: item.mount == mountname
with_items: '{{ ansible_mounts }}'
注意:要使用变量{{ ansible_mounts }}
,您需要将gather_facts
更改为yes
,该变量可以限制为gather_subset=!all,hardware
。