How to set the cpus of a docker container depending on the node it runs

I have a pipeline like the following:

pipeline {
    agent {
      docker {
        image 'mydockerimage'
        args '--pull always'
        registryCredentialsId 'my_credentials'
        label 'agent_label'
      }
    }
    stages {
      ....

This pipeline can run in several windows nodes that have different number of threads each. For some reason, the docker only gets 2 out of the N cores as I explain here. So I thought that if I could have an env variable in the node defining the number of threads, I could change the pipeline to

pipeline {
    agent {
      docker {
        image 'mydockerimage'
        args '--pull always --cpus ' + env.CPUS
        registryCredentialsId 'my_credentials'
        label 'agent_label'
      }
    }
    stages {
      ....

But after trying, the env variable is empty (null) at that point although I have set it in the node configuration.


Any idea on how to do so?

String c = "4"
pipeline {
    agent {
        docker {
            image 'ubuntu' 
            args "--pull always --cpus ${c}"
        }
    }
    stages {
        stage('Test') {
            steps {
                sh 'whoami'
            }
        }
    }
}

To your case:

args "--pull always --cpus ${env.CORES}"

While this is certainly correct, it does not solve the core issue of this topic. How can I make this Strimng c = "4" dependant on the executor node?

I don’t think a declarative pipeline can handle that. Here’s an example using a scripted pipeline:
By the way, it will be easier if by ‘core’ you mean the CPU count of the node – you can retrive that number by a shell cmd.

node("10.33.105.107"){
    def computer =  Jenkins.instance.getComputer("10.33.105.107")
    def all = computer.getAllExecutors().size().toString()  

    docker.image('ubuntu').inside("--cpus ${all}") {
        stage('Test') {
            sh 'whoami'
        }
    }
}


image

I don’t think that using the number of executors of the node is the right approach. It says nothing about the number of CPUs on that node.
I have agents that have 120 CPUs and a single executor configured and others that have just 4 CPUs but 15 executors. It all depends on what you do on the machine
You might consider using --cpu-shares instead which is not an absolute value but a weighted value (check the docker docs)