websoft9/docker/deployment/init_portainer.go

85 lines
1.8 KiB
Go
Raw Normal View History

2023-09-06 11:47:18 +08:00
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"time"
)
func main() {
2023-09-18 09:43:03 +08:00
2023-09-18 09:49:31 +08:00
dirPath := "/var/websoft9"
if _, err := os.Stat("/var"); os.IsNotExist(err) {
err = os.Mkdir("/var", 0755)
if err != nil {
fmt.Println(err)
return
}
}
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err = os.Mkdir(dirPath, 0755)
if err != nil {
fmt.Println(err)
return
}
}
2023-09-18 09:43:03 +08:00
filePath := "/var/websoft9/credential"
2023-09-06 11:47:18 +08:00
_, err := os.Stat(filePath)
if os.IsNotExist(err) {
2023-09-19 16:36:28 +08:00
fmt.Println("credential is not exist, create it.")
2023-09-06 11:47:18 +08:00
password := generatePassword(16)
err := writeToFile(filePath, password)
if err != nil {
fmt.Println("write file error:", err)
return
}
2023-09-19 16:28:36 +08:00
}else{
2023-09-19 16:36:28 +08:00
fmt.Println("credential is exist, skip it.")
2023-09-19 16:28:36 +08:00
cmd := exec.Command("./portainer")
cmd.Run()
2023-09-06 11:47:18 +08:00
}
2023-09-19 16:07:56 +08:00
content, err := ioutil.ReadFile(filePath)
2023-09-06 11:47:18 +08:00
if err != nil {
fmt.Println("read file error:", err)
return
}
fmt.Println("-----portainer_admin_user: admin, portainer_admin_password: " + string(content) + " ------")
// call portainer
2023-09-18 09:43:03 +08:00
cmd := exec.Command("./portainer", "--admin-password-file", filePath)
2023-09-06 11:47:18 +08:00
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println("error running compiled_program:", err)
return
}
}
func generatePassword(length int) string {
rand.Seed(time.Now().UnixNano())
charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+{}[]:;?.,<>"
password := make([]byte, length)
for i := range password {
password[i] = charset[rand.Intn(len(charset))]
}
return string(password)
}
2023-09-19 16:07:56 +08:00
func writeToFile(filePath , content string) error {
2023-09-18 09:49:31 +08:00
2023-09-19 16:07:56 +08:00
return ioutil.WriteFile(filePath , []byte(content), 0755)
2023-09-06 11:47:18 +08:00
}