Files
kube-forge/internal/kubespray/utility.go

116 lines
3.0 KiB
Go

package kubespray
import (
"context"
"fmt"
"io"
"kube-forge/internal/config"
"kube-forge/internal/logging"
"kube-forge/internal/python"
"os"
"path/filepath"
"github.com/apenella/go-ansible/v2/pkg/execute"
"github.com/apenella/go-ansible/v2/pkg/execute/stdoutcallback"
"github.com/apenella/go-ansible/v2/pkg/playbook"
)
func getPlaybookParameters(tags string) playbook.AnsiblePlaybookOptions {
cfg := config.GetConfig()
ansiblePlaybookOptions := playbook.AnsiblePlaybookOptions{
Inventory: filepath.Join(cfg.InventoryDir, "hosts"),
Tags: tags,
User: cfg.Credentials.User,
Become: true,
}
if cfg.Credentials.PrivateKeyFile != "" {
ansiblePlaybookOptions.PrivateKey = cfg.Credentials.PrivateKeyFile
}
if cfg.Credentials.AskSudoPassword {
ansiblePlaybookOptions.AskBecomePass = true
}
return ansiblePlaybookOptions
}
func CopyK8SAdminConfig(outFile string) {
config := config.GetConfig()
var adminDefaultConfigPath = filepath.Join(config.InventoryDir, "artifacts/admin.conf")
source, err := os.Open(adminDefaultConfigPath)
if err != nil {
panic(err)
}
defer source.Close()
destination, err := os.Create(outFile)
if err != nil {
panic(err)
}
defer destination.Close()
_, err = io.Copy(destination, source)
if err != nil {
panic(err)
}
logging.Log.Info(fmt.Sprintf("K8s admin config: %s", outFile))
}
func runPlaybook(playbookPath string, tags string) {
config := config.GetConfig()
var callbackExecute execute.Executor
epExec := python.NewPythonExec()
envVars := map[string]string{
"ANSIBLE_DISPLAY_SKIPPED_HOSTS": "false",
"ANSIBLE_DISPLAY_OK_HOSTS": "false",
"ANSIBLE_FORCE_COLOR": "true",
"ANSIBLE_HOST_KEY_CHECKING": "false",
}
playbookOptions := getPlaybookParameters(tags)
playbookCmd := playbook.NewAnsiblePlaybookCmd(
playbook.WithPlaybooks(
filepath.Join(epExec.ResourcesFsPath, playbookPath),
),
playbook.WithPlaybookOptions(&playbookOptions),
playbook.WithBinary(
filepath.Join(epExec.PythonLibFsPath, "bin", "ansible-playbook"),
),
)
execute := execute.NewDefaultExecute(
execute.WithCmd(playbookCmd),
execute.WithErrorEnrich(playbook.NewAnsiblePlaybookErrorEnrich()),
execute.WithExecutable(epExec),
)
if config.Verbose {
envVars["ANSIBLE_STDOUT_CALLBACK"] = "unixy"
envVars["ANSIBLE_VERBOSITY"] = "3"
envVars["ANSIBLE_DISPLAY_SKIPPED_HOSTS"] = "true"
envVars["ANSIBLE_DISPLAY_OK_HOSTS"] = "true"
} else {
envVars["ANSIBLE_STDOUT_CALLBACK"] = "dense"
envVars["ANSIBLE_ACTION_WARNINGS"] = "false"
envVars["ANSIBLE_DEVEL_WARNING"] = "false"
envVars["ANSIBLE_DEPRECATION_WARNINGS"] = "false"
envVars["ANSIBLE_DUPLICATE_YAML_DICT_KEY"] = "ignore"
envVars["ANSIBLE_HOST_PATTERN_MISMATCH"] = "ignore"
envVars["ANSIBLE_SYSTEM_WARNINGS"] = "false"
}
callbackExecute = stdoutcallback.NewDefaultStdoutCallbackExecute(execute)
for key, value := range envVars {
os.Setenv(key, value)
}
err := callbackExecute.Execute(context.Background())
if err != nil {
panic(err)
}
}