背景:前一节搭建jenkins并创建了job任务后,用户可以在jenkins平台手动点击构建来执行pytest自动化任务,想实现一个从web界面去触发构建jenkins中的job任务,在这选择使用php来调用jenkins-api去触发构建
安装php-jenkins-api包
# composer安装,使用的是外国友人写的一个包,该包也是基于别人的进行了部分扩展
composer require chbiel/jenkins-php-api
php调用php-jenkins-api方法构建job
# 以下是一个自定义的service文件:JenkinsApiService.php
<?php
/**
* Created by PhpStorm.
* User: wkk
* Time: 2022/10/21 - 00:26
* Desc: <jenkins-api操作jenkins>
*/
namespace app\common\service\jenkins;
use JenkinsApi\Item\Job;
use JenkinsApi\Jenkins;
class JenkinsApiService
{
private Jenkins $jenkins;
private $token; // token密钥:php调用jenkins-api时需要的,在这不使用用户名和密码
private $userName; // jenkins用户名
private $jenkinsHost; // jenkins系统host:port
public function __construct()
{
$this->token = env('JENKINS.APITEST_TOKEN');
$this->userName = env('JENKINS.JENKINS_USER');
$this->jenkinsHost = env('JENKINS.JENKINS_HOST');
$this->jenkins = new Jenkins("http://{$this->userName}:{$this->token}@{$this->jenkinsHost}");
}
/**
* 获取job信息
*
* @param $jobName
* @return Job|null
*/
public function getJob($jobName): ?Job
{
return $this->jenkins->getJob($jobName);
}
/**
* 构建job
*
* @param $jobName
* @return bool
*/
public function buildJob($jobName): bool
{
return $this->getJob($jobName)->launch();
}
}
使用方法
# goujian
/**
* 构建job任务
* @param $jobName
* @return bool
*/
public static function buildJob($jobName): bool
{
try {
$jenkinsService = new JenkinsApiService();
$res = $jenkinsService->buildJob($jobName);
} catch (\Exception $e){
// todo log日志
$res = false;
}
return $res;
}
标签:return,jobName,job,api,jenkins,php
From: https://www.cnblogs.com/alisleepy/p/16815185.html