自動化營運工具Ansible之Python API

來源:互聯網
上載者:User

標籤:ansible   playbooks   自動化營運   python   api   

Ansible 的Python API使用起來相當簡單快捷,使用API可以將某些營運操作封裝成一個帶有WEB介面的操作,免去了每次執行某個操作的時候都需要SSH運行Ansible命令。

官方給出的一個簡單樣本:

import ansible.runner        runner = ansible.runner.Runner(       module_name=‘ping‘,       module_args=‘‘,       pattern=‘web*‘,       forks=10    )    datastructure = runner.run()

run()方法會返回執行的結果。返回的資料是一個JSON格式的:

    {        "dark" : {           "web1.example.com" : "failure message"        },        "contacted" : {           "web2.example.com" : 1        }    }

Ansible的API使用起來就這麼方便,先是匯入ansible,然後直接調用相應的模組,賦值相應的模組參數即可。


    [[email protected] ~]# cat an.py    #!/usr/bin/env python        import ansible.runner        runner = ansible.runner.Runner(        module_name=‘ping‘,#調用的模組        module_args=‘‘,#模組參數        pattern=‘webservers‘,#主機群組,可以是Regex如web*        forks=10    )        data = runner.run()    print data    [[email protected] ~]# python an.py     {‘dark‘: {}, ‘contacted‘: {‘192.168.1.65‘: {‘invocation‘: {‘module_name‘: ‘ping‘, ‘module_args‘: ‘‘}, u‘changed‘: False, u‘ping‘: u‘pong‘}}}

預設使用的主機資源檔位置為/etc/ansible/hosts,也可以指定host_list參數,來指定一個inventory檔案的路徑,也可以指定一個動態inventory指令碼。dark裡面是執行失敗的主機列表,contacted是執行操作成功的主機列表。


但是並不是所有的模組都可以通過API調用的,如template模組,在ansible1.9或之前的版本中,就無法通過Python API調用。

本文出自 “diannaowa” 部落格,請務必保留此出處http://diannaowa.blog.51cto.com/3219919/1683455

自動化營運工具Ansible之Python API

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.