从Jenkins脚本控制台访问Slack插件

时间:2017-12-25 18:07:40

标签: jenkins groovy jenkins-pipeline

我想知道是否可以从Jenkins脚本控制台模拟管道插件操作。例如,Slack插件用于通过管道作业发送通知,命令为:

  

slackSend(color:colorCode,message:summary)

我想尝试一下,看看对象和属性。我非常确定Jenkins脚本控制台可以使用groovy。

1 个答案:

答案 0 :(得分:1)

我发现它通常需要查看源代码。在这种情况下,源代码位于jenkinsci/slack-plugin的GitHub上。

以下是我要做的步骤:

我在查看代码时注意到的主要部分是使用提供给步骤的参数创建StandardSlackService,并且可能来自全局Jenkins配置。

如果你想从脚本控制台执行它,可以稍微调整和调整这段代码,因为很难以管道路径的方式执行它。

以下是我认为相关的参考代码:

SlackService slackService = getSlackService(baseUrl, team, token, tokenCredentialId, botUser, channel);
boolean publishSuccess;
if(step.attachments != null){
    JsonSlurper jsonSlurper = new JsonSlurper();
    JSON json = null;
    try {
        json = jsonSlurper.parseText(step.attachments);
    } catch (JSONException e) {
        listener.error(Messages.NotificationFailedWithException(e));
        return null;
    }
    if(!(json instanceof JSONArray)){
        listener.error(Messages.NotificationFailedWithException(new IllegalArgumentException("Attachments must be JSONArray")));
        return null;
    }
    JSONArray jsonArray = (JSONArray) json;
    for (int i = 0; i < jsonArray.size(); i++) {
        Object object = jsonArray.get(i);
        if(object instanceof JSONObject){
            JSONObject jsonNode = ((JSONObject) object);
            if (!jsonNode.has("fallback")) {
                jsonNode.put("fallback", step.message);
            }
        }
    }
    publishSuccess = slackService.publish(jsonArray, color);
}else{
    publishSuccess = slackService.publish(step.message, color);
}
if (!publishSuccess && step.failOnError) {
    throw new AbortException(Messages.NotificationFailed());
} else if (!publishSuccess) {
    listener.error(Messages.NotificationFailed());
}
// rest of method...

// ...

//streamline unit testing
SlackService getSlackService(String baseUrl, String team, String token, String tokenCredentialId, boolean botUser, String channel) {
    return new StandardSlackService(baseUrl, team, token, tokenCredentialId, botUser, channel);
}
相关问题