Add a sudoer non-interactively from command line

Solution 1:

You could use cat to append text to the end of /etc/sudoers. First, make a backup copy of your /etc/sudoers file. Then:

cat >> /etc/sudoers
...type one or more lines here...
[control-D]

Make absolutely sure to use two greater-than characters (>>) and not just one, or else you will overwrite the entire contents of your file.

Solution 2:

I had a similar issue trying to get my docker container to allow jenkins scripts to use sudo commands without prompting for a password.

This was solved via the Dockerfile:

RUN echo "jenkins ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers

Solution 3:

To be able to do that, you should make sure you have the following line in your sudoers file:

%sudo   ALL=(ALL:ALL) ALL

You can customize the above line to change the permissions just as though %sudo was a user. That line will allow any users in the sudo group to use sudo.

Now to allow <username> to use sudo, you can just do usermod -a -G sudo <username> as root, which adds <username> to the sudo group.

Solution 4:

Here's how I setup a non-root user with the base image of ubuntu:18.04:

RUN \
    groupadd -g 999 foo && useradd -u 999 -g foo -G sudo -m -s /bin/bash foo && \
    sed -i /etc/sudoers -re 's/^%sudo.*/%sudo ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^root.*/root ALL=(ALL:ALL) NOPASSWD: ALL/g' && \
    sed -i /etc/sudoers -re 's/^#includedir.*/## **Removed the include directive** ##"/g' && \
    echo "foo ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers && \
    echo "Customized the sudoers file for passwordless access to the foo user!" && \
    echo "foo user:";  su - foo -c id

What happens with the above code:

  • The user and group foo is created.
  • The user foo is added to the both the foo and sudo group.
  • The uid and gid is set to the value of 999.
  • The home directory is set to /home/foo.
  • The shell is set to /bin/bash.
  • The sed command does inline updates to the /etc/sudoers file to allow foo and root users passwordless access to the sudo group.
  • The sed command disables the #includedir directive that would allow any files in subdirectories to override these inline updates.