1

Setup/Contraints

I want to run an ansible play located at /tmp/run_tests.yml and I want to perform the run in a python script, not command line (these are general constraints on the problem I am working on). I;ve tried several different approaches which all feel like guess work on reverse engineering the Runner class but have been unsuccessful. I was hoping to find out if this is possible and what the code would look like.

If I want to run a single command I can simply use the Ansible API's runner:

works.py (a simple example of using the Runner with a module)

ansible.runner.Runner(**{
            "pattern": '*',
            "module_name": 'ping',
            "inventory": webInventory,
            "remote_user": self.username,
            "private_key_file": self.private_key
        }).run() 

doesnotwork.py (trying to use runner with a play)

hosts = ["127.0.0.0.1"] #dummy ip address
webInventory = ansible.inventory.Inventory(hosts)

runner = ansible.runner.Runner(pattern="*", )
response = runner.run(**{
    "pattern": '*',
    "module_name": "/tmp/run_tests.yml",
    "inventory": webInventory,
    "remote_user": "ubuntu",
    "private_key_file": "~/.ssh/id_rsa"
})

Error Produced

{'contacted': {}, 'dark': {'127.0.0.1': {'failed': True, 'msg': 'module is missing interpreter line'}}}

From the source, the error suggests a shebang is missing and since I am new to ansible I speculate passing a yml file is not an appropriate file for a module_name. What would the runner command have to look like in order to run my python play?

blong
  • 2,815
  • 8
  • 44
  • 110
Victor 'Chris' Cabral
  • 2,135
  • 1
  • 16
  • 33

1 Answers1

2

I'm sure you've figured this out after 3+ months, but the module_name within an Ansible Runner object should be a module available from Ansible's module index, such as "apt" or "service".

I think you're looking for Ansible's ansible-playbook equivalent, which has its own run class method.

It looks like a working example of running a Playbook programmatically might be here.

You can find examples of the CLI ansible-playbook and how it's used in Ansible's github repository.

Don Branson
  • 13,631
  • 10
  • 59
  • 101
fideloper
  • 12,213
  • 1
  • 41
  • 38