Skip to content

Instantly share code, notes, and snippets.

@privateip
Created April 26, 2018 19:34
Show Gist options
  • Save privateip/879683a0172415c408fb2afb82a97511 to your computer and use it in GitHub Desktop.
Save privateip/879683a0172415c408fb2afb82a97511 to your computer and use it in GitHub Desktop.
how to use ansible runner programatically
import os
import json
import tempfile
import subprocess
import ansible_runner
def run():
# create an Ansible playbook as a native Python dict object. Currently
# ansible-runner does not validate the playbook structure so it needs to be
# correct when passed in otherwise ansible will fail.
playbook = {
'hosts': 'eos',
'gather_facts': False,
'roles': [{
'name': 'ansible-eos',
'function': 'clear_sessions'
}]
}
# this addes the path endpoints that allow ansible work be run from a
# virtualenv when ansible-runner calls ansible. setting the path is not
# necessary if ansible is installed in system python.
path = '/home/sprygada/Workspaces/ansible/bin:/home/sprygada/.virtualenvs/ansible/bin:'
path += os.environ.get('PATH', '')
# setup various environment vars to be set prior to starting the ansible
# executable. this step is completely optional depending on what needs to
# be done.
envvars = {
'PATH': path,
'PYTHONPATH': '/home/sprygada/Workspaces/ansible/lib:',
'ANSIBLE_ROLES_PATH': '/home/sprygada/Workspaces/roles:',
'ANSIBLE_INVENTORY_PLUGIN_EXTS': '.json'
}
# this is the inventory that ansible will use when the playbook is run.
# this inventory is implemented by the yaml inventory plugin which is
# documented below
# https://docs.ansible.com/ansible/latest/plugins/inventory/yaml.html
hosts = {
'hosts': {
'veos01': {
'ansible_host': 'an-veos-01.ansible.eng.rdu2.redhat.com'
},
'veos02': {
'ansible_host': 'an-veos-02.ansible.eng.rdu2.redhat.com'
}
},
'vars': {
'ansible_python_interpreter': 'python',
'ansible_user': 'ansible',
'ansible_password': 'ansible'
},
'children': {
'eos': {
'vars': {
'ansible_network_os': 'eos',
'ansible_become': True,
'ansible_become_method': 'enable'
},
'hosts': {
'veos01': {},
'veos02': {}
}
}
}
}
# this will pass any extra vars to the ansible command line (same as using
# the -e switch when running ansible manually)
extravars = {
'ansible_connection': 'network_cli'
}
# builds the set of kwargs to pass to ansible-runner. not in this example
# is the use of passwords, ssh_key both of which are supported. see
# https://github.com/ansible/ansible-runner for more details.
kwargs = {
'playbook': [playbook],
'inventory': {'all': hosts},
'envvars': envvars,
'extravars': extravars
}
result = ansible_runner.run(**kwargs)
stdout = result.stdout.read()
events = list(result.events)
stats = result.stats
print json.dumps(stats, indent=4)
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment