Python calls the Ansible interface API to execute commands

Source: Internet
Author: User
Tags dataloader

Python version: Python 2.6.6

Ansible version: Ansible 2.3.1.0

Call Script: task_exec_v1.py

#!/usr/bin/Env Python#coding:utf-8Import osimport sysimport jsonimport logging fromCollections Import Namedtuple fromansible.inventory Import Inventory fromansible.vars Import Variablemanager fromansible.parsing.dataloader Import Dataloader fromansible.executor.playbook_executor Import Playbookexecutor fromansible.plugins.callback Import Callbackbase fromansible.errors Import Ansibleparsererror fromOptparse Import optionparser# defines the print log logging.basicconfig (filename='Task_exec_v3.log', #通过logging. basicconfig function to configure the output format and mode of the log.='% (asctime) s-% (name) s-% (LevelName) s-% (module) s:% (message) s', datefmt='%y-%m-%d%h:%m:%s%p', level=Ten)classMycallback (callbackbase): #这里是状态回调, all kinds of successful failure of the state, the various methods are actually written in the Callbackbase parent class inside, in fact, there are many, can be taken out according to the need for Def __init__ ( Self,*args): Super (Mycallback,self). __init__ (Display=None) Self.status_ok=json.dumps ({}) Self.status_fail=json.dumps ({}) self.status_unreachable=json.dumps ({}) Self.status_playbook="'self.status_no_hosts=False SELF.HOST_OK={} self.host_failed={} self.host_unreachable={} def v2_runner_on_ok (Self,result): Host=result._host.get_name () SELF.RUNNER_ON_OK (host, Result._result) #self. STATUS_OK=json.dumps ({host:result._result},indent=4) Self.host_ok[host]=result def v2_runner_on_failed (self, result, ignore_errors=False): Host=result._host.get_name () self.runner_on_failed (host, Result._result, Ignore_errors) #self. status_fail=json.dumps ({host:result._result},indent=4) Self.host_failed[host]=result def v2_runner_on_unreachable (self, result): Host=result._host.get_name () self.runner_on_unreachable (host, Result._result) #self. Status_unreachable=json.dumps ({host:result._result},indent=4) Self.host_unreachable[host]=result def v2_playbook_on_no_hosts_matched (self): self.playbook_on_no_hosts_matched () self.status_no _hosts=True def v2_playbook_on_play_start (self, play): Self.playbook_on_play_start (play.name) Self.playbook_ Path=Play.nameclassMy_ansible_play (): #这里是ansible运行 #初始化各项参数, most are defined, only a few parameters are required to pass in the Def __init__ (self, playbook, EXTRA_VARS={}, Host_list='/etc/ansible/hosts', Connection='SSH', become=False, Become_user=None, Module_path=None, fork= -, Ansible_cfg=none, #os. environ["Ansible_config"] =None Passwords={}, check=False): Self.playbook_path=Playbook Self.passwords=Passwords Self.extra_vars=Extra_vars Options= Namedtuple ('Options',                   ['Listtags','Listtasks','listhosts','Syntax','Connection','Module_path',                   'Forks','Private_key_file','Ssh_common_args','Ssh_extra_args','Sftp_extra_args',                      'Scp_extra_args','become','Become_method','Become_user','verbosity','Check']) logging.info (Options) self.options= Options (Listtags=false, listtasks=False, Listhosts=false, syntax=False, Connection=connection, module_path=Module_path, Forks=fork, private_key_file=None, Ssh_common_args=none, ssh_extra_args=None, Sftp_extra_args=none, scp_extra_args=None, become=become, become_method=None, Become_user=Become_user, verbosity=none, check=check) logging.info (self.options)ifAnsible_cfg! =none:os.environ["Ansible_config"] =ansible_cfg Self.variable_manager=Variablemanager () self.variable_manager.extra_vars=Self.extra_vars Self.loader=Dataloader () self.inventory=inventory (loader=self.loader,variable_manager=self.variable_manager,host_list=host_list) #定义运行的方法和返回值 def run (self): complex_msg={}        ifNot os.path.exists (self.playbook_path): Code= +Results={'Playbook': Self.playbook_path,'msg': self.playbook_path+'Playbook is not exist','Flag': False} logging.info (results) #results=self.playbook_path+'Playbook is not existed'            #returncode,complex_msg,results Pbex= Playbookexecutor (playbooks=[Self.playbook_path], inventory=self.inventory, Variable_manager=Self.variable_manager, Loader=Self.loader, Options=self.options, Passwords=self.passwords) Self.results_callback=mycallback () pbex._tqm._stdout_callback=Self.results_callbackTry: Code=Pbex.run () except Ansibleparsererror:code=1001Results={'Playbook': Self.playbook_path,'msg': self.playbook_path+'playbook have syntax error','Flag': False} #results='syntax error in'+Self.playbook_path #语法错误returnCode,resultsifSelf.results_callback.status_no_hosts:code=1002Results={'Playbook': Self.playbook_path,'msg': Self.results_callback.status_no_hosts,'Flag': False,'executed': False}returncode,results def get_result (self): Self.result_all={'Success':{},'fail':{},'Unreachable':{}}         forHost, resultinchSelf.results_callback.host_ok.items (): self.result_all['Success'][host] =Result._result forHost, resultinchSelf.results_callback.host_failed.items ():ifResult._result.has_key ("msg"): self.result_all['fail'][host] = result._result['msg']         forHost, resultinchSelf.results_callback.host_unreachable.items (): self.result_all['Unreachable'][host]= result._result['msg']                 forIinchself.result_all['Success'].keys (): Print i,self.result_all['Success'][i] Print self.result_all['fail'] Print self.result_all['Unreachable']if__name__ = ='__main__': Play_book=my_ansible_play ('/etc/ansible/playbooks/test_ping.yml') Logging.info (Play_book) Play_book.run () Play_book.get_result ()

Attached Playbook script: Test_ping.yml

---- hosts:test  gather_facts:false  tasks:    - name:test ping      :    -  Name:shell commond      "helloWorld"      register:result    - name:show Debug Info      var=result.stdout verbosity=0

python3.5 Call Ansible Reference Document:

Https://www.cnblogs.com/stones/p/8252731.html

Python calls the Ansible interface API to execute commands

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.