While loop to monitor task in gradle - gradle

I want to monitor a kubernetes pod created after redeploy task and once it is completed, I want to check the liquibase logs. If it is successful, I want to delete the job. How can I achieve this in gradle? I don't want to undeploy immediately after redeploy. So doLast is not an option. The following code doesn't keeps printing ob has not completed yet
task undeployAfterCompleted() {
group "kubernetes"
description "Undeploy the liquibase update job after completion"
def output = new ByteArrayOutputStream()
commandLine "bash", "-c", "kubectl get po -n pbr | grep 'liquibase' | awk '{ print \$3 }'"
while(!output.toString().equals('Completed')) {
sleep(5 * 1000)
println "Job has not completed yet."
commandLine "bash", "-c", "kubectl get po -n pbr | grep 'liquibase' | awk '{ print \$3 }'"
}
tasks.undeploy.execute()
}

I added a doLast block to achieve this:
doLast {
String status = getStatus()
println status.length()
while (status != "Completed") {
println "not"
sleep(5 * 1000)
if (getStatus() == "Completed") {
println "did"
break
}
}
tasks.undeploy.execute()
}

Related

Can not find or read the content from variables returning null from params

I have an issue where the the prompt is allowing user to pick the params value based on what is loaded into the variables. The user can select the value in the variables , but the value of the params is not returning. The echo is blank and also inside the node it is not returning the params value.
+ echo
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NullPointerException: Cannot invoke method $() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:91)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:48)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
Script:
#!/usr/bin/env groovy
stage('Connect Primary') {
node("Primary") {
script {
GET_LISTSTANDBY= sh (script: "sudo cat /pathtofile/samplestandby.txt", returnStdout: true).trim()
println "$GET_LISTSTANDBY"
}
stage('Connect Primary DB Server') {
node("nodename2") {
sh """
sudo su - postgres -c 'repmgr cluster show | grep -i "standby" | sed 's/standby.*//' | sed -r 's/^.{4}//' | cut -d "|" -f 2 | sed 's/^[[:space:]]*//' > samplestandby.txt'
samplestandby=`sudo cat /pathtofile/samplestandby.txt | sed 's/ //g'`
echo "\${samplestandby}"
sudo cp -R /pathtofile/samplestandby.txt ${env.WORKSPACE}/dir-switch
""".stripIndent()
script {
GET_samplestandby= sh (script: "sudo cat /pathtofile/samplestandby.txt", returnStdout: true).trim()
println "$GET_samplestandby"
}
}
}
stage('Prompt to select Standby') {
script {
def nodechosen = input message: 'Choose', ok: 'Next',
parameters: [choice(name: 'standbynode', choices: "${GET_LISTSTANDBY}", description: 'Select the option')]
node(nodechosen) {
echo "Running in Selected node for the choice prompt"
}
}
}
Use ${WORKSPACE} Jenkins environment variable in your getNodeNames() function instead of current directory.

Bash Script is Not Taking 2nd Argument in Jenkins Declarative Pipeline

Here is my script to get telnet status
#!/bin/bash
IP=$1;
PORT=$2;
exec 3> /dev/tcp/$IP/$PORT
if [ $? -eq 0 ];then echo "PortOpen";else echo "PortClosed";fi
I am calling the func in my pipeline stage
def telnetTest (namespace, release, port) {
script {
// Getting Service IP
def serviceIP = sh (
returnStdout: true,
script: "kubectl get svc -n ${namespace} | grep ${release} | awk '{print \$4}'"
)
echo "ServiceIP: ${serviceIP}"
// Checking Service IP is Exsisting ?
if (serviceIP.equals('')) {
echo "ERROR: Getting service IP failed"
sh 'exit 1'
}
// Telnet Testing
sh "chmod +x telnetPort.sh"
def telnetTesting = sh (
returnStdout: true,
script: "./telnetPort.sh ${serviceIP} ${port}"
)
echo "${telnetTesting}"
}
}
Pipeline Stage
Pipeline {
environment {
NAMESPACE = default
RELEASE = test
PORT = 9040
}
stages {
stage ('Telnet Test') {
steps {
script {
telnetTest ("${NAMESPACE}", "${RELEASE}", "${PORT}")
}
}
}
}
}
Now its taking only first arg passing to the script
Any one let me know why & where i am going wrong
In your function, you write port, and in the defining line, you wrote PORT.

How to get gradle property from command line?

I am trying read a project property from command line interface. There is a task gradle properties, which prints all of them. Therefore, I can write: gradle properties | grep "rootProject: root project" | awk '{print $NF}' | tr -d "'" and get what I want. The returned result is correct. I would like to use a proper gradle command to achieve the same result. What is a gradle command to get the project name?
this is my build.gradle:
plugins {
id 'java'
}
tasks.register("rootProjectName") {
doLast {
println(rootProject.name)
}
}
build {
println 'hi'
}
Looks like you're just after the rootProject.name property. There is no built-in Gradle task that will give you that property. You can write a simple task that prints that value to the console which will simplify your command.
tasks.register("rootProjectName") {
doLast {
println(rootProject.name)
}
}
Then simply call that task with -q:
$ ./gradlew rootProjectName -q
demo
You can see demo is simply printed out for this example.
So far the closest I got is the following build.gradle:
plugins {
id 'java'
}
task printRootProjectName {
doLast {
println('root project: ' + rootProject.name)
}
}
build {
println 'unwanted output'
}
and then:
gradle printRootProjectName -q | grep "root project:" | awk '{print $NF}' | head -n 1

Gradle exec task fails with "execCommand == null!"

I have the following task in my build.gradle file:
task myTask(type:Exec) {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'cmd', '/c', 'whoami'
standardOutput = stdout;
}
println "Output: $stdout"
}
When I run my task with ./gradlew myTask, I get the following output:
> Configure project :
Output: retrovius
> Task :myTask FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':myTask'.
> execCommand == null!
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
1 actionable task: 1 executed
The task successfully outputs my username (retrovius), then fails anyway. Any pointers for what I'm doing wrong?
Depending on what you want to achieve, the answer you found is probably still not correct.
All tasks have two main stages: configuration and execution. Everything you put in the outermost block to the task definition is part of the configuration. And the exec method actually executes the command whenever that block of code is evaluated. So when you type:
task myTask() {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'cmd', '/c', 'whoami'
standardOutput = stdout;
}
println "Output: $stdout"
}
Then it means you are running the whoami command no matter what task you specify. If you run gradle -i help, it will print the name. I expect this is not what you intend.
Most of the time, you will want to run a command only when the task is actually executed. So if you want the command to only run if you type gradle -i myTask, you will need to do defer it to the execution stage instead. There are two ways you can do that.
Either you can put everything in a doLast block like this:
task myTask() {
doLast {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'cmd', '/c', 'whoami'
standardOutput = stdout
}
println "Output: $stdout"
}
}
Or you use the Exec type, like you already tried. The reason it didn't work for you is that you need to configure it with the command you like - and not actually run the command through the exec method. It could look like this:
task myTask(type: Exec) {
commandLine 'cmd', '/c', 'whoami'
standardOutput = new ByteArrayOutputStream()
doLast {
println "Output: $standardOutput"
}
}
You an also probably get rid of the cmd /c part. And println should only be used for debugging - use logger.info (or .warn, etc) if you need to output something to the user.
I figured out that the only thing I was doing wrong was to include the (type:Exec) in the definition of my task. If I place the following code in my build.gradle file:
task myTask() {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'cmd', '/c', 'whoami'
standardOutput = stdout;
}
println "Output: $stdout"
}
I get the following output:
> Configure project :
Output: retrovius
BUILD SUCCESSFUL in 2s
My mistake must have been that I was defining the task to be of type exec, but not giving it a command to run. This reveals a fundamental misunderstanding of the exec task and task type on my part. If anyone knows more specifically what I did wrong, please feel free to comment and explain or post a better answer.

Jenkins build output set as current build description

I want to set current build description in my jenkins job from #bash output
Jenkins build output set as current build description
For example to set revision and branch from string and choice parameters I do it like this:
parameters {
string(defaultValue: "", description: '11.00', name: 'REVISION')
choice(name: 'BRANCH', choices: 'trunk\nupdate', description: 'Branch')
}
stage('Set build') {
steps {
script {
// Set build parameters
currentBuild.description = "$REVISION $BRANCH"
}
}
}
Let's say that I want get my diskspace % #bash execution and put it in the description...
stage('bash') {
steps {
script {
sh '''
DISK_SIZE="$(df -h --output='pcent' /mnt | grep -v "Use%")
}
currentBuild.description = "$DISK_SIZE"
}
}
I want in the build description for example to put my disk%. In this case I expect to in the description %30
Or to put some other staff that are generated from current build.
You can tell your sh command to return its stdout using the returnStdout option.
myOutput = sh(script: '$(df -h --output='pcent' /mnt | grep -v "Use%")', returnStdout: true)
currentBuild.description = myOutput

Resources