ansible是一個python package,是個完全的unpack and play軟體,對用戶端唯一的要求是有ssh有python,並且裝了python-simplejson包,部署上簡單到髮指。下面這篇文章就給大家主要介紹了ansible作為python模組庫使用的方法執行個體,需要的朋友可以參考借鑒。
前言
ansible是新出現的自動化營運工具,基於Python開發,集合了眾多營運工具(puppet、cfengine、chef、func、fabric)的優點,實現了批量系統配置、批配量序部署、批量運行命令等功能。ansible是基於模組工作的,本身沒有批量部署的能力。真正具有批量部署的是ansible所啟動並執行模組,ansible只是提供一種架構。
主要包括:
(1)、串連外掛程式connection plugins:負責和被監控端實現通訊;
(2)、host inventory:指定操作的主機,是一個設定檔裡面定義監控的主機;
(3)、各種模組核心模組、command模組、自訂模組;
(4)、藉助於外掛程式完成記錄日誌郵件等功能;
(5)、playbook:劇本執行多個任務時,非必需可以讓節點一次性運行多個任務。
Asible是營運工具中算是非常好的利器,我個人比較喜歡,可以根據需求靈活配置yml檔案來實現不同的業務需求,因為不需要安裝用戶端,上手還是非常容易的,在某些情況下你可能需要將ansible作為python的一個庫組件寫入到自己的指令碼中,今天的指令碼指令碼就將展示下ansible如何跟python指令碼結合,也就是如何在python指令碼中使用ansible,我們逐步展開。
先看第一個例子:
#!/usr/bin/python import ansible.runnerimport ansible.playbookimport ansible.inventoryfrom ansible import callbacksfrom ansible import utilsimport json # the fastest way to set up the inventory # hosts listhosts = ["10.11.12.66"]# set up the inventory, if no group is defined then 'all' group is used by defaultexample_inventory = ansible.inventory.Inventory(hosts) pm = ansible.runner.Runner( module_name = 'command', module_args = 'uname -a', timeout = 5, inventory = example_inventory, subset = 'all' # name of the hosts group ) out = pm.run() print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))
這個例子展示我們如何在python指令碼中運行如何通過ansible運行系統命令,我們接下來看第二個例子,跟我們的yml檔案對接。
簡單的yml檔案內容如下:
- hosts: sample_group_name tasks: - name: just an uname command: uname -a
調用playbook的python指令碼如下:
#!/usr/bin/python import ansible.runnerimport ansible.playbookimport ansible.inventoryfrom ansible import callbacksfrom ansible import utilsimport json ### setting up the inventory ## first of all, set up a host (or more)example_host = ansible.inventory.host.Host( name = '10.11.12.66', port = 22 )# with its variables to modify the playbookexample_host.set_variable( 'var', 'foo') ## secondly set up the group where the host(s) has to be addedexample_group = ansible.inventory.group.Group( name = 'sample_group_name' )example_group.add_host(example_host) ## the last step is set up the invetory itselfexample_inventory = ansible.inventory.Inventory()example_inventory.add_group(example_group)example_inventory.subset('sample_group_name') # setting callbacksstats = callbacks.AggregateStats()playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY) # creating the playbook instance to run, based on "test.yml" filepb = ansible.playbook.PlayBook( playbook = "test.yml", stats = stats, callbacks = playbook_cb, runner_callbacks = runner_cb, inventory = example_inventory, check=True ) # running the playbookpr = pb.run() # print the summary of results for each hostprint json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))