如何使用ad-hoc命令过滤nocache
块或free
块?我试过ansible centos1 -m setup -a 'filter=ansible_memory_mb.nocache'
,但没有过滤掉。
ansible centos1 -m setup -a 'filter=ansible_memory_mb'
centos1 | SUCCESS => {
"ansible_facts": {
"ansible_memory_mb": {
"nocache": {
"free": 11808,
"used": 926
},
"real": {
"free": 10686,
"total": 12734,
"used": 2048
},
"swap": {
"cached": 0,
"free": 4096,
"total": 4096,
"used": 0
}
},
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": false
}
如果你想尝试使用ansible命令,你必须混合使用grep和head:
ansible centos -m setup -a 'filter=ansible_memory_mb' | grep -Eo [0-9]+ | head -1
,但你应该使用playbook: var结果将包含所需的值。
- name: test
hosts: centos1
tasks:
- name: set vars
set_fact: result="{{ ansible_memory_mb.nocache.free}}"
- name: show
debug:
var: result
结果:
TASK [show] ***********************************************************************************************************************************************************************
ok: [localhost] => {
"result": "712"
}
几个月前有同样的问题,但答案是,如果您需要访问特定的内部块,您需要使用Ansible Playbook,不幸的是,您不能使用ad-hoc命令。例如在您的本地主机的日期时间:
ansible -m setup localhost -a 'filter=ansible_date_time'
将返回许多特定信息,如秒、年、分钟等。如果你想只返回格式日期,如'2021-10-16',你需要使用playbook。这里有一些特定的剧本来创建一个日期特定格式的文件夹:
tasks:
- name: Collect Year, Month and Day.
setup:
filter: "ansible_date_time"
gather_subset: "!all"
- name: Put today's date in a variable.
set_fact:
DTG: "{{ ansible_date_time.date }}"
- name: Create directory with the following path C:bkp_"year-month-day"Switches
file:
path: /mnt/c/bkp_{{ hostvars.localhost.DTG }}/Switches/
state: directory
我不知道如果没有操纵脚本是否可用。对于一个快速的解决方案,您可以在下面运行特设命令
ansible centos -m setup -a 'filter=ansible_memtotal_mb'
ansible centos -m setup -a 'filter=ansible_memfree_mb'
引自文档:
这个模块被剧本自动调用来收集关于远程主机的有用变量,这些变量可以在剧本中使用。它也可以由
/usr/bin/ansible
直接执行,以检查主机可用的变量。
不同的参数,如subset
,filter
,限制从主机收集的信息。这些数据存储在ansible_facts
字典中。
最重要的是:
过滤器选项只过滤ansible_facts以下的第一级子键
虽然,当setup
模块从playbook(或作为gather_facts: true
)运行时,我们可以访问事实及其子键/元素,因为它的作为变量可用。
# play.yml
- hosts: "{{ my_hosts }}"
gather_facts: false
tasks:
- name: filter memory facts
setup:
filter: ansible_memory_mb
# note that an intermediate set_fact task is not required as such
- name: show memory nocache values
debug:
var: ansible_memory_mb.nocache
然后运行它而不是ad-hoc命令(在centos1
上):
ansible-playbook play.yml -e "my_hosts=centos1" -i <inventory-path>