ansible通过脚本获取inventory
很多场景下需要通过脚本按需(动态)获取inventory
- 脚本必须实现
--list
和--host <hostname>
两个参数
- 可执行权限
- 结果以
标准输出
输出(返回)
--list: 返回所有的主机组信息
--host : 返回指定主机的变量信息(或空字典)
简单示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #!/usr/bin/python # encoding=utf-8
import sys import json
''' { "_meta": { "hostvars": { "127.0.0.1": { "var1": "value1" } } }, "all": { "children": [ "dev" ] }, "dev": { "hosts": [ "127.0.0.1" ] } } '''
data = {"_meta":{"hostvars":{"127.0.0.1":{"var1":"value1"}}}, "all":{"children":["dev"]}, "dev":{"hosts":["127.0.0.1"]}}
if len(sys.argv) == 2 and (sys.argv[1] == ' print(json.dumps(data))
elif len(sys.argv) == 3 and (sys.argv[1] == ' print(json.dumps(data["_meta"]["hostvars"][sys.argv[2]]))
|
测试
1 2 3 4 5
| root@VM-0-11-ubuntu ~ @all: |--@dev: | |--127.0.0.1 |--@ungrouped:
|
ad-hoc
1 2 3 4
| root@VM-0-11-ubuntu ~ #ansible -i inventory_scripts.py dev -m raw -a 'whoami' 127.0.0.1 | CHANGED | rc=0 >> root Shared connection to 127.0.0.1 closed.
|
playbook
raw-book.yml
1 2 3 4 5 6
| - hosts: dev remote_user: root
tasks: - name: ping test raw: whoami
|
1
| root@VM-0-11-ubuntu ~ #ansible-playbook -i inventory_scripts.py raw-book.yml
|