title: Ansible basic Dynamic Inventory
body: <p>I try to code a basic Inventory, which reads the exsiting YAML files from HOST_VAR and generate this template, which I can use to connect to all the host via the specified ansilble_host IP:</p>
  <pre><code>---
  
  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
  </code></pre>
  <p>This is the python script:</p>
  <pre><code>#!/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'] : { &quot;ansible_host&quot; : host['mgmt_ip'] }}
  
  print(json.dumps(groups))
  </code></pre>
  <p>I always got this error or something similar:</p>
  <pre><code>[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 &quot;/usr/lib/python2.7/site-packages/ansible/inventory/manager.py&quot;, line 280, in parse_source
      plugin.parse(self._inventory, self._loader, source, cache=cache)
    File &quot;/usr/lib/python2.7/site-packages/ansible/plugins/inventory/script.py&quot;, 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
  </code></pre>
  <p>Question:</p>
  <p>Can anyone give me an example of how to create a dynamic inventory that provides the above results?</p>