Setting build args for dockerfile agent using a Jenkins declarative pipeline

You can also use the args parameter to solve the issue.
As described in Pipeline Syntax:

docker also optionally accepts an args parameter which may contain arguments to pass directly to a docker run invocation.

This is also possible when using dockerfile instead of docker in agent section.

I had the same problem like you and the following lines working fine for me:

       agent { 
            dockerfile { 
                dir 'Docker/kubernetes-cli' 
                args '-u 0:0' //Forces Container tu run as User Root                    
                reuseNode true
            }
        }

I verified that trying to assign user_id and group_id without a node didn't work, as you found, but this worked for me to assign these values and later access them:

def user_id
def group_id
node {
  user_id = sh(returnStdout: true, script: 'id -u').trim()
  group_id = sh(returnStdout: true, script: 'id -g').trim()
}

pipeline {
  agent { label 'docker' }
  stages {
    stage('commit_stage') {
      steps {
        echo 'user_id'
        echo user_id
        echo 'group_id'
        echo group_id
      }
    }
  }
}

Hopefully these will also work in your additionalBuildArgs statement.

In a comment, you pointed out what is most likely a critical flaw with the approach that figures out the user_id and group_id outside the declarative pipeline before using it to configure the dockerfile: the slave on which it discovers the user_id will not necessarily match up with the slave that it uses to kick off the docker-based build. i don't there is any way around this while also keeping the declarative Jenkinsfile constraint.

You can guarantee one slave for all stages by using a global agent declaration: Jenkins declarative pipeline: What workspace is associated with a stage when the agent is set only for the pipeline?

But multiple node references with the same label don't guarantee the same workspace: Jenkins declarative pipeline: What workspace is associated with a stage when the agent is set only for the pipeline?


You can also add a block like this:

agent {
    dockerfile {

        args '-v /etc/passwd:/etc/passwd -v /etc/group:/etc/group'
    }
}

That will allow the container to have the correct user and group ID.