python Dynamic Inventory won't work: it is interpreted as a .ini file

Hi,

I’m trying the simplest possible example of a Dynamic Inventory but it won’t work: my hosts.py file gets interpreted as a .ini file:

$ ansible-playbook -i hosts.py play.yml
ERROR: Invalid ini entry: sys - need more than 1 value to unpack

Here is the dynamic inventory hosts.py:

import sys
import json

if len(sys.argv) == 2 and (sys.argv[1] == ‘–list’):
inventory={}
inventory[‘local’] = [ ‘127.0.0.1’ ]
print json.dumps(inventory, indent=4)
elif len(sys.argv) == 3 and (sys.argv[1] == ‘–host’):
print ‘{}’
else:
print “Usage: %s --list or --host ” % sys.argv[0]
sys.exit(1)

I’m pretty sure that it returns what it should. It’s a much simpler example of the one shown there.

And the playbook play.yml could not be simpler:

  • hosts: all
    connection: local
    tasks:
  • name: Can I run this playbook?
    debug: msg=“Yes!”

The playbook works when I run it playbook locally with this command:

$ ansible-playbook -i 127.0.0.1, play.yml

[output not copied here - it’s all fine]

I am stuck there.
What am I doing wrong with my dynamic inventory?
How can I get it to be evaluated as a python file, rather than a .ini file?

Sounds like you forgot to

chmod +x hosts.py

Similarly, don’t forget the shebang line at the top of your inventory script. e.g. '#!/usr/bin/env python`

Oh so silly of me, thank you Serge and Scott ! Now it works.

Perhaps these info could be added to this documentation page:
http://docs.ansible.com/developing_inventory.html
I could submit a pull request for that.

And now my more complex dynamic inventory works. Easy peasy, cheers! I’m loving Ansible :slight_smile: