run jenkins pipeline agent with sudo

前端 未结 7 1612
一生所求
一生所求 2020-12-09 11:19

I have an Jenkins Server running in an docker container and have access to docker an the host system, so far it is working well. Now I want to set up a pipeline testing an s

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 11:36

    I might have found a reasonably good solution for this.

    Setup

    I run Jenkins as a container and use it to build containers on the dockerhost it's running on. To do this, I pass /var/run/docker.sock as a volume to the container.

    Just to reiterate the disclaimer some other people already stated: Giving access to the docker socket is essentially like giving root access to the machine - be careful!

    I assume that you've already installed docker into your Jenkins Image.

    Solution

    This is based on the fact, that the docker binary is not in the first directory of $PATH. We basically place a shell script that runs sudo docker instead of just the plain docker command (and passes the parameters along).

    Add a file like this to your jenkins repository and call it docker_sudo_overwrite.sh:

    #! /bin/sh 
    # This basically is a workaround to add sudo to the docker command, because aliases don't seem to work 
    # To be honest, this is a horrible workaround that depends on the order in $PATH
    # This file needs to be place in /usr/local/bin with execute permissions
    sudo /usr/bin/docker $@
    

    Then extend your Jenkins Dockerfile like this:

    # Now we need to allow jenkins to run docker commands! (This is not elegant, but at least it's semi-portable...)
    USER root
    
    ## allowing jenkins user to run docker without specifying a password
    RUN echo "jenkins ALL=(ALL) NOPASSWD: /usr/bin/docker" >> /etc/sudoers
    
    # Create our alias file that allows us to use docker as sudo without writing sudo
    COPY docker_sudo_overwrite.sh /usr/local/bin/docker
    RUN chmod +x /usr/local/bin/docker
    
    # switch back to the jenkins-user
    USER jenkins
    

    This gives the jenkins service user the ability to run the docker binary as root with sudo (without providing a password). Then we copy our script to /usr/local/bin/docker which "overlays" the actual binary and runs it with sudo. If it helps, you can look at my example on Github.

提交回复
热议问题