Search code examples
jenkins-pipeline

how to create loop inside jenkinsfile


i have created a jenkinsfile inside i have created a text parameter with 10 server names. i want to create a loop within a stage to echo each server name.

// ######################################################################### PROPERTIES ###########################################################################

properties([
    parameters([
        text(defaultValue: '', description: 'EXAMPLE:   lsch3-123', name: 'SERVERS')])])

// ######################################################################### START PIPELINE ###########################################################################

pipeline {
    agent none
    options {
        skipDefaultCheckout true
    }
    stages {
        stage('GIT & PREP') {
            agent {label "${params.DC}-ansible01"}
            steps {
                cleanWs()
                run loop here
            }
        }
    }
}

Solution

  • Please see below code/reference example which will loop within the stage.

    // Define list which would contain all servers in an array. Initialising it as empty
    def SERVERS = []
    pipeline {
        agent none
        options {
            skipDefaultCheckout true
        }
         parameters
        {
            // Adding below as example string which is passed from paramters . this can be changed based on your need
            // Example: Pass server list as ; separated string in your project. This can be changed 
            string(name: 'SERVERS', defaultValue:'server1;server2', description: 'Enter ; separated SERVERS in your project e.g. server1;server2')
        }
        stages {
            stage('GIT & PREP') {
                agent {label "${params.DC}-ansible01"}
                steps {
                    cleanWs()
                    // run loop here under script 
                    script
                    {
                        // Update SERVERS list.Fill SERVERS list with server names by splitting the string.
                        SERVERS = params.SERVERS.split(";")
                        // Run loop below : execute below part for each server listed in SERVERS list
                        for (server in SERVERS)
                        {
                            println ("server is : ${server}") 
                        }
                    }
                }
            }
        }
    }
    

    Regards.