Ansible 代码:
---
- hosts: all
gather_facts: no
tasks:
- command: 'docker --version | { read _ _ v _; printf %s\\n "${v%,}"; }'
register: docker_version
- debug: var=hostvars[inventory_hostname].docker_version.stdout
ignore_errors: true
- set_fact:
docker_version: "{{ docker_version.stdout }}"
- name: Display all variables/facts known for a host
debug: var=hostvars[inventory_hostname]
ansible-playbook -i 库存.txt 收集.yml
PLAY [all] *********************************************************************
TASK [command] *****************************************************************
changed: [10.x-hosname]
TASK [debug] *******************************************************************
ok: [10.x-hosname] => {
"hostvars[inventory_hostname].docker_version.stdout": "Docker version 1.12.3, build 34a2ead"
}
TASK [set_fact] ****************************************************************
ok: [10.x-hosname]
TASK [Display all variables/facts known for a host] ****************************
ok: [10.x-hosname] => {
"hostvars[inventory_hostname]": {
"ansible_check_mode": false,
"ansible_version": {
"full": "2.2.1.0",
"major": 2,
"minor": 2,
"revision": 1,
"string": "2.2.1.0"
},
"docker_version": "Docker version 1.12.3, build 34a2ead",
"group_names": [],
"groups": {
"all": [
"10.x-hosname"
],
"ungrouped": []
},
"inventory_dir": "/Users/username/Git/gather",
"inventory_file": "/Users/username/Git/gather/inventory.txt",
"inventory_hostname": "10.x-hosname",
"inventory_hostname_short": "10",
"playbook_dir": ""
}
}
10.x-hosname 是 inventory.txt 中列出的 IP 地址。
我希望此脚本能从多个服务器创建一个 json 清单文件,包括自定义信息,如 docker_version。此脚本最后一条命令的输出正是我希望在 json 文件中看到的输出,但针对的是多个主机。
答案1
制作模板(例如facts.j2
):
[
{% for host in play_hosts %}
{{ hostvars[host] | to_nice_json }}
{% if not loop.last %},{% endif %}
{% endfor %}
]
称之为最后一项任务:
- name: Generate JSON
template:
src: facts.j2
dest: /tmp/facts.json
delegate_to: localhost
run_once: yes