Under http://[JENKINS_NAME]/job/[JOB_NAME]/[BUILD_NUMBER]/
I can see Started by user [USER_NAME].
I want to get that username from my java application.
Any help is much appreciated.
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.
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
Related
I'm trying to parse the following swagger file with openapi4j:
{
"openapi" : "3.0.0",
"info" : {
"title" : "My Service",
"version" : "1.0.0"
},
"paths" : {
"/endpoint" : { "$ref" : "swagger2.json#/paths/get_endpoint" },
}
}
You can see it has a simple ref to another file within the same folder.
I parse the Swagger file with the following:
URL url = Thread.currentThread().getContextClassLoader().getResource(filePath);
openAPI = new OpenApi3Parser().parse(url, false);
Locally in my IDE, this works great. The ref is loaded and I am able to validate requests against it with no issues. However, when I jar up the project, it is able to load the initial swagger file fine, but none of the refs. I get the following error:
StackTrace: org.openapi4j.core.exception.ResolutionException: Failed to load document from 'swagger2.json'
at org.openapi4j.core.model.reference.AbstractReferenceResolver.registerDocument(AbstractReferenceResolver.java:118)
at org.openapi4j.core.model.reference.AbstractReferenceResolver.findReferences(AbstractReferenceResolver.java:92)
at org.openapi4j.core.model.reference.AbstractReferenceResolver.resolve(AbstractReferenceResolver.java:53)
at org.openapi4j.core.model.v3.OAI3Context.resolveReferences(OAI3Context.java:103)
at org.openapi4j.core.model.v3.OAI3Context.<init>(OAI3Context.java:73)
at org.openapi4j.core.model.v3.OAI3Context.<init>(OAI3Context.java:47)
at org.openapi4j.parser.OpenApi3Parser.parse(OpenApi3Parser.java:34)
at org.openapi4j.parser.OpenApi3Parser.parse(OpenApi3Parser.java:18)
at org.openapi4j.parser.OpenApiParser.parse(OpenApiParser.java:53)
I'm not sure if this is possible. I assume I may have to copy my project resources out at runtime to the filesystem somewhere to be accessed more easily. I would like to avoid that route if possible.
Turns out this was a bug in openapi4j, which was resolving refs with URI instead of URL. This has been fixed in 0.9
I've inherited a large-ish Java project using org.springframework.beans.factory.annotation.Autowired, among other things.
I have one module that starts like this:
#Autowired
public Application(
FlattenByFeedRunInvoker flattenRunInvoker,
#Value("${jobId:}") String jobId,
#Value("${instanceId:}") String instanceId,
#Value("${feed}") String feed,
When I run it under debug, using this config:
{
"type": "java",
"name": "Debug (Launch)-Application<tbsm-reporting-etl-flatten>",
"request": "launch",
"mainClass": "com.tbsm.reporting.etl.flatten.Application",
"projectName": "tbsm-reporting-etl-flatten"
}
I get the message:
[ERROR] 2019-07-23 10:10:58.137 [THREAD ID=main]
[CLASS=(SpringApplication:771)] - Application startup failed
java.lang.IllegalArgumentException: Could not resolve placeholder
'feed' in value "${feed}"
I'm guessing that the framework is trying to find a value labelled "feed" somewhere. FWIW I do have a file called "default.properties" in the "resources" directory for the project and that file has the line
feed=myfeed
It looks like that file or value is not being found. I'm wondering if it is just in the wrong directory wrt the program i'm running:
..\src\main\java\com\tbsm\reporting\etl\flatten\Application.java
vs
..src\main\resources\default.properties
Or if I need to do something else to tell it where to look. e.g. does the vscode launch config need something else?
Can I export, in any conventional file format, a history of builds, with their time/date and success. And hopefully even promotion status.
You can make use of Jenkins rest api :
Start at : Traverse all jobs on your Jenkins Server using :
http://JENKINS_URl/api/json?tree=jobs[name,url]
This will give json response with all jobs with job name and job url.
Then for each job access its builds using api :
http://JENKINS_URL/job/JOB_NAME/api/json?tree=allBuilds[number,url]
This will give all the builds for job JOB_NAME and return json response with build number and build url.
Now Traverse each build using api :
http://JENKINS_URL/job/JOB_NAME/BUILD_NUMBER/api/json
This will give everything related to the build as json response. Like Build status, how build was triggered, time etc.
For automation, you can use bash, curl and jq to achieve this.
Have written small bash script to retrieve build status and timestamp for each job on Jenkins server :
#!/bin/bash
JENKINS_URL=<YOUR JENKINS URL HERE>
for job in `curl -sg "$JENKINS_URL/api/json?tree=jobs[name,url]" | jq '.jobs[].name' -r`;
do
echo "Job Name : $job"
echo -e "Build Number\tBuild Status\tTimestamp"
for build in `curl -sg "$JENKINS_URL/job/$job/api/json?tree=allBuilds[number]" | jq '.allBuilds[].number' -r`;
do
curl -sg "$JENKINS_URL/job/$job/$build/api/json" | jq '(.number|tostring) + "\t\t" + .result + "\t\t" + (.timestamp|tostring)' -r
done
echo "================"
done
Note : Above script assumes that Jenkins server does not have any authentication. For authentication, add below parameter to each curl call :
-u username:API_TOKEN
Where :
username:API_TOKEN with your username and password/API_Token
Similar way you can export all build history in any format you want.
Parvez' suggestion to use the REST API is perfectly fine.
However, the REST API is awkward to use if it does not directly provide the data you're looking for, leading to convoluted and multiple invocations of the REST API. This is slow and it makes you depend on stability of that API.
For anything but the most basic queries, I usually prefer to run a small groovy script that will extract the required data from Jenkins' internal structures. This is way faster, and often it's also more simple to use. Here's a small script that will fetch the data that you're looking for:
import jenkins.model.*
import hudson.plugins.promoted_builds.*
import groovy.json.JsonOutput
def job = Jenkins.instance.getItemByFullName( 'TESTJOB' )
def buildInfos = []
for ( build in job.getBuilds() ) {
def promotionList = []
for ( promotion in build.getAction(PromotedBuildAction.class).getPromotions() ) {
promotionList += promotion.getName()
}
buildInfos += [
result : build.getResult().toString(),
number : build.getNumber(),
time : build.getTime().toString(),
promotions: promotionList
]
}
println( JsonOutput.toJson( buildInfos ) )
The script will produce the result in JSON format, like this (prettified):
[
{
"number": 2,
"promotions": [
"promotionA"
],
"result": "SUCCESS",
"time": "Thu Oct 18 11:50:37 EEST 2018"
},
{
"number": 1,
"promotions": [],
"result": "SUCCESS",
"time": "Thu Oct 18 11:50:34 EEST 2018"
}
]
You can run such a script via the Jenkins "Script Console" GUI, or via the REST API for running groovy scripts (sic). There's also a CLI interface command for doing that.
I've got question about resolving environment variables in shared files of config server.
My current setup is pretty minimal :
src/main/resources/shared/application.yml :
application:
version: 0.0.1-early
test: ${JAVA_HOME}
src/main/resources/application.properties :
spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=classpath:/shared
Using gradle with :
spring-boot-gradle-plugin:2.0.0.RELEASE
spring-cloud-dependencies:Camden.SR7
And then of course compile 'org.springframework.cloud:spring-cloud-config-server' in deps
Problem :
GET http://localhost:8888/apptest/application gives me :
{
"name": "apptest",
"profiles": [
"application"
],
"label": null,
"version": null,
"state": null,
"propertySources": [
{
"name": "classpath:/shared/application.yml",
"source": {
"application.version": "0.0.1-early",
"application.test": "${JAVA_HOME}"
}
}
]
}
So env variable is not resolved. Same thing is with :
http://localhost:8888/apptest/application?resolvePlaceholders=true
http://localhost:8888/lab/apptest-application.properties?resolvePlaceholders=true
http://localhost:8888/lab/apptest-application.properties?resolvePlaceholders=false
http://localhost:8888/apptest-application.properties?resolvePlaceholders=true
I've looked at Spring cloud config server. Environment variables in properties but solution didn't help me + there where few new versions since then. So I'm opening new question.
Actually it's not a bug and everything is fine. I did not understood how Config server works.
http://localhost:8888/apptest/application - returns yet not resolved value of ${JAVA_HOME}
When we get ei. into container "C" that pings Config Service for configuration and do curl http://config:8888/apptest/application we get the same - unresolved ${JAVA_HOME}
But when we look into Spring application ei. in container "C" and try to inject #Value("${application.test}") somewhere, we get proper value or info that env variable was not set.
It means that environment variables are resolved on client side.
Thanks to that I've understood how NOT production ready env_variables approach is.
Well the changes happened here https://github.com/spring-cloud/spring-cloud-config/commit/f8fc4e19375d3b4c0c2562a71bc49ba288197100 that removes the support of replacing the environment variables.
You can always add a new controller and override the behaviour of the EnvironmentPropertySource#prepareEnvironment
I'm trying to package a sencha application for ios. But when I in the terminal do: "sencha package build package.json" I get the following
: [ERR] null
at com.sencha.command.environment.AppEnvironment.(AppEnvironment.java:48)
at com.sencha.command.environment.BuildEnvironment.load(BuildEnvironment.java:193)
at com.sencha.command.Sencha.loadBuildEnvironment(Sencha.java:374)
at com.sencha.command.Sencha.main(Sencha.java:127)
I probably screwed something up with the certficates and provisioning profiles, but, I'm not sure if this is some kind of environment error, ie sencha cmd not finding path of Java. The error seems to suggest this, but the cmd works with other commands. I can, for example, create a new app with "sencha app generate myapp ..myapp".
So, my question is really, is the error caused by some environment problem, and if so, what to do about it, or is his a problem related to some errror in my packager.json. Here's my packager.json file.
All help much appreciated!
{
"applicationName":"app",
"applicationId":"com.appname",
"bundleSeedId":"xxxxxxxx",
"versionString":"1.0",
"iconName":"icon.png",
"icon": {
"36":"resources/icons/Icon_Android36.png",
"48":"resources/icons/Icon_Android48.png",
"57":"resources/icons/Icon.png",
"72":"resources/icons/Icon~ipad.png",
"114":"resources/icons/Icon#2x.png",
"144":"resources/icons/Icon~ipad#2x.png"
},
"inputPath":"/Applications/XAMPP/xamppfiles/htdocs/app/",
"outputPath":"../build/",
"configuration":"Debug",
"platform":"iOS",
"deviceType":"Universal",
"certificatePath":"../cert/mycert.p12",
"certificateAlias":"iPhone Developer:",
"certificatePassword":"",
"provisionProfile":"../cert/name.mobileprovision",
"notificationConfiguration":"",
"orientations": [
"portrait",
"landscapeLeft",
"landscapeRight",
"portraitUpsideDown"
]
}