LoginSignup
15
9

More than 5 years have passed since last update.

Jenkinsでビルドパラメータで指定するブランチをプルダウンで選択できるようにする

Posted at

イメージ

こんな感じで動的にブランチ一覧をプルダウンで表示させる

image.png

やりかた

Extended Choice Parameter Pluginを使います

プラグインをインストールしたら、ビルドパラメータで、Extended Choice Parameterが選択できるので、以下のようにparameter typeにSingle Selectを指定します

image.png

Choose Source for Valueに以下のようなGroovy Scriptを指定入力すれば完成です。

listBranches.groovy
#!/usr/bin/env groovy

import hudson.model.*
import jenkins.model.*

def listBranches() {
    // target repo url
    def gitURL = "https://github.com/jenkinsci/jenkins.git"
    // get branches
    def branches = ("git ls-remote -t -h ${gitURL}").execute()
    return branches.text.readLines().collect { it.split()[1].replaceAll('refs/heads/|refs/tags/', '') }.unique().join(",")
}
return listBranches()

プライベートリポジトリの場合は以下のようにJenkinsで管理しているクレデンシャルを取得すればOKです。

listBranches.groovy
#!/usr/bin/env groovy

import hudson.model.*
import jenkins.model.*

def listBranches() {
    // target repo url
    def gitURL = "https://YOUR_PRIVATE_GIT_URL"
    def credentialID = "YOUR_CREDENTIAL_ID"

    // get credential
    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
        jenkins.model.Jenkins.instance
    )
    def credential = creds.findResult { it.id == credentialID ? it : null}

    // get branches
    gitURL = gitURL.replace("https://", "https://${credential.username}:${credential.password}@")
    def branches = ("git ls-remote -t -h ${gitURL}").execute()

    return branches.text.readLines().collect { it.split()[1].replaceAll('refs/heads/|refs/tags/', '') }.unique().join(",")
}
return listBranches()
15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9