How to create a function def test() which does some steps after sshing into an instance
I have something like this:
#!/usr/bin/env groovy
def test() {
cd $testPath
mv test*.txt archiveFiles
sh "someScript.sh"
}
pipeline {
agent java
parameters {
string(
name: 'testPath',
defaultValue: '/home/ubuntu/testFiles',
description: 'file directory'
)
}
stages {
stage(test) {
steps{
script{
sh "ssh ubuntu#IP 'test()'"
}
}
}
}
}
I am trying to ssh into an instance and do the steps in the function test() by calling it
I am getting an error like this:
bash: -c: line 1: syntax error: unexpected end of file
ERROR: script returned exit code 1
We use the SSH plugin as follows:
steps {
timeout(time: 2, unit: 'MINUTES') {
sshagent(credentials: ['local-dev-ssh']) {
sh "ssh -p 8022 -l app ${ENVIRONMENT_HOST_NAME} './run-apps.sh ${SERVICE_NAME} ${DOCKER_IMAGE_TAG_PREFIX}-${env.BUILD_NUMBER}'"
}
}
}
Related
I have a spring boot application on centos server and use a shell file to restart it.
jenkins version: docker run -dp 8080:8080 --name jenkins jenkinsci/blueocean
start-service.sh
#!/bin/bash
sudo systemctl restart sb
In my Jenkinsfile i upload jar file to server and execute the start-service.sh, but jenkins seem dosen't know my java application restart success or fail.
Jenkinsfile
pipeline {
agent none
stages {
stage('Build') {
agent {
docker {
image 'maven:3-alpine'
args '-v /root/.m2:/root/.m2'
}
}
steps {
sh 'mvn -B -DskipTests clean package'
sh 'mvn help:evaluate -Dexpression=project.name | grep "^[^\\[]" > project-name'
sh 'mvn help:evaluate -Dexpression=project.version | grep "^[^\\[]" > project-ver'
}
}
stage('Deploy') {
agent any
environment {
HOST = "${HEHU_HOST}"
USER = "yunwei"
DIR = "/www/java/sb-demo"
VERSION_FILE = "${DIR}/version"
CMD_SERVICE = "${DIR}/start-service.sh"
}
steps {
sshagent (credentials: ['hehu']) {
sh '''
name=$(cat project-name)
ver=$(cat project-ver)
jarFile=${name}-${ver}.jar
scp target/${jarFile} ${USER}#${HOST}:${DIR}/${jarFile}
scp project-ver ${USER}#${HOST}:${VERSION_FILE}
ssh -o StrictHostKeyChecking=no -l ${USER} ${HOST} -a ${CMD_SERVICE}
'''
}
}
}
}
}
I deliberately let Java application go wrong, and systemctl restart is fail but jenkins stage is success.
#SpringBootApplication
#RestController
public class Application {
public static void main(String[] args) {
throw new RuntimeException("Test error");
// SpringApplication.run(Application.class, args);
}
#GetMapping("/test")
String test() {
return "furukawa nagisa\n";
}
}
Try Daniel Taub solution get syntax error.
pipeline {
agent none
stages {
stage('Hello') {
agent any
steps {
sshagent (credentials: ['hehu']) {
SH_SUCCESS = sh(
script: '''
ssh -o StrictHostKeyChecking=no -l yunwei ${HEHU_HOST} -a /www/java/sb-demo/start-service.sh
''',
returnStatus: true
) == 0
echo '${SH_SUCCESS}'
}
}
}
}
}
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 9: Expected a step # line 9, column 21.
SH_SUCCESS = sh(
You can get the sh returned exit status code and fail the build manually if its error status.
For checking your exit code, Jenkins support it that way
returnStatus (optional)
Normally, a script which exits with a nonzero status code will cause the step to fail with an exception. If this option is checked, the return value of the step will instead be the status code. You may then compare it to zero, for example.
script {
SH_SUCCESS = sh (
script: "your command",
returnStatus: true
) == 0
}
To manually fail the build you have couple of options:
error('Fail my build!')
Or alternatively
currentBuild.result = 'FAILURE'
return
I am working on a groovy script for a Jenkins pipeline and am struggling to find how to pass a variable across stages when the variable is obtained from a remote ssh connection.
I found Example 1 and Example 2 on this site and I want to merge them together as seen in "My attempt" below. Note that the output of the file on the remote server is 4. I'm trying pass 4 to a_var.
Example 1: works fine. SSH connection. This reads the file and outputs value to the Jenkins console
def sshCredId = 'myid_cred'
def sshUser = 'myid'
def sshServer = 'myserver'
pipeline {
agent { label 'docker-maven-slave' }
stages {
stage('one') {
steps {
script {
sshagent([sshCredId]){
sh "ssh -o StrictHostKeyChecking=no ${sshUser}#${sshServer} cat /mydir/myfile.csv"
}
}
}
}
stage('two') {
steps {
echo "something"
}
}
stage('three') {
steps {
echo "do stuff"
}
}
}
}
Example 2: works fine. This passes a parameter across stages
pipeline {
agent {
label 'docker-maven-slave'
}
parameters {
string(name: 'a_var', defaultValue: '')
}
stages {
stage("one") {
steps {
script {
tmp_param = sh (script: 'echo something', returnStdout: true).trim()
env.a_var = tmp_param
}
}
}
stage("two") {
steps {
echo "${env.a_var}"
}
}
}
}
**My attempt: stage two output is null. I'm expecting '4' **
def sshCredId = 'myid_cred'
def sshUser = 'myid'
def sshServer = 'myserver'
pipeline {
agent { label 'docker-maven-slave' }
parameters {
string(name: 'a_var', defaultValue: 'nothing')
}
stages {
stage('one') {
steps {
script {
tmp_param=sshagent([sshCredId]){
sh "ssh -o StrictHostKeyChecking=no ${sshUser}#${sshServer} cat /mydir/myfile.csv"
}
env.a_var=tmp_param
}
}
}
stage('two') {
steps {
echo "${env.a_var}"
}
}
stage('three') {
steps {
echo "do stuff"
}
}
}
}
Update the answer based on comments and feedback from MayJoAnneBeth
Try below snippet
sshagent([sshCredId]){
env.a_var = sh (script: "ssh -o StrictHostKeyChecking=no ${sshUser}#${sshServer} cat /mydir/myfile.csv", returnStdout: true).trim()
}
Does anyone have a pipeline{} example with a loop?
I'm trying to "condense" a long and repetitive JenkinsFile by using loops to run the same logic on multiple hosts.
... but ... I'm not getting loops right in my piepline{} JenkinsFile.
Specifically, I'm doing this ...
pipeline {
agent { label 'buildhost' }
stages {
stage("checks") {
parallel {
// ['mac-amd64', 'linux-arm', 'win-amd64', 'linux-x86', 'linux-armv8', 'linux-amd64' ].each {
['mac-amd64', 'linux-armv8', 'linux-amd64'].each {
host ->
stage("checks / ${host}") {
agent { label "buildhost-${host}" }
steps {
dir ('peterlavalle.sbt/') {
// combining these seemed to launch the SBT server which makes Jenkins hang
sh 'java -Dsbt.log.noformat=true -jar ./sbt-launch.jar clean'
sh 'java -Dsbt.log.noformat=true -jar ./sbt-launch.jar test'
sh 'java -Dsbt.log.noformat=true -jar ./sbt-launch.jar publish'
}
['cgc3.gradle/', 'kanobi.sbt/'].each {
gradle ->
dir (path) {
sh 'chmod +=rwx ./gradlew'
sh './gradlew --stacktrace --console=plain clean'
sh './gradlew --stacktrace --console=plain check'
sh './gradlew --stacktrace --console=plain publish'
}
}
dir ("coffeeskript.cgc/") {
sh 'chmod +=rwx ./gradlew'
sh './gradlew --stacktrace --console=plain check'
}
}
}
}
}
}
}
}
}
... and Jenkins says "only stages here!" or somesuch.
...
...
...
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 47: Expected a stage # line 47, column 11.
['mac-amd64', 'linux-armv8', 'linux-amd64'].each {
^
WorkflowScript: 44: Expected one of "steps", "stages", or "parallel" for stage "checks" # line 44, column 4.
stage("checks") {
^
...
...
...
I'm trying to configure a parameter in Jenkins pipeline and then execute it within bat command:
pipeline {
agent {
label 'master'
}
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe'
)
}
stages {
stage("hi") {
steps {
script {
bat '${params.varExe}'
}
}
}
}
}
Unfortunately, i'm getting this error:
'${varExe}'is not recognized as an internal or external command
For some reason, Jenkins doesn't use varExe value.
I've also tried bat '${varExe}' but still no luck.
Any ideas ?
You need to use a double quote here to replace the variable.
bat "${params.varExe}"
You have to be careful with single and double quotes. For the following example, the first one would echo someExe.exe, while the second one would throw a Bad substitution error.
pipeline {
agent any
parameters {
string (
defaultValue: '"someExe.exe"',
description: '',
name : 'varExe')
}
stages {
stage ('Test') {
steps {
script {
sh "echo '${params.varExe}'"
sh 'echo "${params.varExe}"'
}
}
}
}
}
I think for bat command should be like below
bat ''' echo %varExe% '''
reference : pass parameter from jenkins parameterized build to windows batch command
I am trying to start a docker image from Jenkins.
(Not getting Docker to run from within Jenkins)
I think I'm really close but this part has still some issues.
Can please anyone help?
stage('build Dockerimage 1') {
steps{
apitestimage = docker.build('apitestimage', '--no-cache=true dockerbuild')
}
}
stage('start Dockerimage and Tests 2') {
steps{
apitestimage.inside {
sh 'cd testing && ctest'
}
}
}
Jenkins reports:
WorkflowScript: 21: Expected a step # line 21, column 15. apitestimage = docker.build('apitestimage', '--no-cache=true dockerbuild')
and also
WorkflowScript: 27: Method calls on objects not allowed outside "script" blocks. # line 27, column 13. apitestimage.inside {
From your error, it shows that you're missing a script block in your steps. You'll need a script block when using the DSL in steps.
stage('build Dockerimage 1') {
steps{
script {
def apitestimage = docker.build('apitestimage', '--no-cache=true dockerbuild')
}
}
}
stage('start Dockerimage and Tests 2') {
steps{
script {
apitestimage.inside {
sh 'cd testing && ctest'
}
}
}
}
References:
https://jenkins.io/doc/book/pipeline/syntax/#script
In my case, I did declare a variable using the stages name: def stages = [buildStage]
Changing this variable name to another name fixed my issue.