I implemented jenkins build script.
That script started by remote server. ( using Build Triggers )
In build console Output log, wrote down
"Started by remote host xx.xx.xxx.xxx (my ip)"
I want to know remote host that called jenkins build job in pipeline script.
Any ideas??
Thank you.
set an environment variable BUILD_CAUSES in your Jenkins pipeline script. Which will save all build information
You can access it by jenkins file
def remoteHost = ''
for (cause in currentBuild.getCauses()) {
if (cause instanceof Cause.RemoteCause) {
remoteHost = cause.getAddr()
break
}
}
println "Remote host IP: ${remoteHost}"
To set environment variable
click on the job where you want to set the variable from homepage.
Go to "Configure" link for your job.
Go to "Build Environment" section.
Check the "Set environment variables" checkbox.
In the "Name" field, enter "BUILD_CAUSES".
In the "Value" field, enter the desired value for the BUILD_CAUSES
variable.
Click the "Save" button to save your changes.
Related
I have created a jenkins parameterized pipeline script as below. I have stored it on my Github repository.
properties([parameters([string(defaultValue: 'Devasish', description: 'Enter your name', name: 'Name'),
choice(choices: ['QA', 'Dev', 'UAT', 'PROD'], description: 'Where you want to deploy?', name: 'Environnment')])])
pipeline {
agent any
stages {
stage('one') {
steps {
echo "Hello ${Name} Your code is Building in ${Environnment} "
}
}
stage('Two') {
steps {
echo "Hello ${Name} hard testing in ${Environnment}"
}
}
stage('Three') {
steps {
echo "Hello1 ${Name} deploying in ${Environnment}"
}
}
}
}
Then, I have created a jenkins job by choosing pipeline option. While creating jenkins pipeline Under build triggers section, I have checked GitHub hook trigger for GITScm polling checkbox and Under Pipeline section, I have chosen Pipeline script from SCM followed by choosing Git in SCM, providing Repository URL where the above written JenkinsFile script is stored.
Then, Under Github repository settings, I have gone to webhooks and added one webhook where I specified my Payload URL as myJenkinsServerURL/github-webhook/. which will enable a functionality like whenever there will be any push event occurred within the repository, it will run the jenkins pipeline I created above.
Now, the situation is, when I am running this jenkins job from Classic UI by clicking Build with parameters, I am getting a text box to fill my name and a dropdown having list of 4 options ('QA', 'Dev', 'UAT', 'PROD') I gave above in script to choose, in which server I want to deploy my code, then it gets run.
But when I am committing in Github, it starts jenkins pipeline but not asking for parameters value instead just taking default value Devasish in name and QA in server.
What should I do to get an option of filling these details but not from Classic UI.
Thanks in advance.
As you have noted, when you trigger your pipeline manually, it will ask for the Build Parameters and let you specify values before proceeding.
However, when triggering the pipeline thru automatic triggers (e.g. SCM triggers/webhooks), then it is assumed to be an unattended build and it will use the defaultValue settings from your Jenkinsfile build parameters" definition.
I'm using this Jenkins plugin: https://wiki.jenkins-ci.org/display/JENKINS/Build+User+Vars+Plugin
With this plugin installed, if you check the box "Set jenkins user build variables", you can use the environment variable ${BUILD_USER} which gives the name of the person who built the Jenkins job.
But, I can't get the plugin to work with the Pipeline plugin (https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin).
I noticed that checking that "Set jenkins user build variables" box adds the following line to the config.xml of your Jenkins job: <org.jenkinsci.plugins.builduser.BuildUser plugin="build-user-vars-plugin#1.5"/>
So I tried the following:
import org.jenkinsci.plugins.builduser.BuildUser
echo "${env.BUILD_USER}"
But it prints out null.
try use this variable:
def USER = wrap([$class: 'BuildUser']) {
return env.BUILD_USER
}
I used here and It worked !!
I wanted to have 2-factor authentication in Jenkins for all the users (even super admin) and wanted to know, if it's possible and if it is, what is the possible way or do we need a plugin for it.
Plus can we have authorization for scheduling the deployment in Jenkins and if it's possible, how can we do it.
Jenkins authorization is explained in detail here:
https://wiki.jenkins-ci.org/display/JENKINS/Standard+Security+Setup
The "Authorize Project plugin" is not for what you are asking.
You will not be prompted for password everytime you start a job. Instead, you should configure individual jobs to give access to individual people. Jenkins allows that granularity.
If you really want to prompt for password at every job execution, you will have to configure job to create a new password parameter, and then as one of your first build steps, validate the entered password against... against whatever it is that you want. But that means your validation script will probably reside on Jenkins itself.
Edit:
Configure Job
Select "This build is parameterized"
Add "String" parameter
Call it "password"
If on *nix environment, select "Execute Shell" for the first build step:
set +x
if ! [[ "$password" == "mysecret" ]]; then
echo "Bad password"
exit 1
fi
exit 0
If on Windows environment, select "Execute Windows batch command" for the first build step:
#echo off
if not "%password%" == "mysecret" (
echo "Bad password"
exit /b 1
)
exit /b 0
Add other build steps as normal.
Now, every time the job runs, it will prompt for "password", and if it doesn't match string "mysecret", the job will fail.
Important Notes:
This will run after SCM checkout. If you want to run it before SCM checkout, you'd need Pre-SCM build step plugin.
Anyone with "Configuration" access to the job permission or above will be able to see the "mysecret" in plain text. You can use EnvInject plugin to configure global (or job local) password and validate against that variable, instead of "mysecret"
Anyone with direct/remote login to the Jenkins machine will be able see the configuration file with "mysecret" in plain text (unless using EnvInject from above).
People with enough permissions could modify or copy the job, and remove this validation.
Once again, I implore you that the correct approach is to provide granular per-user permissions through default Jenkins security/authorization. Use "matrix" authorization to give permissions per user per job.
I installed the Feature Branch Notifier Plugin in my instance of Jenkins.
I have checked the "Show full length branch name in the build history view" checkbox at jenkins:8080/configure
I am expecting to see the branch names in build history view, but even after restarting Jenkins I am not seeing the branch names in the build history, as can be seen in the enclosed image.
The project issue queue lists no open issues, and when I try to log in to post an issue, I get the message "Proxy Error - The proxy server received an invalid response from an upstream server. The proxy server could not handle the request POST /account/doSignup. Reason: Error reading from remote server Apache/2.2.14 (Ubuntu) Server at jenkins-ci.org Port 443"
Does anyone know how to go about seeing the branch name of builds in the build history view of Jenkins? Thanks!
Albert.
You can use Build Name Setter Plugin, and set Set Build Name something like #${BUILD_NUMBER} - ${GIT_BRANCH}.
Build-Name-setter-plugin no longer works. I tried on 2.319.1, and the setting never appears in the pipline.
The solution I found is to use the build environment variables to apply to your display name for the build in a step script.
Adjust your Jenkinsfile to pull the branch name as a environmental variable (I am using CURRENT_BRANCH_NAME). Then I created a new stage / step, that runs before any other, and ran a script to adjust the displayname there:
pipeline {
agent {any}
environment {
CURRENT_BRANCH_NAME = "${GIT_BRANCH.split('/').size() > 1 ? GIT_BRANCH.split('/')[1..-1].join('/') : GIT_BRANCH}"
}
stages {
stage('Set branch name') {
steps {
script{
currentBuild.displayName = "#"+currentBuild.number+": "+CURRENT_BRANCH_NAME
}
}
}
stages {
stage('Ok now start doing testing') {
steps {
sh '''#!/bin/bash
echo "Im gona test everything"
'''
}
}
}
}
Now when your Jenkins test starts to build, the name will update once the step is complete.
Note: this solution was tested in a single pipeline (not multi-pipeline), and was for a SCM repo integration.
Sources:
Get git branch name in Jenkins Pipeline/Jenkinsfile
https://sleeplessbeastie.eu/2021/01/29/how-to-define-build-name-and-description-in-jenkins/
I have a Jenkins job that is doing the following (amongst other things):
Read user input for ENVIRONMENT and SERVERTYPE
Inject environment variable AGENT (initially blank) as a build step to create
a new variable
Execute shell as a build step to populate AGENT, based on what was entered
in ENVIRONMENT and SERVERTYPE
Use AGENT as an input to a plugin as a post build action
The problem is that the value of AGENT doesn't seem to persist outside of the "execute shell" build step. When I try and pass it into the post build action plugin, it's still blank.
Can anyone point out what am I doing wrong? I have read the documentation, but can't seem to figure it out.
Your problem is that whatever variables you set in the shell script, they don't make it out.
This is true for any process: child process (your shell script) can never directly affect environment of parent process (Jenkins executor client).
If you need the data to persist, you need to store it outside the script; there are many options like uploading it to a server or storing it in a database, the most obvious and easiest option is to save it to a file.
You can even save the value to a "properties file" in the syntax supported by EnvInject and specify path in "Properties File Path" field.
You need to populate properties file with the values of the environment variables to be injected again, so they will survive until post-build actions. The properties file usually resides in the job's workspace.
For example use the following steps:
Build step "Execute shell" :
AGENT="My agent"
echo AGENT=$AGENT > my.properties
Build step: "Inject environment variables",
Field "Properties File Path":
$WORKSPACE/my.properties
Post-Build Actions: "Editable Email Notification", Field "Default Content":
Current Agent $AGENT
Or ${ENV, var="AGENT"}