shelljenkinsjenkins-pipelinejenkins-groovygroovyshell

How to use Random number in Jenkins Declarative pipeline


Can someone please help me how to use random numbers in jenkins declarative pipelines as a environment variable to use this number in whole pipeline, we need this number to use as a tag to my build artifact. Thank you.

I tried below in my Jenkins declarative pipeline but it throws null message

environment {
          rand = "$RANDOM"
}

stages{
    stage("number"){
     steps{
       script{
               echo " this is a number $rand"
}}}}

Solution

  • Here is the pipeline script, to generate random number:

    pipeline {
        agent any
        
        environment {
            max = 50
            random_num = "${Math.abs(new Random().nextInt(max+1))}"
        }
        
        stages {
            
            stage('Randon number') {
                steps {
                    echo "The random number is: ${env.random_num}"
                }
            }
            
        }
        
    }
    

    This will generate random numbers between 0-50.

    Here you can change the value of the max to decide the upper limit range.