I want to run Ansible in Python without specifying the inventory file through (ANSIBLE_HOST) but just by:
ansible.run.Runner(
module_name='ping',
host='www.google.com'
)
I can actually do this in fabric easily but just wonder how to do this in Python. On the other hand, documentation of the Ansible API for python is not really complete.
Surprisingly, the trick is to append a
,
or
The host parameter preceding the
,
can be either a hostname or an IPv4/v6 address.You can do this with:
Whatever is in hosts becomes your inventory and you can search it with pattern (or do "all").
This isn't a full answer, but there's some discussion of this topic in this discussion thread. At the end of the first post in that thread, a suggestion is made to create a wrapper bash script for ansible-playbook, which is a bit of a hack but workable.
Other things that I've been considering are the use of 'ansible-pull' and the creation of an ansible inventory plugin. I'm also interested in finding the answer to this question, and I'll keep updating this answer as I find more information.
There seems to be not direct way to give a pattern. This is my hack to solve it.
I know this question is really old but think that this little trick might helpful for future users who need help for this:
if you run for local host:
The trick is that after ip address/dns name, put the comma inside the quotes and requires '
hosts: all
' in your playbook.Hope this will help.
I also needed to drive the Ansible Python API, and would rather pass hosts as arguments rather than keep an inventory. I used a temporary file to get around Ansible's requirement, which may be helpful to others: