@@ -24,6 +24,7 @@ import (
2424 "os/exec"
2525 "os/user"
2626 "path"
27+ "path/filepath"
2728 "strconv"
2829 "strings"
2930 "sync"
@@ -449,14 +450,8 @@ func (s *Server) setUser(ctx context.Context) error {
449450 }
450451
451452 if s .isFreshRun {
452- zap .L ().Debug ("Adding NOPASSWD to user sudoers" )
453- if err := os .MkdirAll ("/etc/sudoers.d" , 0750 ); err != nil {
454- return err
455- }
456-
457- if err := os .WriteFile (fmt .Sprintf ("/etc/sudoers.d/%s" , s .userInfo .name ),
458- []byte (fmt .Sprintf (`%%%s ALL=(ALL:ALL) NOPASSWD: ALL` , s .userInfo .name )), 0644 ); err != nil {
459- return errors .Errorf ("Could not write to sudoers file: %+v" , err )
453+ if err := s .setSudoersFile (); err != nil {
454+ zap .L ().Warn ("Could not set sudoers file" , zap .Error (err ))
460455 }
461456 } else {
462457 zap .L ().Debug ("No need to add NOPASSWD to user sudoers" )
@@ -489,6 +484,30 @@ func (s *Server) setUser(ctx context.Context) error {
489484 return nil
490485}
491486
487+ func (s * Server ) setSudoersFile () error {
488+ sudoersDir := "/etc/sudoers.d"
489+ username := s .userInfo .name
490+ filePath := filepath .Join (sudoersDir , username )
491+
492+ if _ , err := os .Stat (sudoersDir ); os .IsNotExist (err ) {
493+ if err := os .MkdirAll (sudoersDir , 0755 ); err != nil {
494+ return err
495+ }
496+ }
497+
498+ if _ , err := os .Stat (filePath ); err == nil {
499+ return nil
500+ }
501+
502+ content := fmt .Sprintf ("%s ALL=(ALL) NOPASSWD: ALL\n " , username )
503+
504+ if err := os .WriteFile (filePath , []byte (content ), 0440 ); err != nil {
505+ return err
506+ }
507+
508+ return nil
509+ }
510+
492511func (s * Server ) getCmd (ctx context.Context , cmdStr string ) * exec.Cmd {
493512 cmd := exec .CommandContext (ctx , s .shellPath , "-c" , cmdStr )
494513 if ldflags .IsDev () {
0 commit comments