我想查询Jenkins使用它的API和Python来获取当前可以构建的分支。
我该怎么做?
答案 0 :(得分:1)
您可以在jenkins API中查看
lastSuccessfulBuild/api/json?tree=actions[buildsByBranchName]
也许您可以做的是构建您的东西,并在构建作业完成后触发第二个作业。
然后在这个新工作中,您可以找到分支名称
我不使用python,但是使用jq你可以在这样的数组中得到分支名称:
jq -r '.actions[].buildsByBranchName | select(. != null)'
完整代码(您当然可以正确替换bash变量):
JENKINS_API_URL=$JENKINS_SERVER/job/$DEPLOY_JOB/lastSuccessfulBuild/api/json?tree=actions[buildsByBranchName]
BRANCHES_JSON=$(curl --globoff --insecure --silent $JENKINS_API_URL)
BRANCHES=`echo $BRANCHES_JSON | /var/lib/jenkins/tools/jq/jq -r '.actions[].buildsByBranchName | select(. != null)'`
答案 1 :(得分:0)
我终于做到了。
# the url of jenkins config.xml jenkins_url = 'http://11.11.111.11:8686/job/TheJob/config.xml' j_user = "someone" j_pass = "somepass" def get_jenkins_branch_name(jenkins_url, j_user, j_pass): """ The function goes to the provided jenkins XML url, authenticates with an authenticated user, grabs the xml, turns it to dictionary, searches inside the dictionary for the branch name """ import requests,xmltodict from requests.auth import HTTPBasicAuth # get the url with an authenticated user response = requests.get(jenkins_url, auth=HTTPBasicAuth(j_user, j_pass)) #the response must be 200 # the content of the response is the xml xml = response.content # parse the xml to a dictionary jenkins_dict = xmltodict.parse(xml) # grab the actual branch name branch_name = jenkins_dict['project']['scm']['branches']['hudson.plugins.git.BranchSpec']['name'] return branch_name