0

Ansible-playbook has a --list-hosts cli switch that just outputs the hosts affected by each play in a playbook. I am looking for a way to access to same information through the python API.

The (very) basic script I am using to test right now is

#!/usr/bin/python 
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json

# hosts list
hosts = ["127.0.0.1"]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)

pm = ansible.runner.Runner(
    module_name = 'command',
    module_args = 'uname -a',
    timeout = 5,
    inventory = example_inventory,
    subset = 'all' # name of the hosts group 
    )

out = pm.run()

print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

I just can't figure out what to add to ansible.runner.Runner() to make it output affected hosts and exit.

blong
  • 2,815
  • 8
  • 44
  • 110

1 Answers1

0

I'm not sure what are you trying to achieve, but ansible.runner.Runner is actually one task and not playbook.
Your script is a more kind of ansible CLI and not ansible-playbook.
And ansible doesn't have any kind of --list-hosts, while ansible-playbook does.
You can see how listhosts is done here.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • I'm trying to use the ansible python module to get a list of hosts that would be affected by a playbook. Similar to running the playbook with the ansible-playbook command with `--list-hosts`, but I want the data in a more machine readable format (list a list or tuple). – Jason Donahue Aug 01 '16 at 19:19
  • Then you should implement exactly the same functionality as in ansible-playbook CLI (take the code you need and modify it). Unfortunately, there is no handy method ready for you to list affected hosts via some API call. – Konstantin Suvorov Aug 01 '16 at 19:40