首页 > 解决方案 > 如何在詹金斯 delarative piepline 中获取会话数据

问题描述

我不想从 CurrentBuild 或 CurrentUser 使用,因为这会返回构建工作的用户信息,但我想获取登录到 jenkins 的用户信息。例如由计时器运行的作业 X 和一个用户将中止这个,我想找到哪个用户中止了这个作业。

标签: groovyjenkins-groovyjenkins-declarative-pipeline

解决方案


您可以使用以下代码。请注意,当您要执行此代码时,您必须通过转到“管理 Jenkins/in process script Approval”并批准它们可执行来允许运行这些方法。通过使用此代码,您不仅可以在手动运行作业中也可以在计时器运行中了解谁中止了 Jenkins 管道。

pipeline {
agent any
triggers{cron("*/1 * * * *")}
stages {
    stage('Hello') {
        steps {
            sleep(20000)
            
            echo 'Hello World'
        }
    }
}
post{
    aborted{
        script{
            def causee = ''
            def actions = currentBuild.getRawBuild().getActions(jenkins.model.InterruptedBuildAction)
            for (action in actions) {
                def causes = action.getCauses()
        
                // on cancellation, report who cancelled the build
                for (cause in causes) {
                    causee = cause.getUser().getDisplayName()
                    cause = null
                }
                causes = null
                action = null
            }
            actions = null
        
            echo causee
        }
        
    }
}

}


推荐阅读