Instructions for using Python 3 to call ansible API

Time:2020-8-2

Install ansible module in Python 3

pip3 install ansible

pip3 install ansible_runner

pip3 install ansible_inventory

pip3 install ansible_playbook

Instructions for using Python 3 to call ansible API

Get the official instance and modify it

https://docs.ansible.com/ansible/latest/dev_guide/developing_api.html

Instructions for using Python 3 to call ansible API

Core class introduction

Full import classpath Functional use
from ansible.module_utils.common.collections import ImmutableDict Use to add options. For example: specify remote user remote_ user=None
from ansible.parsing.dataloader import DataLoader Data parser for reading files in JSON / ymal / ini format
from ansible.vars.manager import VariableManager Variable manager for managing hosts and host groups
from ansible.inventory.manager import InventoryManager To manage the repository, you can specify an inventory file, etc
from ansible.playbook.play import Play The class used to execute ad hoc needs to pass in the corresponding parameters
from ansible.executor.task_queue_manager import TaskQueueManager Task queue manager used in ansible
ansible.plugins.callback.CallbackBase Process the status returned after task execution
from ansible import context Context manager, which is the sample object used to receive immutabledict
import ansible.constants as C Used to get temporary documents generated by ansible.
from ansible.executor.playbook_executor import PlaybookExecutor Executing the core class of Playbook
from ansible.inventory.host import Group YesHost groupExecute operation, you can add variables to the group and other operations, expand
from ansible.inventory.host import Host YeshostExecute operations, you can add variables to the host and other operations, expand
[[email protected] shell]# cat ansible2.py   
import json  
import shutil  
from ansible.module_utils.common.collections import ImmutableDict  
from ansible.parsing.dataloader import DataLoader  
from ansible.vars.manager import VariableManager  
from ansible.inventory.manager import InventoryManager  
from ansible.playbook.play import Play  
from ansible.executor.task_queue_manager import TaskQueueManager  
from ansible.plugins.callback import CallbackBase  
from ansible import context  
import ansible.constants as C

  
class ResultCallback(CallbackBase):  
    """  
    Override partial methods of callbackbase class  
    """  
    def __init__(self, *args, **kwargs):  
        super().__init__(*args, **kwargs)  
        self.host_ok = {}  
        self.host_unreachable = {}  
        self.host_failed = {}  
        self.task_ok = {}  
    def v2_runner_on_unreachable(self, result):  
        self.host_unreachable[result._host.get_name()] = result

    def v2_runner_on_ok(self, result, **kwargs):  
        self.host_ok[result._host.get_name()] = result

    def v2_runner_on_failed(self, result, **kwargs):  
        self.host_failed[result._host.get_name()] = result

class MyAnsiable2():  
    def __init__(self,  
        Connection = local, local, smart SSH  
        remote_ User = none, ා SSH user  
        remote_ Password = none, the password of SSH user should be a dictionary, and the key must be Conn_ pass  
        private_ key_ File = none, ා specifies the user-defined private key address  
        sudo=None, sudo_user=None, ask_sudo_pass=None,  
        module_ Path = none, ා module path. You can specify the path of a custom module  
        Come = none  
        become_ Method = none, sudo can be su by default  
        become_ User = none, the user you want to become is not the login user  
        check=False, diff=False,  
        listhosts=None, listtasks=None,listtags=None,  
        verbosity=3,  
        syntax=None,  
        start_at_task=None,  
        inventory=None):

        #Function documentation comments  
        """  
        Initialization function, defined default option value,  
        Parameters can be passed during initialization to override the value of the default option  
        """  
        context.CLIARGS = ImmutableDict(  
            connection=connection,  
            remote_user=remote_user,  
            private_key_file=private_key_file,  
            sudo=sudo,  
            sudo_user=sudo_user,  
            ask_sudo_pass=ask_sudo_pass,  
            module_path=module_path,  
            become=become,  
            become_method=become_method,  
            become_user=become_user,  
            verbosity=verbosity,  
            listhosts=listhosts,  
            listtasks=listtasks,  
            listtags=listtags,  
            syntax=syntax,  
            start_at_task=start_at_task,  
        )

        #For ternary expression, if inventory is not passed, use "localhost,"  
        #Specify inventory file  
        #The value of inventory can be an asset list file  
        #It can also be a tuple containing the host, which is only applicable to tests  
        #For example: 1.1.1.1, ා if there is only one IP address, there must be a comma in English  
        #Or: 1.1.1.1, 2.2.2.2

        self.inventory = inventory if inventory else "localhost,"

        #Instantiation data parser  
        self.loader = DataLoader()

        #Instantiate asset configuration object  
        self.inv_obj = InventoryManager(loader=self.loader, sources=self.inventory)

        #Set password  
        self.passwords = remote_password

        #Instantiate callback plug-in object  
        self.results_callback = ResultCallback()

        #Variable Manager  
        self.variable_manager = VariableManager(self.loader, self.inv_obj)

    def run(self, hosts='localhost', gether_facts="no", module="ping", args='', task_time=0):  
        """  
        Parameter Description:  
        task_ Time -- the number of seconds to wait when executing an asynchronous task. This should be greater than 0. If it is equal to 0, asynchrony is not supported (default value). This value should be equal to the actual time taken to execute the task  
        """  
        play_source =  dict(  
            name = "Ad-hoc",  
            hosts = hosts,  
            gather_facts = gether_facts,  
            tasks = [  
                #Here, each task is an element in the list in the form of a nested dictionary  
                #It can also be passed as a parameter, which is simplified here.  
               {"action":{"module": module, "args": args}, "async": task_time, "poll": 0}])

        play = Play().load(play_source, variable_manager=self.variable_manager, loader=self.loader)

        tqm = None  
        try:  
            tqm = TaskQueueManager(  
                      inventory=self.inv_obj ,  
                      variable_manager=self.variable_manager,  
                      loader=self.loader,  
                      passwords=self.passwords,  
                      stdout_callback=self.results_callback)

            result = tqm.run(play)  
        finally:  
            if tqm is not None:  
                tqm.cleanup()  
            shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    def playbook(self,playbooks):  
        """  
        Keyword arguments:  
        A playbooks -- need a list  
        """  
        from ansible.executor.playbook_executor import PlaybookExecutor

        playbook = PlaybookExecutor(playbooks=playbooks,  
                        inventory=self.inv_obj,  
                        variable_manager=self.variable_manager,  
                        loader=self.loader,  
                        passwords=self.passwords)

        #Using callback functions  
        playbook._tqm._stdout_callback = self.results_callback

        result = playbook.run()

  
    def get_result(self):  
      result_raw = {'success':{},'failed':{},'unreachable':{}}

      # print(self.results_callback.host_ok)  
      for host,result in self.results_callback.host_ok.items():  
          result_raw['success'][host] = result._result  
      for host,result in self.results_callback.host_failed.items():  
          result_raw['failed'][host] = result._result  
      for host,result in self.results_callback.host_unreachable.items():  
          result_raw['unreachable'][host] = result._result

      #The final result is printed and continues to be formatted using JSON  
      print(json.dumps(result_raw, indent=4))  
        
      return json.dumps(result_raw)

Test run ansible

[[email protected] shell]# cat ansible_run_wc.py   
From ansible2 import * ා references all modules of modified ansible2.py  
import ansible_runner  
import subprocess  
import os, sys, json, datetime, time

Ansible3 = myansiable2 (inventory '/ data / ansible / host / hosts', connection ` smart') 3535; create a repository object

ansible3.run(hosts= "192.168.0.94", module="shell", args='pm2 ls | grep sk_service_design_calculate_rda | wc -l')

stdout_dict = json.loads(ansible3.get_result())  
print(stdout_dict,type(stdout_dict))  
print(stdout_dict['success']['192.168.0.94']['stdout'],'######wc')

Operation results:

[[email protected] shell]# python ansible_run_wc.py   
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details  
{  
    "success": {  
        "192.168.0.94": {  
            "changed": true,  
            "end": "2020-07-06 14:59:30.529462",  
            "stdout": "3",  
            "cmd": "pm2 ls|grep sk_service_design_calculate_rda|wc -l",  
            "rc": 0,  
            "start": "2020-07-06 14:59:30.309994",  
            "stderr": "",  
            "delta": "0:00:00.219468",  
            "invocation": {  
                "module_args": {  
                    "creates": null,  
                    "executable": null,  
                    "_uses_shell": true,  
                    "strip_empty_ends": true,  
                    "_raw_params": "pm2 ls|grep sk_service_design_calculate_rda|wc -l",  
                    "removes": null,  
                    "argv": null,  
                    "warn": true,  
                    "chdir": null,  
                    "stdin_add_newline": true,  
                    "stdin": null  
                }  
            },  
            "stdout_lines": [  
                "3"  
            ],  
            "stderr_lines": [],  
            "ansible_facts": {  
                "discovered_interpreter_python": "/usr/bin/python"  
            },  
            "_ansible_no_log": false  
        }  
    },  
    "failed": {},  
    "unreachable": {}  
}

  
{'success': {'192.168.0.94': {'changed': True, 'end': '2020-07-06 14:59:30.529462', 'stdout': '3', 'cmd': 'pm2 ls|grep sk_service_design_calculate_rda|wc -l', 'rc': 0, 'start': '2020-07-06 14:59:30.309994', 'stderr': '', 'delta': '0:00:00.219468', 'invocation': {'module_args': {'creates': None, 'executable': None, '_uses_shell': True, 'strip_empty_ends': True, '_raw_params': 'pm2 ls|grep sk_service_design_calculate_rda|wc -l', 'removes': None, 'argv': None, 'warn': True, 'chdir': None, 'stdin_add_newline': True, 'stdin': None}}, 'stdout_lines': ['3'], 'stderr_lines': [], 'ansible_facts': {'discovered_interpreter_python': '/usr/bin/python'}, '_ansible_no_log': False}}, 'failed': {}, 'unreachable': {}} <class 'dict'>

  
3 ######wc

Ansible playbook test

Ansible playbook Python script

[[email protected] shell]# cat ansible_playbook_test.py 
from ansible2 import *
import ansible_runner
import subprocess
import os, sys, json, datetime, time
import urllib.request




ansible3 = MyAnsiable2(inventory='/data/ansible/host/hosts', connection='smart')

ansible3.playbook(playbooks=['test.yml'])

stdout_dict = json.loads(ansible3.get_result())
print(stdout_dict,type(stdout_dict))
#print(stdout_dict['success']['192.168.0.94']['stdout'])

test.yml

[[email protected] shell]# grep -C5 192.168.0.94 /data/ansible/host/hosts 

###RDA environment node high load application Linux standard group A###
[rda-highload-node-service-linux-stdA]
192.168.0.94 ansible_ssh_user=root ansible_ssh_pass="Sxxx-xxxx"
- name: test server
  hosts: 'rda-highload-node-service-linux-stdA'
  tasks:
        - name: online pm2 ls
          raw: ls /data/

test result

[[email protected] shell]# python ansible_playbook_test.py 
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
{
    "success": {
        "192.168.0.94": {
            "rc": 0,
            "stdout": "lost+found  pm2-log  pm2-web  rsyslog  samba  xxxx-java  xxxx-node  source\r\n",
            "stdout_lines": [
                "lost+found  pm2-log  pm2-web  rsyslog  samba  xxxx-java  xxxx-node  source"
            ],
            "stderr": "Shared connection to 192.168.0.94 closed.\r\n",
            "stderr_lines": [
                "Shared connection to 192.168.0.94 closed."
            ],
            "changed": true,
            "_ansible_no_log": false
        }
    },
    "failed": {},
    "unreachable": {}
}
{'success': {'192.168.0.94': {'rc': 0, 'stdout': 'lost+found  pm2-log  pm2-web  rsyslog  samba  xxxx-java  xxxx-node  source\r\n', 'stdout_lines': ['lost+found  pm2-log  pm2-web  rsyslog  samba  xxxx-java  xxxx-node  source'], 'stderr': 'Shared connection to 192.168.0.94 closed.\r\n', 'stderr_lines': ['Shared connection to 192.168.0.94 closed.'], 'changed': True, '_ansible_no_log': False}}, 'failed': {}, 'unreachable': {}} <class 'dict'>
[[email protected] shell]#

Recommended Today

ASP.NET Example of core MVC getting the parameters of the request

preface An HTTP request is a standard IO operation. The request is I, which is the input; the responsive o is the output. Any web development framework is actually doing these two things Accept the request and parse to get the parameters Render according to the parameters and output the response content So let’s learn […]