How to connect to list of servers using a loop in Jenkin pipeline?

Viewed 215

I'm trying to connect to couple of my Jenkins slaves and run simple command on each of them. This Jenkinsfile code works fine:

pipeline {
agent none
stages {
    stage('alexander') {
        agent { label 'alexanderPig' }
        steps {
            sh "uptime"
        }
    }
    stage('freddy') {
        agent { label 'freddyFox' }
        steps {
            sh "uptime"
         }
    }
}

}

But what if I had 20 slaves? Is there a way to define an array of agents and then simply run sh commands once inside ie. a loop?

Regards!

1 Answers

I think matrix may be exactly what you need. You can execute stages in parallel with unique parameter sets (like agent's label). Here's complete example:

pipeline {
    agent none
    stages {
        stage('call salves') {
            matrix {
                agent {
                    label "${SLAVE}"
                }
                axes {
                    axis {
                        name 'SLAVE'
                        values 'alexanderPig', 'freddyFox'
                    }
                }
                stages {
                    stage('do something') {
                        steps {
                            sh 'uptime'
                        }
                    }
                }
            }
        }
    }
}

Matrix is not limited to one dimension, you can provide multiple axes and Jenkins will make cartesian product for you.

Related