通过编写自定义插件来收集Ansible facts
Ansible通过收集facts(事实,数据)来获取主机的信息,这些信息可以在playbook中使用。虽然一些facts的收集是基于操作系统和Python模块的可用性,但有些facts是保证可收集的,例如:
如果需要收集更多的facts,可以编写自定义插件并放置在“library”目录中。
以下是一个例子,演示如何收集自定义facts。该插件名为“custom_facts.py”,并存放在主控机的“library”目录中。
#!/usr/bin/python
# custom_facts.py
import json
import subprocess
def get_custom_fact():
output = subprocess.check_output(['/path/to/custom_script.sh'])
# 解析shell脚本输出为一个字典
custom_fact = json.loads(output)
return custom_fact
# 将自定义fact添加到facts字典中
def main():
custom_fact = get_custom_fact()
facts = {}
if custom_fact:
facts['my_custom_fact'] = custom_fact
print(json.dumps(facts))
if __name__ == '__main__':
main()
然后,在playbook中使用“setup”模块收集facts,并使用自定义的facts:
- name: Collect facts and use custom fact
hosts: all
tasks:
- name: Get facts
setup:
- name: Use custom fact
debug:
var: ansible_local.my_custom_fact
执行playbook时,自定义facts将包含在ansible_local变量中。