簡體   English   中英

Ansible 基本動態庫存

[英]Ansible basic Dynamic Inventory

我嘗試編寫一個基本清單,它從 HOST_VAR 讀取現有的 YAML 文件並生成此模板,我可以使用該模板通過指定的 ansilble_host IP 連接到所有主機:

---

all:
  children:
    routers:
      children:
        PE:
          hosts:
            R1:
              ansible_host: 192.168.99.1
            R3:
              ansible_host: 192.168.99.3
            R4:
              ansible_host: 192.168.99.4
        OSPF:
          hosts:
            R2:
              ansible_host: 192.168.99.2

這是 python 腳本:

#!/usr/bin/env python

import json
import yaml
import glob

groups = {}

for hostfilename in glob.glob('./host_vars/*.yml'):
    with open(hostfilename, 'r') as hostfile:
        host = yaml.load(hostfile)
        for hostgroup in host['host_groups']:
            if hostgroup not in groups.keys():
                groups[ hostgroup ] = { 'hosts': {} }
            groups[ hostgroup ]['hosts'] = { host['host_fqdn'] : { "ansible_host" : host['mgmt_ip'] }}

print(json.dumps(groups))

我總是得到這個錯誤或類似的東西:

[WARNING]:  * Failed to parse /home/sp-user/cisco-config-generator/inventory with script plugin: You defined a group
'PE' with bad data for the host list:  {u'hosts': {u'R1': {u'ansible_host': u'192.168.99.2'}}}
  File "/usr/lib/python2.7/site-packages/ansible/inventory/manager.py", line 280, in parse_source
    plugin.parse(self._inventory, self._loader, source, cache=cache)
  File "/usr/lib/python2.7/site-packages/ansible/plugins/inventory/script.py", line 161, in parse
    raise AnsibleParserError(to_native(e))
[WARNING]:  * Failed to parse /home/sp-user/cisco-config-generator/inventory with yaml plugin: We were unable to read
either as JSON nor YAML, these are the errors we got from each: JSON: No JSON object could be decoded  Syntax Error
while loading YAML.   mapping values are not allowed in this context  The error appears to be in '/home/sp-user/cisco-
config-generator/inventory': line 9, column 51, but may be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:   for hostfilename in glob.glob('./host_vars/*.yml'):
^ here

問題:

誰能給我一個示例,說明如何創建提供上述結果的動態庫存?

這是生成動態庫存的解決方案:

#!/usr/bin/python3

import json
import yaml
import glob

groups = {}

for hostfilename in glob.glob('./host_vars/*.yml'):
    with open(hostfilename, 'r') as hostfile:
        host = yaml.load(hostfile, Loader=yaml.FullLoader)
        for hostgroup in host['host_groups']:
            if hostgroup not in groups.keys():
                groups[ hostgroup ] = { 'hosts': [] }
            groups[ hostgroup ]['hosts'].append( host['hostname'] )

print(json.dumps(groups))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM