Jenkinsfile 同時檢出多個 Git 倉庫

2022-11-17 06:00:51

前置

通常,在 Jenkinsfile 中使用 Git 倉庫是這樣的:

stage('Checkout git repo') {
    steps {
        checkout([
            $class: 'GitSCM',
            branches: [[name: 'develop']],
            userRemoteConfigs: [[
                credentialsId:  'ssh-private-key-id',
                url: 'project-git-repo-url'
            ]]
        ])
    }
}

以上寫法的結果是遠端 Git 倉庫中所有內容都被檢出到當前工作目錄下,因此我們才能像下面這樣(不用切換目錄而)直接執行一些命令:

stage('generate version number') {
    steps {
        VERSION_NUBMER = sh(script: "git describe --always", returnStdout: true).trim()
    }
}

將 Git 倉庫檢出到指定資料夾

如果要同時拉取多個 Git 倉庫,面臨的首要問題是如何將 Git 倉庫檢出到指定資料夾。對此,可以通過使用 $class: 'RelativeTargetDirectory' 解決,具體程式碼如下:

stage('Checkout git repo') {
    steps {
        checkout([
            $class: 'GitSCM',
            branches: [[name: 'develop']],
            userRemoteConfigs: [[
                credentialsId:  'ssh-private-key-id',
                url: 'project-git-repo-url'
            ]],
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'repo-folder'
            ]]
        ])
    }
}

這樣一來,遠端 Git 倉庫中所有內容將被檢出到 ./repo-folder 資料夾下;後續我們若想在 Git 專案目錄下操作,就需要先 cd ./repo-folder 了,例如:

stage('generate version number') {
    steps {
        VERSION_NUBMER = sh(script: "cd ./repo-folder && git describe --always", returnStdout: true).trim()
    }
}

檢出多 Git 倉庫

在解決了將 Git 倉庫檢出到指定資料夾這一問題後,檢出多 Git 倉庫這一需求就稍顯容易,下面以檢出repoA、repoB、repoC三個倉庫為例:

stage('Checkout multiple git repos') {
    steps {
        checkout([
            $class: 'GitSCM',
            branches: [[name: 'develop']],
            userRemoteConfigs: [[
                credentialsId:  'ssh-private-key-id',
                url: 'project-git-repoA-url'
            ]],
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'repoA-folder'
            ]]
        ])

        checkout([
            $class: 'GitSCM',
            branches: [[name: 'develop']],
            userRemoteConfigs: [[
                credentialsId:  'ssh-private-key-id',
                url: 'project-git-repoB-url'
            ]],
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'repoB-folder'
            ]]
        ])

        checkout([
            $class: 'GitSCM',
            branches: [[name: 'develop']],
            userRemoteConfigs: [[
                credentialsId:  'ssh-private-key-id',
                url: 'project-git-repoC-url'
            ]],
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'repoC-folder'
            ]]
        ])
    }
}

上面