Reputation: 309
I have a requirement in Jenkins pipeline where in after the successful build I need an user input to proceed or abort. The developers are only intended for deployment into Dev environment and Ops people can do on QA and Prod.
My issue is if I login as dev into Jenkins and execute build and deploy for QA or Prod after build then it should display a message as not authorized to do deployment on QA or Prod. The Dev team will inform Ops team to carry further deployment in pipeline. The Ops people will login with their credential and when they trigger the procced or abort for deployment to QA or Prod it should happen.
My issue how to get current logged user of Jenkins so that I can validate the user and carry on with deployment.
stage('confirmDeploy'){
inputMessage("${TARGET_PLATFORM}")
echo "Deploying release on ${TARGET_PLATFORM} environment"
}
def inputMessage(String inputEnvName) {
timeout(time: 1, unit: 'HOURS') {
input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'
wrap([$class: 'BuildUser']) {
sh 'echo "${BUILD_USER}"'
if (( "${inputEnvName}" == "qa" && "${BUILD_USER}" == "ops")||( "${inputEnvName}" == "prod" && "${BUILD_USER}" == "ops")){
input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'}
else if (( "${inputEnvName}" == "dev" && "${BUILD_USER}" =="devuser")){
input message: "Are you sure to promote this build to ${inputEnvName} env ?", ok: 'deploy'}
else {
echo 'Further code will not be executed'echo "Not authorized to carry deployment to the respective environment", ok: 'deploy'
}
}
}
}
Upvotes: 5
Views: 20327
Reputation: 50191
Try these (3 different possible ways):
currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()
currentBuild
.getBuildCauses('hudson.model.Cause$UserIdCause')[0]
?.userId ?: 'default'
def causes = currentBuild.rawBuild.getCauses()
// loop over each `cause`
if (cause.class.name == 'hudson.model.Cause$UserIdCause') {
// use properties of `cause` object.
}
It appears, though I haven't confirmed, that you can get userId
or userName
from the cause
object. userId
appears to be an email address for some installations, though this may be configurable for other values there.
Upvotes: 2
Reputation: 7881
You can use shell to run user id command and same in Jenkins variable.
environment {
SH_BUILD_USER_ID = sh (
script: 'id -u',
returnStdout: true
).trim()
}
where 'id -u' is Linux command to fetch userid. You can use any command to get its data and use in Jenkins pipeline
Upvotes: -1
Reputation: 1346
you need following code:
wrap([$class: 'BuildUser']) {
def user = env.BUILD_USER_ID
}
Note: this is assuming that you have https://wiki.jenkins-ci.org/display/JENKINS/Build+User+Vars+Plugin installed
Upvotes: 11