Jenkins的版本是:Jenkins2.138.1
实现的操作接口:
using System;
using System.Collections.Generic; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins上创建项目
/// </summary>
public interface IJenkinsOperate: IDisposable
{
/// <summary>
/// 构建jenkins项目
/// </summary>
/// <param name="projectName"></param>
/// <returns></returns>
bool BuildJenkinsProject(string projectName);
/// <summary>
/// 在jenkins上创建项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <param name="info"></param>
/// <returns></returns>
bool CreateJenkinsProject(string projectName, out string info);
/// <summary>
/// 删除jenkins上的项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
bool DeleteJenkinsProject(string projectName); /// <summary>
/// Jenkins 项目列表
/// </summary>
/// <returns></returns>
List<JenkinsJobDto> ListJenkinsProject();
/// <summary>
/// 登录
/// </summary>
/// <param name="j_username">jenkins用户名</param>
/// <param name="j_password">jenkins密码</param>
/// <returns></returns>
bool LoginJenkins(string j_username, string j_password);
/// <summary>
/// 重新加载配置文件,用于手动修改项目的config文件后刷新数据用。
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
bool ReloadJenkinsProject(string projectName);
}
}
实现类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins上创建项目
/// </summary>
public class JenkinsOperate : IJenkinsOperate
{
/// <summary>
/// 写日志
/// </summary>
public static Action<string> writeLogAction;
private static void writeLog(string msg)
{
msg = "[JenkinsOperate]" + msg;
writeLogAction?.Invoke(msg);
Console.WriteLine(msg);
}
static string _j_username = "xxxxx";//这里填入用户名........................................
static string _j_password = "xxxxx";//这里填入密码...............................
static string jenkins_crumb = "568be69f9ad6a3a479c13e71d07b31f7";
static JenkinsOperate()
{
string j_usernameStr = System.Configuration.ConfigurationManager.AppSettings["j_username"];
string j_passwordStr = System.Configuration.ConfigurationManager.AppSettings["j_password"];
string jenkins_crumbStr = System.Configuration.ConfigurationManager.AppSettings["jenkins_crumb"];
_j_username = string.IsNullOrEmpty(j_usernameStr) ? _j_username : j_usernameStr;
_j_password = string.IsNullOrEmpty(j_passwordStr) ? _j_password : j_passwordStr;
//测试用从配置文件读取。
jenkins_crumb = string.IsNullOrEmpty(jenkins_crumbStr) ? jenkins_crumb : jenkins_crumbStr;
}
System.Net.Http.HttpClient client = new HttpClient(); string jenkinsBaseUrl = "http://127.0.0.1:8080/"; /// <summary>
/// Jenkins 操作
/// </summary>
/// <param name="_jenkinsBaseUrl">Jenkins地址,如:http://xxx.xxx.xxx.xxx:8080</param>
public JenkinsOperate(string _jenkinsBaseUrl)
{
string jenkinsBaseUrlStr = System.Configuration.ConfigurationManager.AppSettings["jenkinsBaseUrl"];
jenkinsBaseUrl = string.IsNullOrEmpty(jenkinsBaseUrlStr) ? jenkinsBaseUrl : jenkinsBaseUrlStr;
if (!string.IsNullOrEmpty(_jenkinsBaseUrl))
{
jenkinsBaseUrl = _jenkinsBaseUrl;
}
} /// <summary>
/// 登录
/// </summary>
/// <param name="j_username">jenkins用户名</param>
/// <param name="j_password">jenkins密码</param>
/// <returns></returns>
public bool LoginJenkins(string j_username, string j_password)
{
if (string.IsNullOrEmpty(j_username)) { j_username = _j_username; }
if (string.IsNullOrEmpty(j_password)) { j_password = _j_password; }
string loginUrl = string.Format("{0}/j_acegi_security_check", jenkinsBaseUrl);
object obj = new { j_username = j_username, j_password = j_password };
var objJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
List<KeyValuePair<String, String>> loginParamList = new List<KeyValuePair<String, String>>();
loginParamList.Add(new KeyValuePair<string, string>("j_username", j_username));
loginParamList.Add(new KeyValuePair<string, string>("j_password", j_password)); var loginPara = new FormUrlEncodedContent(loginParamList);
var loginResponseMessage = client.PostAsync(loginUrl, loginPara).Result;
var loginStr = loginResponseMessage.Content.ReadAsStringAsync().Result;
writeLog("[loginStr]" + loginStr);
if (loginStr.Contains("登录"))
{
return false;
} //获取Jenkins-Crumb
string jenkinsCrumbStr = "\"Jenkins-Crumb\", \"";
var index = loginStr.IndexOf(jenkinsCrumbStr);
writeLog("[loginStr] jenkinsCrumbStr Index:" + index);
if (index == -)
{
return false;
}
var indexStart = index + jenkinsCrumbStr.Length;
var indexEnd = loginStr.IndexOf("\");", indexStart);
writeLog("[loginStr] jenkinsCrumbStr indexEnd:" + indexEnd);
if (indexEnd == -)
{
return false;
}
string jenkinsCrumb = loginStr.Substring(indexStart, indexEnd - indexStart);
jenkins_crumb = jenkinsCrumb;
return true;
} /// <summary>
/// 在jenkins上创建项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <param name="info"></param>
/// <returns></returns>
public bool CreateJenkinsProject(string projectName, out string info)
{
info = "ok"; //验证名称
string checkNameUrl = string.Format("{0}/view/all/checkJobName?value={1}", jenkinsBaseUrl, projectName);
var checkResult = client.GetAsync(checkNameUrl).Result;
var checkStr = checkResult.Content.ReadAsStringAsync().Result; writeLog("[CreateJenkinsProject] checkStr:" + checkStr);
if (checkStr != "<div/>")
{
info = "已存在项目名称";
return false;
} //创建新项目
string createItemUrl = string.Format("{0}/view/all/createItem", jenkinsBaseUrl);
List<KeyValuePair<String, String>> createParamList = new List<KeyValuePair<String, String>>();
createParamList.Add(new KeyValuePair<string, string>("name", projectName));
createParamList.Add(new KeyValuePair<string, string>("mode", "hudson.model.FreeStyleProject"));
createParamList.Add(new KeyValuePair<string, string>("from", ""));
createParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb));
createParamList.Add(new KeyValuePair<string, string>("json", string.Format("{{'name': '{0}', 'mode': 'hudson.model.FreeStyleProject', 'from': '', 'Jenkins-Crumb': '{1}'}}", projectName, jenkins_crumb)));
var createPara = new FormUrlEncodedContent(createParamList);
var createResponseMessage = client.PostAsync(createItemUrl, createPara).Result;
var createStr = createResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[CreateJenkinsProject] createStr:" + createStr);
if (createResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
} /// <summary>
/// 删除jenkins上的项目
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
public bool DeleteJenkinsProject(string projectName)
{
//删除
string deleteUrl = string.Format("{0}/job/{1}/doDelete", jenkinsBaseUrl, projectName); List<KeyValuePair<String, String>> deleteParamList = new List<KeyValuePair<String, String>>();
deleteParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb)); var deletePara = new FormUrlEncodedContent(deleteParamList);
var deleteResponseMessage = client.PostAsync(deleteUrl, deletePara).Result;
var deleteStr = deleteResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[DeleteJenkinsProject] deleteStr:" + deleteStr);
if (deleteResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
}
/// <summary>
/// 构建jenkins项目
/// </summary>
/// <param name="projectName"></param>
/// <returns></returns>
public bool BuildJenkinsProject(string projectName)
{
string buildUrl = string.Format("{0}/job/{1}/build?delay=0sec", jenkinsBaseUrl, projectName);
List<KeyValuePair<String, String>> buildParamList = new List<KeyValuePair<String, String>>(); var buildPara = new FormUrlEncodedContent(buildParamList);
client.DefaultRequestHeaders.Add("Jenkins-Crumb", jenkins_crumb);
var buildResponseMessage = client.PostAsync(buildUrl, buildPara).Result;
var buildStr = buildResponseMessage.Content.ReadAsStringAsync().Result;
writeLog("[BuildJenkinsProject] buildStr:" + buildStr);
if (buildResponseMessage.StatusCode == HttpStatusCode.Created)
{
return true;
}
return false;
}
/// <summary>
/// Jenkins 项目列表
/// </summary>
/// <returns></returns>
public List<JenkinsJobDto> ListJenkinsProject()
{
var listUrl = $"{jenkinsBaseUrl}/api/json?pretty=true";
var listResult = client.GetAsync(listUrl).Result;
var listStr = listResult.Content.ReadAsStringAsync().Result;
var jobList = Newtonsoft.Json.JsonConvert.DeserializeObject<JenkinsDto>(listStr);
if (jobList != null && jobList.jobs != null)
{
return jobList.jobs;
}
return new List<JenkinsJobDto>();
}
/// <summary>
/// 重新加载配置文件
/// </summary>
/// <param name="projectName">项目名称</param>
/// <returns></returns>
public bool ReloadJenkinsProject(string projectName)
{
var reloadUrl = $"{jenkinsBaseUrl}/job/{projectName}/reload"; List<KeyValuePair<String, String>> reloadParamList = new List<KeyValuePair<String, String>>();
reloadParamList.Add(new KeyValuePair<string, string>("Jenkins-Crumb", jenkins_crumb)); var reloadPara = new FormUrlEncodedContent(reloadParamList);
var reloadResponseMessage = client.PostAsync(reloadUrl, reloadPara).Result;
var reloadStr = reloadResponseMessage.Content.ReadAsStringAsync().Result; writeLog("[ReloadJenkinsProject] reloadStr:" + reloadStr);
if (reloadResponseMessage.StatusCode == HttpStatusCode.OK)
{
return true;
}
return false;
} /// <summary>
/// 销毁数据
/// </summary>
public void Dispose()
{
client.Dispose();
}
}
}
dto对象:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace iHRPublish.Utility
{
/// <summary>
/// Jenkins job
/// </summary>
public class JenkinsJobDto
{
/// <summary>
/// job类型
/// 如:hudson.model.FreeStyleProject
/// </summary>
public string _class { get; set; }
/// <summary>
/// 项目名称
/// 如:iHR-Hardware-GuangBen
/// </summary>
public string name { get; set; }
/// <summary>
/// jenkins地址
/// 如: http://127.0.0.1:8080/job/iHR-Hardware-GuangBen/
/// </summary>
public string url { get; set; }
/// <summary>
/// 状态
/// 如:notbuilt,blue
/// </summary>
public string color { get; set; }
}
/// <summary>
///
/// </summary>
public class JenkinsDto
{
/// <summary>
/// jobs
/// </summary>
public List<JenkinsJobDto> jobs { get; set; }
}
}
调用方法:
//在jenkins上创建项目
string jenkinsHost = "http://127.0.0.1:8080";
string jenkinsLoginUserName = "admin";
string jenkinsLoginPwd = "123456";
string projectName = "项目名称";
using (JenkinsOperate jOperate = new JenkinsOperate(dto.jenkinsHost))
{
bool loginSuccess = jOperate.LoginJenkins(jenkinsLoginUserName, jenkinsLoginPwd);
if (!loginSuccess)
{
return ResultHelper.QuickReturnError(false, "Login_Jenkins_Fail", "登录Jenkins失败");
}
string info;
//创建项目
bool createSuccess = jOperate.CreateJenkinsProject(projectName, out info);
if (!createSuccess)
{
return ResultHelper.QuickReturnError(false, "Create_Jenkins_Project_Fail", "创建Jenkins项目失败:" + info);
}
//生成项目
bool createSuccess = jOperate.BuildJenkinsProject(dto.projectName);
if (!createSuccess)
{
return ResultHelper.QuickReturnError(false, "Build_Jenkins_Project_Fail", "创建Jenkins项目失败");
}
//列出所有项目
var list = jOperate.ListJenkinsProject();
if(list == null || list.Count == 0)
{
return ResultHelper.QuickReturnError<List<JenkinsJobDto>>(null, "Not_Find_Any_Project", "未查询到任何项目");
}
//删除项目
bool createSuccess = jOperate.DeleteJenkinsProject(projectName);
if (!createSuccess)
{
return ResultHelper.QuickReturnError(false, "Delete_Jenkins_Project_Fail", "删除Jenkins项目失败");
}
}