PHP使用curl调用jenkins来执行构建任务

一、首先介绍一下exec()函数

  PHP使用curl调用jenkinsAPI执行构建任务,我们采用exec()函数来执行curl命令

  

  exec()函数的基本用法:

    exec(string $command [,array $res] [,int $rt]);

    $command:表示要执行的命令

    $res:表示执行命令后的输入结果

    $rt:表示命令执行后的返回状态信息,0表示成功,其他为失败(注意:$rt只有在$res存在时才能使用)

  

二、jenkins中的配置

  

 

 

  

 

  在配置任务时:

  

 

 

三、调用构建jenkins任务

  curl方式1:curl -X post -v -u  用户名:密码 jenkins地址/job/jenkins任务名/build?token=token值(就是上边的身份验证令牌,也会是root)  #注意这种 方式是当任务中不需要参数是使用的,如果有参数不能执行

  curl方式2:curl --user 用户名:密码 --data build jenkins地址/job/jenkins任务名/buildWithParameters?token=token值(就是上边的身份验证令牌,也会是root) &参数  #这种方式是,任务中存在参数时使用的

  PHP方式:exec("curl -user 用户名:密码 --data build jenkins地址/job/jenkins任务名/buildWithParameters?token=token值 & 参数",$res,$rt)

  例:(注:小编这里jenkins临时搭建,所有任务结果都是错误的)

<?php
#无参的 exec("curl -X post -v -u root:root http://106.13.110.183:8080/job/root1/build?token=root",$res,$rt); return $rt;
有参的
exec("curl --user root:root --data build http://106.13.110.183:8080/job/root1/buildWithParameters?token=root & canshu=canshu",$res,$rt);

  

四、获取上一次的构建结果

#上一次的结果是唯一的
curl jenkins地址/job/jenkins任务名/lastBuild/api/xml
获取上一次的buildId
curl jenkins地址/job/jenkins任务名/lastBuild/api/xml | awk -F'#' '{print $2}' | awk -F'<' '{print $1}'

  

五、执行中任务状态


构建中: <img height="16" alt="pending > Console Output" width="16" src="/static/ea09c638/images/16x16/grey_anime.gif" tooltip="pending > Console Output" /> 排队中: <img height="16" alt="In progress > Console Output" width="16" src="/static/ea09c638/images/16x16/grey_anime.gif" tooltip="In progress > Console Output" /> 成功: <img height="16" alt="Success > Console Output" width="16" src="/static/ea09c638/images/16x16/blue.png" tooltip="Success > Console Output" /> 警告: <img height="16" alt="Unstable > Console Output" width="16" src="/static/ea09c638/images/16x16/yellow.png" tooltip="Unstable > Console Output" /> 失败: <img height="16" alt="Aborted > Console Output" width="16" src="/static/ea09c638/images/16x16/grey.png" tooltip="Aborted > Console Output" />
<img height="16" alt="Failed> Console Output" width="16" src="/static/ea09c638/images/16x16/grey.png" tooltip="Failed> Console Output" />
#其中img标签是唯一的,你可以通过下面的awk命令直接获取到alt获取到的状态(Success等)
awk -F'[ \"]' '/img/{for (i = 1; i <= NF; i++) if (\$i~/alt/)print $(i + 1)}'

  

  

 

posted @ 2020-04-15 14:19  风之老凌  阅读(1014)  评论(0编辑  收藏  举报