I have 3 stages to build in jenkins using pipeline code (Scripted0 - jenkins-pipeline

I have 3 stages(a,b,c) to run on jenkins using pipeline code(scripted), I
need to run stage a,b in parallel and run c after a is success (I am
doing this using pipeline code) but in blue ocean it showing only task
name but I wanna see stage names(in this case I have only 2 tasks with 3
stages and stage a and c are in one task). can someone help how can view
all three stages according to this situation.
def stages = [failFast: false]
def testList = ["a", "b", "c"]
def tasks = [:]
tasks["a-and-c"] = {
stage ("a"){
ansiColor('xterm') {
sh " ls -lart; sleep 30 "
}
if (currentBuild.currentResult == 'SUCCESS') {
stage("c") {
ansiColor('xterm') {
sh " ls -lart "
}
}
} else {
sh 'exit'
}
}
}
tasks["c"] = {
stage ("c"){
ansiColor('xterm') {
sh " ls -lart; sleep 20"
}
}
}
parallel tasks
I am expecting to have a separate view in blueocean for all three stages,
right now I am getting a-and-c and b parallel but I looking for a,b as
parallel and c after a is success. Thank you in advance.

Related

Gradle Task - unable to execute fibonacci series in groovy

Facing problem in a question:
Write a gradle program to generate 10 fibonaci series, with task name as fibo, and variable name as num. Use command line argument for num.
For example, if a task name is test and I want to pass 10 as the input, use gradle test -Pnum=10.
I have created a function:
def fibo(n){
a = 0
b = 1
if (n == 1)
println a
else if
(n == 2)
println a + " " + b
else if (n > 2) {
print a + " " + b
i = 2
while (i <= n)
{
c = a + b
print " " + c
a = b
b = c
i = i + 1
}
}
}
My question is, how to link it with a task as I encounter error like:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'fibo' not found in root project 'root'.
* Try:
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 2.61 secs
or how to pass parameters in a gradle task?
Note: Please do not suggest optimization in fibonacci code, thats not a concern for now.
You can define a task like this:
def hello(name) {
println "Hello, $name"
}
task sayHello() {
doLast {
hello sayHelloTo
}
}
And call it like this:
% gradle sayHello -PsayHelloTo=World
> Task :sayHello
Hello, World
BUILD SUCCESSFUL in 518ms
1 actionable task: 1 executed
def fibo(num) {
if (num < 2) {
return 1
} else {
return fibo(num-2) + fib(num-1)
}
}
task (fibo) << {
println fibo(5)
}

What is the best possible way to read the data from a file using readFile and converting it to a List in groovy?

I'm trying to read values from text files and putting the values into the list using the below method.
def myKeys = []
new File( '/tmp/A.txt' ).eachLine { line ->
myKeys << line
}
def myValues = []
new File( '/tmp/B.txt' ).eachLine { line ->
myValues << line
}
Problem is, Jenkins doesn't allow this to run on a slave and I'm not sure how to use readFile method here because it doesn't solve the purpose. I want to create a List, which readFile couldn't do.
You can get the same result using readFile step. It reads a given file from your workspace and returns the content of the file as a string. Then you can use String.eachLine(closure) method to iterate every line and add it to the list you expect. Keep in mind one thing, however - if you want to use String.eachLine() method, you need to do it in the #NonCPS mode. Otherwise, you will get maybe a single element from the iteration at best.
Take a look at the following example:
pipeline {
agent any
stages {
stage("Read test.txt file") {
steps {
script {
final String content = readFile(file: "test.txt")
final List myKeys = extractLines(content)
echo "myKeys = ${myKeys}"
}
}
}
}
}
#NonCPS
List extractLines(final String content) {
List myKeys = []
content.eachLine { line ->
myKeys << line
}
return myKeys
}
In this example, we use simple test.text file with the following content:
$ cat test.txt
123
qwe
asd
zxc
Running this exemplary pipeline produces the following output:
Running on Jenkins in /home/wololock/.jenkins/workspace/jobA
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Read test.txt file)
[Pipeline] script
[Pipeline] {
[Pipeline] readFile
[Pipeline] echo
myKeys = [123, qwe, asd, zxc]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
You could use a similar approach to extract keys and values from two different files, e.g.
def myKeys = extractLines(readFile(file:"/tmp/A.txt"))
def myValues = extractLines(readFile(file:"/tmp/B.txt"))

Variable expansion in Jenkins Pipeline

I am trying to expand a variable in a Jenkinsfile. I first concatenate a couple of strings to create this variable and would like for it to be expanded so that it is interpreted as my environment variable.
I am looking for something like the exclamation mark ! in bash.
pipeline {
agent: any
environment:{
CRED_DEV_PROJ = "my_credentials"
}
stages {
stage("my_stage"){
steps{
script{
LST = [
["DEV", "PROJ"],
... some more lists ...
for (def i= 0; i < LST.size(); i++) {
CRED = "CRED_" + LST[i][0] + "_" + LST[i][1]
sshagent (credentials: [CRED]) {
... do stuff ...
}
}
}
}
}
}
The variable CRED should be expanded so that it leads to my_credentials, so that the line sshagent (credentials: [CRED]) is executed correctly.
That should be env.“${CRED}“.
See also my answer here: https://stackoverflow.com/a/51338110/4279361

Gradle, what is a sequence of execution in one task?

Gradle 2.14
I write my custom task "run"
task run() {
def allVariantList = [];
android.applicationVariants.all { variant ->
allVariantList.add(variant.getName())
println "Current allVariantList = " + allVariantList
}
println "Result allVariantList = " + allVariantList
}
Start my task: gradlew run
Result:
Result allVariantList = []
Current allVariantList = [prod_no_check]
Current allVariantList = [prod_no_check, prod]
Current allVariantList = [prod_no_check, prod, stage]
Current allVariantList = [prod_no_check, prod, stage, dev]
Current allVariantList = [prod_no_check, prod, stage, dev, release]
Current allVariantList = [prod_no_check, prod, stage, dev, release, dev_no_check]
Questions:
Why println "Result allVariantList = " + allVariantList run BEFORE println "Current allVariantList = " + allVariantList
I need to println "Result allVariantList = " + allVariantList execute AFTER
println "Current allVariantList = " + allVariantList. How I can do this?
I think the problem is, that at the time your task is configured (you do all your stuff at configuration time, not execution time, the applicationVariants are not yet configured by the android plugin. applicationVariants.all runs on all variants that are already added and also on all variants that get added in the future as soon as they are added.
So your output would suggest that at configuration time no variants are setup yet, thus your result printing is empty and the others come later when the variants are created.
As you do everythign you do at configuration time, it will also always be done, even if you don't execute your task. If you call gradlew help or anything else, you will get the same output.
So either do all your code in the execution phase (wrapping it in a doLast { } closure), or at least do the result printing in the execution phase. If you need your stuff to be done before the execution phase and independently whether your task is actually run or not, you might wrap at least your result printing in an afterEvaluate { } closure that gets executed after the project is evaluated, but still in the configuration phase.
OK, thank everybody. This is work:
task run() {
description "Install and run app on device/emulator"
def allVariantList = [];
android.applicationVariants.all { variant ->
allVariantList.add(variant.getName())
println "Current allVariantList = " + allVariantList
}
doLast {
println "Result allVariantList = " + allVariantList
}
}
Here is the explanation.
https://docs.gradle.org/current/userguide/build_lifecycle.html
Example 22.1. Single project build

How do I concatenate multiple files in Gradle?

Is there an easy way to concatenate multiple text files into a single one in Gradle? The build script should look something like this:
FileCollection jsDeps = files(
'file1.js',
'file2.js'
// other files here
)
task concatenate << {
// concatenate the files to file.js
}
I am using Gradle 2.3.
leftShift / "<<" is deprecated in gradle 3.4 You may use something like:
task concatenate {
doLast {
def toConcatenate = files("filename1", "filename2", ...)
def outputFileName = "output.txt"
def output = new File(outputFileName)
output.write('') // truncate output if needed
toConcatenate.each { f -> output << f.text }
}
You can also register the files as inputs/outputs to help with incremental builds. It's especially helpful with larger files.
something like this:
task 'concatenateFiles', {
inputs.files( fileTree( "path/to/dir/with/files" ) ).skipWhenEmpty()
outputs.file( "$project.buildDir/tmp/concatinated.js" )
doLast {
outputs.files.singleFile.withOutputStream { out ->
for ( file in inputs.files ) file.withInputStream { out << it << '\n' }
}
}
}
Instead of the fileTree, it can also be replaced with sourceset/sourceset output, specific files, outputs from a different task, etc.
Gradle doc on task inputs/output
Concatenating files in groovy
The following task should do the job:
task concatenate << {
def toConcatenate = files('f1', 'f2', 'f3')
def output = new File('output')
toConcatenate.each { f -> output << f.text }
}
(new File('test.js')).text = file('test1.js').getText() + file('test2.js').getText()
UPDATE:
For collections.
(new File('test.js')).text = files('test1.js', 'test2.js').collect{it.getText()}.join("\n")

Resources