I am trying to make a Parameterized build
in Jenkins. In this way user can choose the git branch he/she wants to deploy from a cascade menu.
There are two possible ways:
Writing branch names in file and configuring Jenkins to read this file (project configuration > extend choice parameter and selecting Property file
).
Problem : You have to make a local repository as a mirror of remote repo and keep this local repo in sync with remote repo. In the other words, you have to update the file containing the available branch name updated. This needs a scheduled job by cron and I am not allowed using this approach.
Using Groovy script (project configuration > extend choice parameter and selecting "Groovy script"
). Then you need a groovy script to retrieve the branch name as follows: branches=master,feature/Feature-1,feature/Feature-2,hotfix/Hotfix-1,release/Release-1
.
I found a groovy script in here but it doesn't work. I have installed groovy on my machine.
Can anybody help me? To make the story short: I need a groovy script which returns the available branch names of a remote repository.
If you want to be able to dynamically give a Git branch to use in a Jenkins build then you'll need to do a couple of things. Then, in your Pipeline configuration, under Branches to build, add your parameter name inside the Branch Specifier box, surrounded by ${} . Jenkins will expand your variable when the job runs.
To create Groovy-based project, add new free-style project and select "Execute Groovy script" in the Build section, select previously configured Groovy installation and then type your command, or specify your script file name. In the second case path taken is relatively from the project workspace directory.
Login to your Jenkins installation and go you your job and click configure. In the Source Code Management section under Build Triggers check the Generic Webhook Trigger. Click Add next to the Post content parameters. Once a push is made, GitHub passes the branch name in the JSON format with the ref key.
The script below should be helpful. It's based on the scripts from linked question. It filters git command output with simple regular expression and creates list of branch names for specified git repository. Tested on grails-core github repo:
def gitURL = "https://github.com/grails/grails-core.git"
def command = "git ls-remote -h $gitURL"
def proc = command.execute()
proc.waitFor()
if ( proc.exitValue() != 0 ) {
println "Error, ${proc.err.text}"
System.exit(-1)
}
def branches = proc.in.text.readLines().collect {
it.replaceAll(/[a-z0-9]*\trefs\/heads\//, '')
}
println branches
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With