Running shell scripts in a Jenkins DSL mavenJob - jenkins

I'm writing a Jenkins (version 2.6) DSL that will allow me to check out and build a Maven project, run a shell script and deploy it to Artifactory.
mavenJob("test-build") {
multiscm {
...
}
steps {
shell ("bash build-scripts/script.sh")
}
goals("clean install")
configure{ project ->
project/publishers << 'org.jfrog.hudson.ArtifactoryRedeployPublisher' {
details {
artifactoryUrl('<url>')
artifactoryName('<name>')
repositoryKey('libs-release-local')
snapshotsRepositoryKey('libs-snapshot-local')
}
deployBuildInfo(true)
deployArtifacts(true)
evenIfUnstable(false)
}
publishers {
archiveJunit('target/*/.xml')
publishBuilder {
discardOldBuilds(7,10)
}
}
}
The job only works if I remove the steps{} block as steps aren't permitted in a mavenJob. I've tried using a freeStyleJob, but ArtifactoryRedeployPublisher doesn't work.
What do I have to do to run my shell script?

If you want shell script to be run ahead of maven goal, you can use this
preBuildSteps {
// Runs a shell script.
shell(String command)
}
Or if you want the shell script run after the maven goal, you can use this one
mavenJob('example-1') {
postBuildSteps {
shell("echo 'run after Maven'")
}
}
For detail, you can check the job dsl api viewer
https://jenkinsci.github.io/job-dsl-plugin/#method/javaposse.jobdsl.dsl.jobs.MavenJob.postBuildSteps
It is very easy and handy tool.
Br,
Tim

Related

Run unit tests and make unit test report available within jenkins

Newbie to jenkins.
Experimenting to run unit tests (not even sure if the step to run is correct)
and also need to make a report available within jenkins (any suggestions how i can make this possible?)
pipeline {
agent any
stages
{
stage("Build") {
steps {
echo 'Building the appication...'
}
}
stage ('Unit test') {
steps {
sh 'npm run test'
}
}
stage ("Deploy") {
steps {
echo 'Deploying the appication...'
}
}
}
}
Use for example xunit tool (can be invoked on post actions or simply as step) to record a report from tests.
Here is the documentation:
https://plugins.jenkins.io/xunit/
To create a report with npm run test command you have to define it in package.json of the project or wherever the command is defined
Rwmeber also to add script { after steps { in the stage where you call Bash script

'.' is not recognized as an internal or external command for Gradle command in Jenkins when gradlew script is executed

I try to run SonarQube analysis for a Gradle project in a Jenkins Pipeline using the following code:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat "./gradlew sonarqube"
}
}
}
The Gradle plugin is installed in Jenkins but I am getting the following error:
05:15:05 D:\*\*\*\*\*\*>./gradlew sonarqube
05:15:05 '.' is not recognized as an internal or external command,
Two things are incorrect in your code. On Windows machines you have to:
use backslashes instead of slashes in paths (./command → .\command)
execute script written for Windows (gradlew is a Unix script, gradlew.bat is a Windows script)
This code should work:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat '.\\gradlew.bat sonarqube'
}
}
}
Gradle Wtapper by default is provided with two script gardlew and gradlew.bat. If your project doesn't have the gradlew.bat file, execute on your Unix machine ./gradlew wrapper. The missing file will be generated.
Btw. You don't need the Jenkins Gradle plugin, when you use Gradlew Wrapper. The plugin is required when you want to provide Gradle installations for jobs, example:
stage('SonarQube') {
withGradle {
withSonarQubeEnv('SonarQube Env') {
bat "${tool(name: 'toolId', type: 'gradle')}\\bin\\gradle.bat sonarqube"
}
}
}
toolId must much the identifiers used in the Jenkins Global Tool Configuration, examples: gradle-6.X, gradle-6.8.3 etc.

Jenkins pipeline, how can I copy artifact from previous build to current build?

In Jenkins Pipeline, how can I copy the artifacts from a previous build to the current build?
I want to do this even if the previous build failed.
Stuart Rowe also recommended to me on the Pipeline Authoring Sig Gitter channel that I look at the Copy Artifact Plugin, but also gave me some sample Jenkins Pipeline syntax to use.
Based on the advice that he gave, I came up with this fuller Pipeline example
which copies the artifacts from the previous build into the current build,
whether the previous build succeeded or failed.
pipeline {
agent any;
stages {
stage("Zeroth stage") {
steps {
script {
if (currentBuild.previousBuild) {
try {
copyArtifacts(projectName: currentBuild.projectName,
selector: specific("${currentBuild.previousBuild.number}"))
def previousFile = readFile(file: "usefulfile.txt")
echo("The current build is ${currentBuild.number}")
echo("The previous build artifact was: ${previousFile}")
} catch(err) {
// ignore error
}
}
}
}
}
stage("First stage") {
steps {
echo("Hello")
writeFile(file: "usefulfile.txt", text: "This file ${env.BUILD_NUMBER} is useful, need to archive it.")
archiveArtifacts(artifacts: 'usefulfile.txt')
}
}
stage("Error") {
steps {
error("Failed")
}
}
}
}
Suppose you want a single file to from previous build, you can even use curl to place file in workspace before mvn invocation.
stage('Copy csv') {
steps {
sh "mkdir -p ${env.WORKSPACE}/dump"
sh "curl http://<jenkins-url>:<port>/job/<job-folder>/job/<job-name>/job/<release>/lastSuccessfulBuild/artifact/dump/sample.csv/*view*/ -o ${env.WORKSPACE}/dump/sample.csv"
}
}
Thanks,
Ashish
You Can Use Copy Artifact Plugin
For configuration visit https://wiki.jenkins.io/display/JENKINS/Copy+Artifact+Plugin

Jenkins configuration to DSL code conversion

I am trying to write the corresponding dsl code for a jenkins job and i am stuck at Build step and don't know how to code Send Files or Execute commands over SSH.
I have tried the XML to DSL converter plugin but it is also excluding this section.
Can someone help in this?
Build Step
You can use the Jenkins job DSL method: publishOverSsh to archive your goal.
job('test') {
def cmd = 'mkdir -p $MICROSERVICE_NAME\n' +
'mv docker-compse.deploy.yml ${MICROSERVICE_NAME}\n' +
'cd ${MICROSERVICE_NAME}\n'
steps {
publishOverSsh {
server('MiSe_New_External') {
transferSet {
sourceFiles('docker-compse.deploy.yml')
execCommand(cmd)
}
}
}
}
}

Jenkins Pipeline: Executing a shell script

I have create a pipeline like below and please note that I have the script files namely- "backup_grafana.sh" and "gitPush.sh" in source code repository where the Jenkinsfile is present. But I am unable to execute the script because of the following error:-
/home/jenkins/workspace/grafana-backup#tmp/durable-52495dad/script.sh:
line 1: backup_grafana.sh: not found
Please note that I am running jenkins master on kubernetes in a pod. So copying scripts files as suggested by the error is not possible because the pod may be destroyed and recreated dynamically(in this case with a new pod, my scripts will no longer be available in the jenkins master)
pipeline {
agent {
node {
label 'jenkins-slave-python2.7'
}
}
stages {
stage('Take the grafana backup') {
steps {
sh 'backup_grafana.sh'
}
}
stage('Push to the grafana-backup submodule repository') {
steps {
sh 'gitPush.sh'
}
}
}
}
Can you please suggest how can I run these scripts in Jenkinsfile? I would like to also mention that I want to run these scripts on a python slave that I have already created finely.
If the command 'sh backup_grafana.sh' fails to execute when it actually should have successfully executed, here are two possible solutions.
1) Maybe you need a dot slash in front of those executable commands to tell your shell where they are. if they are not in your $PATH, you need to tell your shell that they can be found in the current directory. here's the fixed Jenkinsfile with four non-whitespace characters added:
pipeline {
agent {
node {
label 'jenkins-slave-python2.7'
}
}
stages {
stage('Take the grafana backup') {
steps {
sh './backup_grafana.sh'
}
}
stage('Push to the grafana-backup submodule repository') {
steps {
sh './gitPush.sh'
}
}
}
}
2) Check whether you have declared your file as a bash or sh script by declaring one of the following as the first line in your script:
#!/bin/bash
or
#!/bin/sh

Resources