Question: I want to execute ansible playbook through python script, also implement ansible vault integration Objective: create a function that can take inventory and playbook parameter
I want to execute ansible playbook through python script, also implement ansible vault integration Objective: create a function that can take inventory and playbook parameter and excute it. Ansible has already provide the sample script for this https://docs.ansible.com/ansible/latest/dev_guide/developing_api.html ansible vault implementation required, setup the use and execution https://ansible-docs.readthedocs.io/zh/stable-2.0/rst/developing_api.html all status, up down failed should be capture and documented textfsm integration required to parse the output from the devices https://docs.ansible.com/ansible/latest/network/user_guide/cli_parsing.html I attach some Python files, these could be used for completing the script.
1.) import ansible.runner.py
import ansible.runner import ansible.playbook from ansible import constants as C def run_ansible_playbook(inventory, playbook, vault_password=None): # Set options for the playbook run options = { 'forks': C.DEFAULT_FORKS, 'become': None, 'become_method': None, 'become_user': None, 'check': False, 'diff': False, } if vault_password: options['vault_password'] = vault_password # Create a Playbook object pb = ansible.playbook.PlayBook( playbook=playbook, inventory=inventory, options=options, runner_callbacks={'on_stats': callback} ) # Execute the playbook result = pb.run() # Print the status of the playbook run print("Playbook status: {}".format(result)) 2.) example-ansible.py
from ansible.executor.playbook_executor import PlaybookExecutor from textfsm import TextFSM import subprocess inventory = 'path to your inventory' playbook = 'playbook.yml' # Create a PlaybookExecutor object pbex = PlaybookExecutor(playbooks=[playbook], inventory=inventory) pbex.run() # Encrypt a file using ansible-vault output = subprocess.run(['ansible-vault', 'encrypt', '/path/to/file.txt']) # Define the template for the output template = ''' Value required_value etc..- (\S+) ''' fsm = TextFSM(template) # Parse the output using the TextFSM object results = fsm.ParseText(output) print(results)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
