From 1ac485fb8b5a855dd3b09b7f1b431b14ab5456d2 Mon Sep 17 00:00:00 2001 From: Debarshi Ray Date: Sun, 30 Aug 2020 16:03:53 +0200 Subject: [PATCH] cmd/initContainer: Split out the code to configure the user https://github.com/containers/toolbox/issues/523 --- src/cmd/initContainer.go | 70 +++++++++++++++++++++++----------------- 1 file changed, 40 insertions(+), 30 deletions(-) diff --git a/src/cmd/initContainer.go b/src/cmd/initContainer.go index 8c56285b1..8a9ea3912 100644 --- a/src/cmd/initContainer.go +++ b/src/cmd/initContainer.go @@ -234,37 +234,12 @@ func initContainer(cmd *cobra.Command, args []string) error { } if _, err := user.Lookup(initContainerFlags.user); err != nil { - if initContainerFlags.homeLink { - if err := redirectPath("/home", "/var/home", true); err != nil { - return err - } - } - - sudoGroup, err := utils.GetGroupForSudo() - if err != nil { - return fmt.Errorf("failed to get group for sudo: %w", err) - } - - logrus.Debugf("Adding user %s with UID %d:", initContainerFlags.user, initContainerFlags.uid) - - useraddArgs := []string{ - "--home-dir", initContainerFlags.home, - "--no-create-home", - "--shell", initContainerFlags.shell, - "--uid", fmt.Sprint(initContainerFlags.uid), - "--groups", sudoGroup, + if err := configureUser(initContainerFlags.home, + initContainerFlags.shell, + initContainerFlags.uid, initContainerFlags.user, - } - - logrus.Debug("useradd") - for _, arg := range useraddArgs { - logrus.Debugf("%s", arg) - } - - if err := shell.Run("useradd", nil, nil, nil, useraddArgs...); err != nil { - return fmt.Errorf("failed to add user %s with UID %d", - initContainerFlags.user, - initContainerFlags.uid) + initContainerFlags.homeLink); err != nil { + return err } logrus.Debugf("Removing password for user %s", initContainerFlags.user) @@ -372,6 +347,41 @@ func initContainerHelp(cmd *cobra.Command, args []string) { } } +func configureUser(home, shell, uid, user string, homeLink bool) error { + if homeLink { + if err := redirectPath("/home", "/var/home", true); err != nil { + return err + } + } + + sudoGroup, err := utils.GetGroupForSudo() + if err != nil { + return fmt.Errorf("failed to get group for sudo: %w", err) + } + + logrus.Debugf("Adding user %s with UID %d:", user, uid) + + useraddArgs := []string{ + "--groups", sudoGroup, + "--home-dir", home, + "--no-create-home", + "--shell", shell, + "--uid", fmt.Sprint(uid), + user, + } + + logrus.Debug("useradd") + for _, arg := range useraddArgs { + logrus.Debugf("%s", arg) + } + + if err := shell.Run("useradd", nil, nil, nil, useraddArgs...); err != nil { + return fmt.Errorf("failed to add user %s with UID %d", user, uid) + } + + return nil +} + func mountBind(containerPath, source, flags string) error { fi, err := os.Stat(source) if err != nil {