從0開始實現自動化運維工具(四)

完整的代碼已經在github開源:github.com/CTC-maxiao/…python

編寫入口程序

前面的幾節咱們已經完成了執行字典生成器和執行字典執行器,如今咱們只須要編寫一個入口程序來接收外界輸入而後自動生成執行字典列表,而後再經過task執行器來依次執行任務,就能夠徹底整個程序的編寫。git

import sys
import getopt

from task_executor import TaskExecutor
from get_tasklist import getTaskList

#getopt是一個很是好用的python庫,設定的參數後加":"意味這個參數須要輸入
opts,args = getopt.getopt(sys.argv[1:],'-u:-p:-y:-h-v',['user=','password=','yamlfile=','help','version'])

for opt_name,opt_value in opts:
    if opt_name in ('-u','--user'):
        ssh_user = opt_value
    if opt_name in ('-p','--password'):
        ssh_pwd = opt_value
    if opt_name in ('-y','--yamlfile'):
        yaml_file = opt_value
    if opt_name in ('-h','--help'):
        print "help you"
        sys.exit()
    if opt_name in ('-v','--version'):
        print "version 1.0"
        sys.exit()

task_list = getTaskList.get_final_task_list(ssh_user,ssh_pwd,yaml_file)

for task in task_list:
    tmp=TaskExecutor.run_task(task)
    print tmp
複製代碼

這裏咱們使用getopt庫,這個庫能夠簡潔的接收傳入參數,而且支持長參數和短參數兩種形式。github

測試最終程序

程序至此就已經算是寫好了,雖然還很不完善,但已經實現了基本的功能。咱們編寫一個簡單的playbook來測試一下最終的程序。shell

---
- name: test program on remote machine
  host: 192.168.1.34
  
  tasks:

  - task_name: create test folder on remote machine
    become: yes
    become_user: root
    action_type: shell
    action: mkdir /opt/mstr/test
    
  - task_name: create test folder on localhost
    action_type: shell
    action: mkdir /opt/mstr/test
    delegate_to: localhost
複製代碼

這個playbook很是簡單,執行後會在本機和遠程機器上生成一個文件夾。bash

如今咱們來執行這個playbook:ssh

python main.py -u test_user -p test_pwd -y /opt/mstr/test.yaml
複製代碼

運行結束後能夠看到,本機和遠程機器上成功生成了相應的文件夾。測試

playbook的格式

咱們的playbook的格式基本與ansible的一致,但也有一些不一樣點須要注意:ui

  • 新增action_type和action關鍵字,ansible的action是相似 shell :mkdir test 這樣的格式,module在前,具體的操做在後。但這種格式在解析yaml文件的時候不夠簡單快捷,因而我將它拆成action_type和action兩個關鍵字
  • 暫時不支持register關鍵字。register能夠在playbook中設定變量,這個功能我會在之後有空時添加進來
  • 暫時不支持playbook模板。這個功能之後也會添加進來
  • become_method暫時只有sudo 方式,su方式尚未空寫
  • playbook的一些高級功能尚未實現

若是你須要爲這個程序編寫playbook,請注意以上幾點。另外,完整的程序我已經開源到github,歡迎試用和幫忙找bug。 github地址: github.com/CTC-maxiao/…spa

相關文章
相關標籤/搜索