templatefile/pkg/templater/services.go

89 lines
2.1 KiB
Go
Raw Normal View History

package templater
import (
"encoding/json"
"fmt"
"path/filepath"
)
type Service struct {
2022-06-27 15:58:37 +02:00
ConfigFiles []ConfigFile `json:"ConfigFiles"`
Vars map[string]interface{} `json:"Vars"`
Daemons map[string]SystemService `json:"Daemons"`
Users map[string]SystemUser `json:"Users"`
2022-06-29 16:18:28 +02:00
Repos map[string]Repository `json:"Repositories"`
2022-06-27 15:58:37 +02:00
Packages map[string]SystemPackage `json:"Packages"`
}
2022-06-29 16:18:28 +02:00
func (s *Service) manageRepos(repos map[string]Repository) error {
for _, repo := range s.Repos {
if repo.Type == "helm" {
rp := HelmRepository{repo}
return rp.Manage()
}
if repo.Type == "apk" {
rp := APKRepository{repo}
return rp.Manage()
}
if repo.Type == "deb" {
rp := DebRepository{}
return rp.Manage()
}
2022-06-29 12:13:32 +02:00
2022-06-29 16:18:28 +02:00
}
2022-06-29 12:13:32 +02:00
return nil
}
func (s *Service) Manage(templateDir string) error {
2022-06-29 12:13:32 +02:00
2022-06-29 16:18:28 +02:00
// Manage packages repositories
err := s.manageRepos(s.Repos)
if err != nil {
return err
2022-06-29 12:13:32 +02:00
}
2022-06-27 15:58:37 +02:00
// Manage system packages
for _, pack := range s.Packages {
err := pack.Manage()
if err != nil {
return err
}
}
2022-06-29 16:18:28 +02:00
err = processConfigFiles(s.ConfigFiles, s.Vars, templateDir)
if err != nil {
return fmt.Errorf("ProcessingTemplatesFailed with error: %v", err)
}
2022-06-27 15:58:37 +02:00
for _, daemon := range s.Daemons {
err = daemon.Manage()
if err != nil {
return fmt.Errorf("Error managing service daemons: %v", err)
}
}
return nil
}
func processConfigFiles(tpls []ConfigFile, variables map[string]interface{}, templateDir string) error {
values, err := json.Marshal(variables)
if err != nil {
return fmt.Errorf("Error unmarshaling values on template process; %v", err)
}
for _, tpl := range tpls {
fileExt := filepath.Ext(tpl.Source)
if fileExt == ".hcl" {
tpl.TemplateType = "hcl"
} else if fileExt == ".tpl" {
tpl.TemplateType = "go"
} else {
return fmt.Errorf("Unsupported file extention %s, templates extensions have to be '.hcl' or '.tpl'", fileExt)
}
if err := tpl.Generate("/tmp/test", templateDir, values); err != nil {
return fmt.Errorf("Template %s generation failed with error %v", tpl.Source, err)
}
}
return nil
}