Created
October 8, 2021 15:46
-
-
Save cidrblock/6d38eac868f5e08c182fa8efb8cca893 to your computer and use it in GitHub Desktop.
Sample runner code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ Sample runner script | |
| """ | |
| import datetime | |
| import os | |
| from typing import Dict | |
| from typing import List | |
| import ansible_runner | |
| class Ansible: | |
| """the ansible wrapper class""" | |
| def __init__(self): | |
| self._inventory: Dict = {} | |
| self._playbook: List = [] | |
| def generate_inventory(self) -> None: | |
| """Generate an inventory""" | |
| hosts: Dict = {"nxos101": {}, "nxos102": {}} | |
| ivars = { | |
| "ansible_user": "admin", | |
| "ansible_password": "password", | |
| "ansible_connection": "ansible.netcommon.network_cli", | |
| "ansible_network_os": "nxos", | |
| "ansible_python_interpreter": "python", | |
| "ansible_become": True, | |
| "ansible_become_method": "ansible.netcommon.enable", | |
| "ansible_become_pass": "password", | |
| } | |
| inventory = {"all": {"hosts": hosts, "vars": ivars}} | |
| self._inventory = inventory | |
| @staticmethod | |
| def _generate_play_1_tasks() -> List: | |
| """Generate the tasks for play 1""" | |
| play_1_tasks = [ | |
| { | |
| "name": "Run a module", | |
| "cisco.nxos.interfaces": {"state": "gathered"}, | |
| "register": "output", | |
| }, | |
| {"name": "Show the result", "debug": {"var": "output"}}, | |
| ] | |
| return play_1_tasks | |
| def _generate_play_1(self) -> Dict: | |
| """Generate a play""" | |
| play = { | |
| "hosts": "all", | |
| "gather_facts": False, | |
| "tasks": self._generate_play_1_tasks(), | |
| } | |
| return play | |
| def generate_playbook(self) -> None: | |
| """Generate a playbook""" | |
| self._playbook = [self._generate_play_1()] | |
| def run(self) -> None: | |
| """run the playbook""" | |
| timestamp = datetime.datetime.now().astimezone().isoformat() | |
| dir_path = abs_user_path(f"./ansible_jobs/{timestamp}") | |
| try: | |
| os.makedirs(dir_path) | |
| except FileExistsError: | |
| pass | |
| ansible_runner.run( | |
| private_data_dir=dir_path, | |
| inventory=self._inventory, | |
| playbook=self._playbook, | |
| ) | |
| def abs_user_path(fpath: str) -> str: | |
| """Resolve a path""" | |
| return os.path.abspath(os.path.expanduser(os.path.expandvars(fpath))) | |
| if __name__ == "__main__": | |
| ansible = Ansible() | |
| ansible.generate_inventory() | |
| ansible.generate_playbook() | |
| ansible.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment