dockerubuntudockerfilesudosudoers

Add sudo permission (without password ) to user by command line


I'm creating a docker file from ubuntu:bionic image.

I want an ubuntu user with sudo privileges.

This is my Dockerfile

FROM ubuntu:bionic

ENV DEBIAN_FRONTEND noninteractive

# Get the basic stuff
RUN apt-get update && \
    apt-get -y upgrade && \
    apt-get install -y \
    sudo

# Create ubuntu user with sudo privileges
RUN useradd -ms /bin/bash ubuntu && \
    usermod -aG sudo ubuntu

# Set as default user
USER ubuntu
WORKDIR /home/ubuntu

ENV DEBIAN_FRONTEND teletype

CMD ["/bin/bash"]

But with this aproach I need to write the password of ubuntu user.

There is a way to add NOPASSWD clausule to sudo group in sudoers file by command line?


Solution

  • First, you are not suggested to use sudo in docker. You could well design your behavior using USER + gosu.

    But, if you insist for some uncontrolled reason, just add next line after you setup normal user:

    RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
    

    So for your scenario, the workable one is:

    FROM ubuntu:bionic
    
    ENV DEBIAN_FRONTEND noninteractive
    
    # Get the basic stuff
    RUN apt-get update && \
        apt-get -y upgrade && \
        apt-get install -y \
        sudo
    
    # Create ubuntu user with sudo privileges
    RUN useradd -ms /bin/bash ubuntu && \
        usermod -aG sudo ubuntu
    # New added for disable sudo password
    RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
    
    # Set as default user
    USER ubuntu
    WORKDIR /home/ubuntu
    
    ENV DEBIAN_FRONTEND teletype
    
    CMD ["/bin/bash"]
    

    Test the effect:

    $ docker build -t abc:1 .
    Sending build context to Docker daemon  2.048kB
    Step 1/9 : FROM ubuntu:bionic
    ......
    Successfully built b3aa0793765f
    Successfully tagged abc:1
    
    $ docker run --rm abc:1 cat /etc/sudoers
    cat: /etc/sudoers: Permission denied
    
    $ docker run --rm abc:1 sudo cat /etc/sudoers
    #
    # This file MUST be edited with the 'visudo' command as root.
    #
    # Please consider adding local content in /etc/sudoers.d/ instead of
    # directly modifying this file.
    #
    # See the man page for details on how to write a sudoers file.
    #
    Defaults        env_reset
    ......
    #includedir /etc/sudoers.d
    %sudo ALL=(ALL) NOPASSWD:ALL
    

    You could see with sudo, we could already execute a root-needed command.