Jenkins

[Jenkins] Pipeline - 반복문 for

비번변경 2023. 11. 8. 16:47

개요

2023.11.02 - [Jenkins] pipeline - 변수 선언 및 사용

2023.11.07 - [Jenkins] Pipeline - 동적 변수 사용

 

위 두 개 글에서 Jenkins Pipeline 상에서의 변수 사용에 대해서 알아보았는데, 이번 글에서는 반복문을 사용해보려고 한다.

 

 

for 문

script 블록 내에서 다른 프로그래밍 언어처럼 for 문을 사용할 수 있다.

for (int i = 0; i < 10; ++i) {
    echo "$i"
}

 

예시 )

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    for (int i = 0; i < 3; ++i) {
                        echo "$i"
                    }
                }
            }
        }
    }
}

 

 

for - in

만약 반복 가능한 객체에 인덱스 없이 접근하고 싶다면 for - in 문을 사용할 수 있다.

for (int i in 0..3) {
    echo "$i"
}

 

예시 )

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    for (int i in 0..3) {
                        echo "$i"
                    }
                }
            }
        }
    }
}

 

 

for - each

또는 for - each를 사용해 반복 가능한 데이터에 접근할 수도 있다. each 문 내에서는 기본적으로 it라는 변수명으로 데이터에 접근할 수 있다.

def browsers = ['chrome', 'firefox']
browsers.each {
    echo "Testing the $it browser"
}

each 문 내에 변수명을 재정의할 수도 있다.

browsers.each { item ->
    echo "Testing the $item browser"
}

 

예시 )

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                script {
                    def browsers = ['chrome', 'firefox']
                    browsers.each {
                        echo "Testing the $it browser"
                    }
                    browsers.each { item ->
                        echo "Testing the $item browser"
                    }
                }
            }
        }
    }
}

 

 

참고 문서

https://serverfault.com/questions/1014334/how-to-use-for-loop-in-jenkins-declarative-pipelinehttps://www.tutorialspoint.com/groovy/groovy_for_statement.htm

https://www.tutorialspoint.com/groovy/groovy_forin_statement.htm

728x90