fix(files): change owner for the generated files

Fixes #4
This commit is contained in:
Philippe Caseiro 2023-01-12 12:33:41 +01:00
parent 473ff8ea35
commit ddf37e435a
3 changed files with 33 additions and 11 deletions

2
.gitignore vendored
View File

@ -13,5 +13,5 @@
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
vendor/
bin/

View File

@ -7,6 +7,7 @@ import (
"fmt"
"os"
"os/user"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
@ -25,8 +26,32 @@ type ConfigFile struct {
// Generate the configuration file from the template (hcl or json)
func (cf *ConfigFile) Generate(root string, templateDir string, values []byte) error {
var template string
if utils.DryRun {
return nil
}
cf.TemplateDir = templateDir
dest := filepath.Join(root, cf.Destination)
// Get owner and group UID and GID
owner, err := user.Lookup(cf.Owner)
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
group, err := user.LookupGroup(cf.Group)
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
uid, err := strconv.Atoi(owner.Uid)
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
intMod, err := strconv.ParseInt(cf.Mode, 8, 64)
if err != nil {
return (err)
@ -45,6 +70,10 @@ func (cf *ConfigFile) Generate(root string, templateDir string, values []byte) e
if err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
if err = os.Chown(dest, uid, gid); err != nil {
return fmt.Errorf("Process templates failed with error: %v", err)
}
log.Printf("\tFile %s generated\n", dest)
return nil
}

View File

@ -3,6 +3,7 @@ package templater
import (
"fmt"
"log"
"os/user"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
@ -14,17 +15,9 @@ type SystemUser struct {
Shell string `json:"shell"`
}
func (su *SystemUser) exists() (bool, error) {
_, _, err := utils.RunSystemCommand("getent", "passwd", su.UserName)
if err != nil {
return false, err
}
return true, nil
}
func (su *SystemUser) Manage() error {
exist, _ := su.exists()
if exist {
_, err := user.Lookup(su.UserName)
if err == nil {
log.Printf("\tUser %s already exists", su.UserName)
return nil
}