Want to know which Jenkins job is executing now, in java - java

I have 3 Jenkins job. Below are the name of those Jenkins job:
test_existing_api
test_others_api
test_new_api
I have a config file in java project which have 3 different configuration. I want to pick the configuration depend upon Jenkins job. So first I want to check which Jenkins job is executing and then I will take configuration according to that job. That configuration will further require in java code.
Please help me to understand how can I check which Jenkins job is executing now in Java.

Assuming you want to get this data within the job that is executing, see manual entry:
Jenkins Set Environment Variables
When a Jenkins job executes, it sets some environment variables that you may use in your shell script, batch command, Ant script or
Maven POM 1. The following table contains a list of all of these
environment variables.
Environment Variable Description
BUILD_NUMBER The current build number, such as "153"
BUILD_ID The current build id, such as "2005-08-22_23-59-59" (YYYY-MM-DD_hh-mm-ss)
BUILD_URL The URL where the results of this build can be found (e.g. http://buildserver/jenkins/job/MyJobName/666/)
NODE_NAME The name of the node the current build is running on. Equals 'master' for master node.
JOB_NAME Name of the project of this build. This is the name you gave your job when you first set it up. It's the third column of the Jenkins Dashboard main page.
BUILD_TAG String of jenkins-${JOB_NAME}-${BUILD_NUMBER}. Convenient to put into a resource file, a jar file, etc for easier identification.
JENKINS_URL Set to the URL of the Jenkins master that's running the build. This value is used by Jenkins CLI for example
EXECUTOR_NUMBER The unique number that identifies the current executor (among executors of the same machine) that's carrying out this build. This is the number you see in the "build executor status", except that the number starts from 0, not 1.
JAVA_HOME If your job is configured to use a specific JDK, this variable is set to the JAVA_HOME of the specified JDK. When this variable is set, PATH is also updated to have $JAVA_HOME/bin.
WORKSPACE The absolute path of the workspace.
SVN_REVISION For Subversion-based projects, this variable contains the revision number of the module. If you have more than one module specified, this won't be set.
CVS_BRANCH For CVS-based projects, this variable contains the branch of the module. If CVS is configured to check out the trunk, this environment variable will not be set.
GIT_COMMIT For Git-based projects, this variable contains the Git hash of the commit checked out for the build (like ce9a3c1404e8c91be604088670e93434c4253f03) (all the GIT_* variables require git plugin)
GIT_URL For Git-based projects, this variable contains the Git url (like git#github.com:user/repo.git or https://github.com/user/repo.git)\\
GIT_BRANCH For Git-based projects, this variable contains the Git branch that was checked out for the build (normally origin/master)
Sorry about bad formatting (SO doesn't support nice tables), but you should be able to retrieve these variables with System.getEnv(). This means you don't need to add anything to your Jenkins configuration, just read from java what it already sets.

http://<Jenkins_server>/job/<Job_name>/lastBuild/api/xml?depth=1
Above url will give you the xml structured data, in which you can check <building>false</building> tag value from your java code by parsing the xml.
If value is true than jenkins job is running at the time.
To check which of given three job is running, you can check the status of each job by parsing xml in java code for each job and get configuration file of running job.
P.S. : Replace the place holders in url with applicable data. <Jenkins_server> and <Job_name>

You could pass a system property from the job to the JVM when launching the project:
...whatever... -Dconfig=test_existing_api
and retrieve it in your classes with:
System.getProperty("config")

Related

TeamCity :: How can I access teamcity build ID in Java

Teamcity Build ID (which is different from BUILD_NUMBER) is used in various URLs. I want to send an email having path of a build's artifacts/ overview etc.
In Java, we can get currently running teamcity build number as follows:
String tc_BuildNumber = System.getenv("BUILD_NUMBER");
This is because TC provides an environment variable namely BUILD_NUMBER.
But unfortunately, there is no environment variable corresponding to BUILD_ID.
TeamCity does provide Configuration parameters (like teamcity.build.id) and System property (like system.teamcity.auth.userId) but I don't know how to access these using Java. I want to read the value of teamCity.build.id jusy like we can read environment variables names mentioned in How to fetch the Value of Teamcity Configuration in java?
Are you executing the java code using a build runner?
If so, then you should be able to pass %system.teamcity.build.id% to the runner, and make it available to your code.
i.e. If you're using the command line runner
java -Dbuild_id=%system.teamcity.build.id%
which you can then access as system arguments
Or if you're using gradle, you can do something like
if (project.hasProperty("teamcity")) {
version = project.teamcity["teamcity.build.id"]
}
and pass 'version' to the java command line.
In maven, you can just access it using:
${teamcity.build.id}
in your pom.xml
(I could do with a little more info about how you're running java to answer this specifically)
I've noticed that lots of people want to know the answer to this question.
Fortunately with the help of comment from #Jayan I was able to do solve my exact problem which was how to get URL for build artifacts.
As mentioned in link https://confluence.jetbrains.com/display/TCD10/Patterns+For+Accessing+Build+Artifacts, by default, TeamCity uses Internal Build ID for the path that can be used to access build artifacts:
/repository/download/BUILD_TYPE_EXT_ID/BUILD_ID:id/ARTIFACT_PATH
Accessing build Id could be difficult in the runtime(That is the reason of this question), but we can also use Build Number to access artifacts
/repository/download/BUILD_TYPE_EXT_ID/BUILD_NUMBER/ARTIFACT_PATH
And as shown in my question build number can be accessed as
String BUILD_NUMBER= System.getenv("BUILD_NUMBER");
and
String BUILD_TYPE_EXT_ID = System.getenv("TEAMCITY_BUILDCONF_NAME");
Yes, but you can create env var with value "%system.teamcity.buildType.id%" and read it in build. After that you can do an api request like:
$APIURL = "${API_BaseUrl}/httpAuth/app/rest/builds/?locator=buildType:${API_BuildType},state:running,count:1"
$APIXML = (Invoke-RestMethod -Headers $API_CredentialsHeader -Credential $API_Credentials -Uri $APIURL -Method GET -ContentType "application/xml" -TimeoutSec 20)
# Here you build id.
$APIXML.builds.build.id
This is PS example. But idea the same. In Java that might be more easy.
A link to a TeamCity build can use build number instead of buildID. But, it requires buildTypeId as well (can be seen in build configuration page URL).
A sample of such link is:
https://buildserver/viewLog.html?buildTypeId=Project_Trunk&buildNumber=46523
Hope this helps someone.

Java not finding environment variables defined in Jenkins

I have a snippet of code that is obtaining an environment variable as follows: System.getenv("MY_VAL")
locally on my windows machine this works fine.
However, on my Jenkins CI Server which is running CentOS I am encountering some issues
I have tried setting the value of MY_VAL through both the envinject plugin as well as the global jenkins settings
If i do a pre-build step to echo the value out, it works fine, however inside my java code this is not being resolved.
How do I get this to be resolved?
You can achieve that by installing EnvInject plugin.
1) After installing check the Prepare an environment for the job option in the job configuration screen. This option will display several field for you to fill.
UPDATE
2) Fill the Script Content area with a command touch env.properties to create the file.
3) Fill the Properties Contentt field with the variables you want to inject inside your recently created env.properties file by doing so. Place one variable per line ex:
VARIABLE1=value
VARIABLE2=value
4) Reference env.properties file you've just created in the file path area.
5) At runtime Jenkins will inject those variables and they will be available to your program.
You need to inject this variable into property.file and then access this from property file. e.g. in execute shell you can define "echo MY_VAL=default > property.file" .. Later in subsequent jobs you can pass through using "Jenkins Parameterized Trigger plugin" where you have option to access parameters from property file.

How to make .properties read parameters from Jenkins

I use Jenkins to run regression periodically
I have java-maven project with 'ATC.properties' where I can choose browser, environment etc. by uncommenting appropriate one
#### browser ######
browser.name=firefox
#browser.name=chrome
#browser.name=ie
So I have to commit it, push and only after that job on Jenkins will run build with chosen parameters in 'ATC.properties' as well
How can I make my maven project read parameters from parametrised Jenkins build.
Can any one give me some example with browser ?
Do I have to use another one '.properties' file with described variables
like
browser.name=${browser.name} ...
in my project ?
Parameters defined in Jenkins will be expanded at run in Maven Build , Below process does not require additional property file :
Define jenkins choice parameter :
browser_name
Provide all your Browsers options as choices and select the required option at run time.
Now replace your pom.xml with ${browser_name} where you required the option of reading browser value instead of reading value from property file.
pass parameter at run time as below
mvn clean install -Dbrowser_name=%browser_name% [incase of windows]
mvn clean install -Dbrowser_name=$browser_name [incase of linux]

How to buld a Maven project with a specified java home property in eclipse?

I want to build a maven integrated project with a given java home property. At exactly i want to write a code in java that sets the java home property for an InvocationRequest object. The main goal is to build a project with the runtime given(by an algorithm) java home. So i would call getInvoker().execute(request); to execute maven goals where request is an InvocationRequest object.
I tried to set the request java.home property with properties.setProperty(Goals.JAVA_HOME, javaHomePath); and call the method executeGoals(pom, new String[] { Goals.INSTALL, Goals.CLEAN }, properties); . This executeGoals(...) method contains getInvoker().execute(request) call and the request object definition too.
Output is: Missing: 1) com.sun:tools:jar:1.5.0 #Solved
EDIT: solved the output problem, but a new one appeared:
class file has wrong version 50.0, should be 49.0. Maybe i changed the jre home, so i think i'm compiling with a newer version of java than i'm running with.
Reminder: i want to build with a specified java home property = i want to change the compiler java home(or version) to the specified one. (In eclipse)
I would appreciate any help.
I dont think it is configurable. It is part of the Maven Core to use the JAVA_HOME environment variable. Please see the accepted answer of:
How to set specific java version to Maven
Also it is not possible to set or change environment variables (not system properties) within a Java process (for the current process). If you create another process from within your Java process, there will be methods to specify environment variables for this sub process.
Maybe the solution will be to execute a Maven command e.g. "mvn clean install" with a specific JAVA_HOME variable set as sub process (this requires, that Maven is installed and mvn is available as command). Use the ProcessBuilder to switch into the working directory, where the pom.xml of the target project is located and set the appropriate environment variable(s) before starting the process.
If Maven should not be installed at the enviroment your application is running on, you could also distribute a Maven installation with your application (maybe in a separate directory). Then you could run against the mvn.bat or mvn.sh of this distribution (depending on the os).
When using Eclipse, Build in Run as Configuration, go to the Environment tab and add the new JAVA_HOME variable.
Do not forget to check the Replace native environment ..... option.
This will override your default OS variable. No need to change at the OS level.

How to create a generic launch configuration with Eclipse?

I have a run configuration in my eclipse. In my project we have two branches : DEV and STABLE.
I would like to create one run configuration for building my project whatever branch it is on.
For now, when I set Base directory with one of those two variables : ${project_path}, ${build_project}, I face this error :
Base directory doesn't exist or can't be read.
This works : ${workspace_loc:/my-project-dev-branch} but is tied to a particular branch. I must duplicate this configuration for building the stable branch.
So, how can I view the actual content of ${project_path}, ${build_project} ?
Or which variable should I use to get this result : ${workspace_loc:/${eclipse_variable_with_project_name}} ?
I'm not sure I follow how your branches are represented within the workspace, but
${project_path} represents a path relative to your workspace
${build_project} will only be set during an actual build (not during an execution of your program)
Based on your description you want to be using ${project_loc} instead.
Nota: The project MUST be selected in the perspective project before launching the run configuration. Otherwise, you will get a message like in the screenshot below :
As you are already creating a String Substitution variable, through Run Debug->String Substitution in Eclipse Preferences, to deal with separate paths, you could either:
Create a variable, e.g. branch_loc, with a value of ${workspace_loc:/my-project-dev-branch}
If the paths only differ slightly, e.g. by branch name, then you could create a variable branch with a value, e.g. dev, and then create branch_loc with ${workspace_loc}\${branch}
Then use ${branch_loc} for you Maven base directory.
It would be better to have all branches use the same path, which git and mercurial allow you to do. Then you could use ${project_loc} for your Maven base directory. For project_loc if you specify the project name of your project, e.g. ${project_loc:MY_PROJECT_NAME}, then it doesn't require you to select the project in order to work.
If you right click on the project and then select Properties, you can see what ${project_path} will resolve to by looking at path and what ${project_loc} will resolve to by looking at location.
First of all, if you are using git as version control system: Do not checkout the project twice, but just switch between branches in a single project. Git was designed for that and can do that in seconds. That way your problem would vanish completely.
If that is not an option, maybe putting the run configuration under version control itself would be an alternative. Set the Shared file option as shown with the first highlight:
Then you can run the run configuration by selecting it in the respective project (as that is really a file there) and launch it via context menu. However, I've never tried this with the same launch configuration checked out twice.
You can set the base directory in below mentioned way:
${project_loc:${project_name}}
You can find the above variables from the variables option.
Also you can set your mvn command in goals as example below:
clean install -PautoInstallPackage -Padobe-public -DskipTests

Categories