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

1

6

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?

Herbivore answered 23/12, 2020 at 16:2 Comment(2)
You shouldn't ever need sudo in Docker: a container only runs one process, and when you launch it you can explicitly specify the user at the docker run command line (or, if you need a debugging shell, docker exec -u can launch it as an alternate user). What's the application you're trying to package, and how does it need sudo? Does How to use sudo inside a docker container? have enough information for you?Eartha
You are rigth. But itis not my call.Herbivore
R
19

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.

Radiolocation answered 24/12, 2020 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.