可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
Surprisingly, the trick is to append a ,
# Host and IP address
ansible all -i example.com,
ansible all -i 93.184.216.119,
or
# Requires 'hosts: all' in your playbook
ansible-playbook -i example.com, playbook.yml
The host parameter preceding the ,
can be either a hostname or an IPv4/v6 address.
回答2:
I know this question is really old but think that this little trick might helpful for future users who need help for this:
ansible-playbook -i 10.254.3.133, site.yml
if you run for local host:
ansible-playbook -i localhost, --connection=local site.yml
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.
回答3:
You can do this with:
hosts = ["webserver1","webserver2"]
webInventory = ansible.inventory.Inventory(hosts)
webPing = ansible.runner.Runner(
pattern='webserver*',
module_name='ping',
inventory = webInventory
).run()
Whatever is in hosts becomes your inventory and you can search it with pattern (or do "all").
回答4:
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:
from tempfile import NamedTemporaryFile
from ansible.inventory import Inventory
from ansible.runner import Runner
def load_temporary_inventory(content):
tmpfile = NamedTemporaryFile()
try:
tmpfile.write(content)
tmpfile.seek(0)
inventory = Inventory(tmpfile.name)
finally:
tmpfile.close()
return inventory
def ping(hostname):
inventory = load_temporary_inventory(hostname)
runner = Runner(
module_name='ping',
inventory=inventory,
)
return runner.run()
回答5:
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.
回答6:
There seems to be not direct way to give a pattern. This is my hack to solve it.
echo fldn[3789:3799].mysite.com >test; ansible all -i test -m ping