Jenkins Java: Get user who started the build

后端 未结 2 1833
生来不讨喜
生来不讨喜 2021-01-13 18:52

Under http://[JENKINS_NAME]/job/[JOB_NAME]/[BUILD_NUMBER]/

I can see Started by user [USER_NAME].

I want to get that username f

相关标签:
2条回答
  • 2021-01-13 19:23

    You could get the build user from Jenkins environment (i.e as an env var). If you use Jenkins 2 pipeline, For example: pipeline {

     //rest of the pipeline
     stages {
       stage('Build Info') {
         steps {
           wrap([$class: 'BuildUser']) {
            sh 'java -jar <your_java_app>.jar'
           }
         } 
       }
     }
    

    In your java app you should be able to get the environment variable using System.getenv("BUILD_USER") or else you could pass it as a JVM arg. Ex: sh 'java -jar -DbuildUser=$BUILD_USER <your_java_app>.jar' and get the buildUser system property in the application.

    On older version of Jenkins, you may use Build User Vars Plugin or Env Inject plugin. As in the answers on this question. how to get the BUILD_USER in Jenkins when job triggered by timer

    0 讨论(0)
  • 2021-01-13 19:32

    You can make a http call to get all these details. URL to get those details is:

    http://<Jenkins URL>/job/<job name>/<build number>/api/json
    

    After the rest call, you will be getting this json.

    {
    "_class": "hudson.model.FreeStyleBuild",
    "actions": [
        {
            "_class": "hudson.model.CauseAction",
            "causes": [
                {
                    "_class": "hudson.model.Cause$UserIdCause",
                    "shortDescription": "Started by user XXXXXX",
                    "userId": "xxx@yyy.com",
                    "userName": "ZZZZZZZZ"
                }
            ]
        },
        {},
        {
            "_class": "jenkins.metrics.impl.TimeInQueueAction"
        },
        {},
        {}
    ],
    ...
    }
    

    So All you have do is parse this json and get the value under javavar['actions'][0]['causes'][0]['userName']. Definitely it will be like that only. I maynot be sure about the indexes. You just try and figure out. Hope this helps.

    Mostly for every page in the jenkins instance, you will be having REST API link. Please click on it to see the rest api url and its output for that url.

    0 讨论(0)
提交回复
热议问题