in Jenkins, how to store Console output results to github? - jenkins

How to deploy test report back to github or to my local?
I have the connection from Github to Jenkins using webhook, and the connection from Jenkins to Github using Jenkins setting/Pipeline and add my repository.
The result of the test shows in the Jenkins/Console Output., how to get the result stored somewhere else (such as GithUb) or my local or some server, is there a setup for this?
Thanks.

There are many ways to do this, but here is one way.
pipeline {
agent any
stages {
stage('Sample') {
steps {
script {
echo "Somehitng 1"
echo "Something 2"
// Read the console log
def consoleLog = Jenkins.getInstance().getItemByFullName(env.JOB_NAME).getBuildByNumber(Integer.parseInt(env.BUILD_NUMBER)).logFile.text
//Write the log to a file
writeFile(file: "Log_${BUILD_NUMBER}.txt", text: consoleLog, encoding: "UTF-8")
sh'''
git add *
git commit -m "Add console log"
git push
'''
}
}
}
}
}

Related

Update file content in gitlab using jenkin

Is there a way, after updating the file content via Jenkinsfile, to push it back to Git Lab and replace the previous file?
I fetched all the files to the working dir and changed the content with sed.
pipeline
{
agent any
stages {
stage('Update deployment file') {
steps {
sh 'sed -i "s/source/update/g" file.txt'
}
}
stage('Push to gitlab') {
steps {
?????????
}
}
Thanks in advance.
You can simply use a shell block for this. If you need credentials to push, you may have to append them to the URL or configure them in the git client.
stage(''Push to gitlab''){
steps{
sh '''
git add file.txt
git commit -m "Updates file1.txt"
git push
'''
}
}
In extension to the Answer before.
You can set the ssh Key for git with the following snipped:
sshagent(['<credentialsID>']) {
sh("git push origin HEAD:${BRANCH}")
}

Prevent the jenkins build if previous successful build commit and present commit is same

I want to prevent the Jenkins build if the present commit is same as the previous sucessful build commit. Is there any way to check the present build and previous build in Jenkins. I'm using Jenkins file.
In simple words I don't want jenkins to have a build if there is no commit. Manual Build should not work.
if ("${GIT_COMMIT}"=="${GIT_PREVIOUS_SUCCESSFUL_COMMIT}") {
sh 'exit 1'
}
else {
echo "${GIT_PREVIOUS_COMMIT}"
}
AFAIK, you can't prevent the build from happening, unless you use SCM polling. If polling is not an option you can simply start the build, check whether there are any changes, and then stop the build. For this you can use changeSet.
stage('Build') {
steps {
git url:'https://github.com/xxxx/sample.git', branch: 'main'
script {
if(currentBuild.changeSets.size() > 0) {
echo "There are changes, so continue"
} else {
echo "No changes, stop the build"
currentBuild.result = "NOT_BUILT"
error("Skipping the build.")
}
echo "Building Stuff"
}
}
}

Can't attach the allure report to the Jenkins email

The Allure report is not attaching to the Jenkins email. I am using the Jenkins pipeline script and this is my script however this is the error i get in my email:
Groovy Template file [allure-report.groovy] was not found in $JENKINS_HOME/email-templates.
Also I am not able to find allure-report.groovy in my computer
Here is my Jenkins pipeline, I am not sure how to include the template:
pipeline {
agent {
label {
label ""
customWorkspace "/john/qa-end-to-end"
}
}
tools {nodejs "node"}
stages {
stage('Checkout App') {
steps {
dir("${env.HOME}/app") {
echo "Building.."
sh 'git reset --hard HEAD'
sh 'git clean -f -d'
sh 'git pull'
}
}
}
stage('Starting Tests') {
steps {
echo "Starting End to End Tests"
dir("${env.HOME}/qa-end-to-end/") {
sh './tests.sh'
}
}
}
}
post('Publish Report') {
always {
script {
allure([
includeProperties: false,
jdk: '',
properties: [],
reportBuildPolicy: 'ALWAYS',
results: [[path: '$WORKSPACE/${env.HOME}/app/target/allure-results']]
])
}
}
failure {
emailext(
attachmentsPattern: "$WORKSPACE/${env.HOME}/qa-end-to-end/allure-report/index.html",
body: '''${SCRIPT, template="allure-report.groovy"}''',
subject: "Failure in End to End Tests -> Build Number: ${env.BUILD_NUMBER}",
from: "john#gmail.com",
to: "mike#gmail.com"
)
}
}
}
$JENKINS_HOME/email-templates is used to place email body template, generally when you install Jenkins plugin like email, it which includes some pre-defined templates and those templates will be extracted into $JENKINS_HOME/email-templates after plugin installed.
And when you use send email in job's Post Action, you can choose to use one of template of plugin and Jenkins will try to get the template from folder $JENKINS_HOME/email-templates
If you want to use self template, you need to put it into $JENKINS_HOME/email-templates too.
Using custom scripts (those not packaged with email-ext) requires the cooperation of your Jenkins administrator. The steps are relatively simple:
Create the script/template. The name of the script end in the standard extension for the language (.groovy). The template can be named anything
Have your Jenkins administrator place the script inside $JENKINS_HOME\email-templates.
Use the script token with the template parameter equal to your template filename, or in addition the script parameter equal to the custom script name. For example, if the template filename is foobar.template, the email content would look like this ${SCRIPT, template="foobar.template"}.
More detail

Rename a file - Jenkins

As part of our pipeline I need to rename a file before it gets pushed up to GitHub. Previously this worked when running the Jenkins job on a master node, but now we run them on agents
def rename_build_file() {
print "Append Version Number to File"
// File without version
String myFile = "${WORKSPACE_PATH}/release-pipeline/project/dist/myFile.js
// File with version
String myFileNew = "${WORKSPACE_PATH}/release-pipeline/project/dist/myfile-1.0.js"
// Rename File
new File(myFile).renameTo(new File(myFileNew));
}
Within our JenkinsFile we call helper.rename_build_file() and this usually works
When i sshd onto the agent I found that I had to run sudo to manually change a filename (did not have to enter a password), am i to assume that when the Jenkins job is running it's not running as sudo
And if that's the case how could i do this running the job?
Thanks
When working with files across multiple agents, you should use pipeline's workflow steps like fileExists, readFile, and writeFile. You can use a combination of these steps to create a new file with the desired name in the current workspace.
def sourceFile = "release-pipeline/project/dist/myFile.js"
if (fileExists(file: sourceFile)) {
def newFile = "release-pipeline/project/dist/myFile-1.0.js"
writeFile(file: newFile, encoding: "UTF-8", text: readFile(file: sourceFile, encoding: "UTF-8"))
}
This can be done with the File Operations plugin:
pipeline {
agent any
stages {
stage('Rename') {
steps {
cleanWs()
fileOperations([fileCreateOperation(fileName: 'foo', fileContent: '')])
fileOperations([fileRenameOperation(destination: 'bar', source: 'foo')])
sh "ls -l"
}
}
}
}
The plugin has quite a list of supported file operations.

How to read log file from within pipeline?

I have a pipeline job that runs a maven build. In the "post" section of the pipeline, I want to get the log file so that I can perform some failure analysis on it using some regexes. I have tried the following:
def logContent = Jenkins.getInstance()
.getItemByFullName(JOB_NAME)
.getBuildByNumber(
Integer.parseInt(BUILD_NUMBER))
.logFile.text
Error for the above code
Scripts not permitted to use staticMethod jenkins.model.Jenkins
getInstance
currentBuild.rawBuild.getLogFile()
Error for the above code
Scripts not permitted to use method hudson.model.Run getLogFile
From my research, when I encounter these, I should be able to go to the scriptApproval page and see a prompt to approve these scripts, but when I go to that page, there are no new prompts.
I've also tried loading the script in from a separate file and running it on a different node with no luck.
I'm not sure what else to try at this point, so that's why I'm here. Any help is greatly appreciated.
P.S. I'm aware of the BFA tool, and I've tried manually triggering the analysis early, but in order to do that, I need to be able to access the log file, so I run into the same issue.
You can use pipeline step httpRequest from here
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Test fetch build log'
}
post {
always {
script {
def logUrl = env.BUILD_URL + 'consoleText'
def response = httpRequest(
url: logUrl,
authentication: '<credentialsId of jenkins user>',
ignoreSslErrors: true
)
def log = response.content
echo 'Build log: ' + log
}
}
}
}
}
}
If your jenkins job can run on linux machine, you can use curl to archive same goal.
pipeline {
agent any
stages {
stage('Build') {
environment {
JENKINS_AUTH = credentials('< credentialsId of jenkins user')
}
steps {
sh 'pwd'
}
post {
always {
script {
def logUrl = env.BUILD_URL + 'consoleText'
def cmd = 'curl -u ${JENKINS_AUTH} -k ' + logUrl
def log = sh(returnStdout: true, script: cmd).trim()
echo 'Build log: ' +
echo log
}
}
}
}
}
}
Above two approaches both require the credentials is Username and password format. More detail about what is it and how to add in Jenkins, please look at here
Currently this is not possible via the RunWrapper object that is made available. See https://issues.jenkins.io/browse/JENKINS-46376 for a request to add this.
So the only options are:
explicitly whitelisting the methods
read the log via the URL as described in the other answer, but this requires either anonymous read access or using proper credentials.

Resources