您的位置 首页 golang

Golang实现ansible自动运维

简介

ansible 是自动化 运维 工具,基于Python开发。

ansible目前针对golang提供对应的SDK、API之类的。

我们这里可以采用直接调用ansible-playbook这个命令执行我们的任务。

python

ansible

ansible

利用golang的os/exec来执行ansible-playbook这个命令,实现变量的拼接,由于我习惯将对象存在hosts这个变量里面,因此操作的时候需要指定hosts这个变量。

 package ansible
​
import (
    "os/exec"
    "strings"
    "time"
)
​
// RunPlayBook 执行通过ansible-playbook命令执行ansible任务
func RunPlayBook(ansiblePath, inventory, yamlfile string, vars []string) (result string, ok bool) {
    startTime := time.Now()
    commandStr := []string{ansiblePath, "--ssh-common-args='-o StrictHostKeyChecking=no'", "-i", inventory, yamlfile}
    for _, k := range vars {
        commandStr = append(commandStr, "-e")
        commandStr = append(commandStr, k)
    }
    // fmt.Println(commandStr)
    command := exec.Command(commandStr[0], commandStr[1:]...)
    errString := ""
     output , err := command.CombinedOutput()
    if err != nil {
        errString = "ERROR: " + err.Error()
    }
    // fmt.Println(string(output))
    recapFlag := false
    // ok := false
    for _, line := range strings.Split(string(output), "\n") {
        if strings.TrimSpace(line) == "" {
            continue
        }
        if strings.HasPrefix(line, "PLAY RECAP *") {
            recapFlag = true
        }
        if recapFlag {
            if strings.Contains(line, "unreachable=0") && strings.Contains(line, "failed=0") {
                ok = true
            }
        }
    }
    return strings.Join(commandStr, " ") + "\n " + errString + "\n " + string(output) + "\n=======================================\n开始时间:" + startTime. Format ("2006-01-02 15:04:05") + "\n结束时间:" + time.Now().Format("2006-01-02 15:04:05") + "\n耗时:" + time.Now().Sub(startTime).String(), ok
}
​  

测试

准备playbook文件

 vim /data/ansible/ test . yaml   

做一个简单的测试,将要执行的对象放到hosts这个变量里面

 - name: 测试ansible任务
  hosts: "{{ hosts }}"
  remote_user: root
  gather_facts: False
  tasks:
    - name: hostname
      command: hostname
      register: hostname
    - name: echo
      debug:
        msg: "get hostname from {{ hostname }} by {{ powerby }} "  

coding

Go执行文件

 package main
​
import (
    "ansible/ansible"
    "fmt"
)
​
func main() {
    result, ok := ansible.RunPlayBook("/data/apps/python3/bin/ansible-playbook", "/etc/ansible/hosts", "/data/ansible/test.yaml", []string{
        "hosts=127.0.0.1",
        "powerby=Golang",
    })
    if ok {
        fmt.Println("执行成功")
    } else {
        fmt.Println("执行失败")
    }
    fmt.Println(result)
}
​  

执行输出

 执行成功
/data/apps/python3/bin/ansible-playbook --ssh-common-args='-o StrictHostKeyChecking=no' -i /etc/ansible/hosts /data/ansible/test.yaml -e hosts=127.0.0.1 -e powerby=Golang
 
  [WARNING]: Found variable using reserved name: hosts
​
PLAY [测试ansible任务] *************************************************************
​
TASK [hostname] ****************************************************************
changed: [127.0.0.1]
​
TASK [echo] ********************************************************************
ok: [127.0.0.1] => {
    "msg": "get hostname from {'cmd': ['hostname'], 'stdout': 'tosomeone', 'stderr': '', 'rc': 0, 'start': '2020-08-20 22:23:29.851614', 'end': '2020-08-20 22:23:29.852629', 'delta': '0:00:00.001015', 'changed': True, 'stdout_lines': ['linuxopcai'], 'stderr_lines': [], 'failed': False} by Golang "
}
​
PLAY RECAP *********************************************************************
127.0.0.1                  : ok=2    changed=1    unreachable=0    failed=0   
​
​
=======================================
开始时间:2020-08-20 22:23:28
结束时间:2020-08-20 22:23:29
耗时:1.067408099s  

总结

golang

由于历史原因,很多任务都还是ansible的任务,只能采用这种方式进行过度。

在Go的生态中,大家有什么推荐的批量自动化任务的包或者工具呢?

文章来源:智云一二三科技

文章标题:Golang实现ansible自动运维

文章地址:https://www.zhihuclub.com/86742.shtml

关于作者: 智云科技

热门文章

网站地图