gocron/modules/ansible/host.go

70 lines
1.3 KiB
Go
Raw Normal View History

2017-03-23 05:31:16 +00:00
package ansible
import (
2017-03-23 05:58:42 +00:00
"github.com/ouqiang/cron-scheduler/models"
2017-03-23 05:31:16 +00:00
"sync"
"io/ioutil"
"bytes"
"strconv"
2017-03-24 05:06:53 +00:00
"github.com/ouqiang/cron-scheduler/modules/utils"
2017-03-23 05:31:16 +00:00
)
// 主机名
var DefaultHosts *Hosts
type Hosts struct {
sync.RWMutex
2017-03-24 05:06:53 +00:00
filename string
2017-03-23 05:31:16 +00:00
}
2017-03-24 05:06:53 +00:00
func NewHosts(hostFilename string) *Hosts {
h := &Hosts{sync.RWMutex{}, hostFilename}
2017-03-23 05:31:16 +00:00
2017-03-24 05:06:53 +00:00
return h
2017-03-23 05:31:16 +00:00
}
2017-03-24 05:06:53 +00:00
// 获取hosts文件名
func(h *Hosts) GetFilename() string {
h.RLock()
defer h.RUnlock()
2017-03-23 05:31:16 +00:00
2017-03-24 05:06:53 +00:00
return h.filename
2017-03-23 05:31:16 +00:00
}
2017-03-24 05:06:53 +00:00
// 写入hosts
func(h *Hosts) Write() {
host := new(models.Host)
hostModels, err := host.List()
if err != nil {
utils.RecordLog(err)
return
}
if len(hostModels) == 0 {
utils.RecordLog("hosts内容为空")
return
}
2017-03-23 05:31:16 +00:00
buffer := bytes.Buffer{}
2017-03-24 05:06:53 +00:00
for _, hostModel := range(hostModels) {
2017-03-23 05:31:16 +00:00
buffer.WriteString(strconv.Itoa(int(hostModel.Id)))
buffer.WriteString(" ansible_ssh_host=")
buffer.WriteString(hostModel.Name)
buffer.WriteString(" ansible_ssh_port=")
buffer.WriteString(strconv.Itoa(hostModel.Port))
buffer.WriteString(" ansible_ssh_user=")
buffer.WriteString(hostModel.Username)
if (hostModel.LoginType != models.PublicKey && hostModel.Password != "") {
buffer.WriteString(" ansible_ssh_pass=")
buffer.WriteString(hostModel.Password)
}
buffer.WriteString("\n")
}
2017-03-24 05:06:53 +00:00
h.Lock()
defer h.Unlock()
err = ioutil.WriteFile(h.filename, buffer.Bytes(), 0644)
2017-03-23 05:31:16 +00:00
return
}