skip to Main Content

I am executing my Jenkins build in a docker agent. I need to provide additional arguments to the docker run command, one of which is --group-add. The agent section of my Jenkinsfile looks like:

agent {
    docker {
        image "maven"
        args "-v /var/run/docker.sock:/var/run/docker.sock --group-add 999"
    }
}

The problem is that the group id is hard-coded in the Jenkinsfile and I would much rather this be extracted at runtime. i.e. I would like to do something like this:

agent {
    docker {
        image "maven"
        args "-v /var/run/docker.sock:/var/run/docker.sock --group-add $(getent group docker | cut --delimiter ':' --field 3)"
    }
}

But this expansion doesn’t work. I don’t think setting an environment variable would help because it would occur too late.

Am I stuck with hard coding the group id value?

2

Answers


  1. Chosen as BEST ANSWER

    I've resolved this issue by defining my agent with a dockerfile. This allows for execution-time expansion of variables.


  2. Just FYI, Jenkins automatically passes -u uid:gid to each container run, so the primary group is already set for you.

    Then, to set a secondary group, you have to make sure it actually exists within the container. So if you don’t want to hardcode its value in your Jenkinsfiles, you have to extract it from the container itself, not from the host – otherwise, even I’d the group is present, the group IDs might not match.

    Getting back to the variable substitutions – obviously, they will not work in such a scenario. But you can take advantage of different stages in Jenkinsfile – run the container first time, extract the group id, save to s variable, then run it second time:

    def groupId
    
    pipeline {
      agent {
        label 'some-label'
      }
      stages {
        stage('Detect the group ID') {
          agent {
            docker {
              image "maven"
              reuseNode true
            }
          }
          steps {
            script {
              groupId = sh script: 'getent group docker | cut --delimiter ':' --field 3)',
                returnStdout: true,
                label: 'Extract the secondary group'
          }
        }
        stage('Run Maven goals') {
          agent {
            docker {
              image "maven"
              args "-v /var/run/docker.sock:/var/run/docker.sock --group-add ${groupId}"
              reuseNode true
            }
          }
          steps {
            sh 'mvn --version'
          }
        }
      }
    }
    

    Note the use of reuseNode true that allows you to run the stages on the same agent. I also added an explicit label for it because by default Jenkins assumes that any agent is able to run Docker which might not be true.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search