Why can't I execute systemctl commands as superuser?

11/30/2016

I wrote a script to download and install kubernetes on an ubuntu machine.

The last part of the script would be to start the kubelet service.

echo "Initializing the master node"
kubeadm reset
systemctl start kubelet.service
kubeadm init

I am forcing the user to run the script as root user. However, when the script reaches the systemctl command, it is not able to execute it. Moreover, I tried to execute the command manually as the root user. I was not able to do so. However, I am able to execute it as a regular user. Does anyone know why? Is there a workaround?

-- Nicolas El Khoury
bash
kubernetes
systemctl
ubuntu

1 Answer

12/1/2016

A possible workaround is to start the service as a regular user, even though the script runs as root. First, you need to find out who is the "original" user:

originalUser="$(logname 2>/dev/null)"

and then call the service as this user:

su - "$originalUser" -c "systemctl start kubelet.service"

Maybe that specific service is dependent on being run by an user who is not root (some programs test for that).

-- Jamil Said
Source: StackOverflow