1
votes

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))
3
Run ansible-inventory -i script.py --list -vvv, it will tell you which plugin Ansible is using and provide additional information about the decisions it makes. It should be using the script plugin.Steve E.
Thanks @SteveE.for the hint. I updated the question with more output. I thought I would be fine with returned JSON format which Ansible would be able to parseEagleDev
enable_plugins = script can't be what your Ansible is using. The output clearly shows the host_list, yaml and other plugins are being tried. However it doesn't list the script plugin which is unexpected. The defaults are hereSteve E.
@SteveE.updated the output. Seems to be related to cache which I doubt.EagleDev

3 Answers

2
votes

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

#!/path/to/python
0
votes

Your script needs to be executable:
$ chmod a+x script.py

See docs about using scripts here.

Your script must also accept certain arguments.

0
votes

You need to run the command like this

ansible-inventory -i 'path-to-the-file/script.py' --list

Is important to have the quotation marks. On OsX for me this was the problem.