How to run ansible module in python

Question:

Here is my code:
I am not able to run a ansible module using python.
How to pass a inventory file for which this command is running. I am not able to run it for my inventory.
Do I need to do something else ?
Here is my ansible command:

ansible all -i /home/ubuntu/extra -m 'debug' -a 'var=hostvars' 

Here is my code:

import json
import ansible.runner
import ansible.playbook
import ansible.inventory

hosts = ["10.12.11.101"]
example_inventory = ansible.inventory.Inventory(hosts)
pm = ansible.runner.Runner( module_name = 'debug', module_args = 'vars=hostvars', timeout = 5, inventory = example_inventory, subset = 'all')
out = pm.run()
print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))
Asked By: kohi

||

Answers:

You can pass the inventory file path to ansible.runner.Runner()

And for getting group-names and host-names , you should pass var=hostvars, not vars=hostvars

Your code would look like this,

import json
import ansible.runner
import ansible.playbook
import ansible.inventory

example_inventory = ansible.inventory.Inventory('path/to/your/inventory')
pm = ansible.runner.Runner( module_name = 'debug', module_args = 'var=hostvars', timeout = 5, inventory = example_inventory, subset = 'all')
out = pm.run()
print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

and your output

{'contacted': {'ip-address': {'invocation': {'module_args': u'var=hostvars',
    'module_complex_args': {},
    'module_name': 'debug'},
   'var': {u'hostvars': {'group_names': ['group1', 'group2', 'group3'],
     'groups': {'group1': ['ip-address'],
      'all': ['ip-address'],
      'group2': ['ip-address'],
      'group3': ['ip-address'],
      'ungrouped': []},
     'inventory_hostname': 'ip/hostname',
     'inventory_hostname_short': 'hostname-short'}},
   'verbose_always': True}},
 'dark': {}}
Answered By: frank

Nowadays, it is best to go through the ansible_runner package, (https://github.com/ansible/ansible-runner), instead of importing ansible directly. See my answer to Running ansible-playbook using Python API for a complete example.

Answered By: user7610
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.