Unable to parse inventory script as an inventory

ansibleansible-2.xansible-inventory

My python script dynamically queries and generates a JSON file as follows:

{
    "all": {
      "hosts": [
        "192.158.1.1"
      ], 
      "vars": {
        "ansible_become_method": "sudo", 
        "ansible_become": "yes"
      }
    }
  }

But somehow when I execute the command below

ansible -i script.py -m ping 

it gives out the following warning messages

  • [WARNING] Unable to parse /etc/ansible/script.py as an inventory source
  • [WARNING] No inventory was parse, only implicit localhost is available.
  • [WARNING] provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

I don't know what I'm missing or wrong as I'm new to dynamic inventory with Ansible.

When I run ansible-inventory -i script.py --list I got the following response

{
    "_meta": {
        "hostvars": {}
    }, 
    "all": {
        "children": [
            "ungrouped"
        ]
    }, 
    "ungrouped": {}
}

My Ansible version is 2.7.7

Inventory plugin is script

enable_plugins = script

[Updated] Running -v based on Steve's suggestion gives me a bit more

 [WARNING]:  * Failed to parse /etc/ansible/newhost.py with script plugin: failed to parse executable inventory script results from /etc/ansible/script.py: Syntax
Error while loading YAML.   mapping values are not allowed in this context  The error appears to have been in '<string>': line 3, column 8, but may be elsewhere in the
file depending on the exact syntax problem.


 File "/usr/lib/python2.7/site-packages/ansible/plugins/inventory/script.py", line 125, in parse
    raise AnsibleError("failed to parse executable inventory script results from {0}: {1}\n{2}".format(path, to_native(e), err))

Best Answer

Have you added a header like this in the very first line of your python inventory script?

#!/path/to/python
Related Topic