如何在Jenkins Delarative Piepline中获取会话数据

问题描述

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

解决方法

您可以使用以下代码。注意,当您要执行此代码时,必须允许运行这些方法,方法是转到“管理Jenkins /进程内脚本批准”并批准它们可执行。通过使用此代码,您不仅可以在手动运行的作业中,还可以在计时器运行的情况下,使谁中止了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
        }
        
    }
}

}