Jenkins: How to use choice parameter from an other file? - jenkins

I have many pipelines using the same choice parameters so I want to import them from an external file. I tried to do the following:
pipeline {
agent any
parameters {
choice(
name: 'myParameter',
choices: readFile "${WORKSPACE}/properties",
description: 'interesting stuff' )
}
}
But i have this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 17: expecting ')', found '' # line 17, column 31.
choices: readFile "${WORKSPACE}/properties",
Any idea or advice on what I can do this?

Related

Jenkins Jira steps - Groovy code in Declarative Pipeline

Seems like Jira steps works only in Scripted pipeline. How can I make use of JIRA steps inside Declarative pipeline? I get the error Unsupported map entry expression for CPS transformation when I try defining Jira steps inside pipeline.
stages {
stage('Create JIRA Ticket'){
steps{
script {
def jiraserver = "Demo"
def testIssue = [fields [
project [id: '10101'],
summary: '[Test] Code Scan - $BUILD_NUMBER ',
description: 'Automated Pipeline',
customfield_1000: 'customValue',
issuetype: [id: '10000']]]
response = jiraNewIssue issue: testIssue
echo response.successful.toString()
echo response.data.toString()
jiraAddComment site: 'Demo', idOrKey: 'Test-1', comment: 'Started Unit Tests'
}
}
}
I get the error WorkflowScript: 42: Unsupported map entry expression for CPS transformation in this context # line 42, column 17 project [id: '10101'],
You have several syntax issues on the testIssue parameter definition which causes the Unsupported map entry expression exception.
The issues is that fields and project are dictionary keys and should be followed with :.
In addition if you wish to interpolate the BUILD_NUMBER in the summary use double quotes ("").
The following should work:
def testIssue = [fields: [
project: [id: '10101'],
summary: "[Test] Code Scan - $BUILD_NUMBER",
description: 'Automated Pipeline',
customfield_1000: 'customValue',
issuetype: [id: '10000']]]

Jenkins Pipeline - How to fix syntax error in matrix section?

I've been trying to configure a matrix section in a declarative pipeline, but it keeps failing.
In the official documentation, it states:
Stages in Declarative Pipeline may have a matrix section defining a multi-dimensional matrix of name-value combinations to be run in parallel.
This is my (simplified) pipeline:
pipeline {
agent { label 'production-linux' } // Set where this project can run
stages {
stage("do something") {
matrix {
axes {
axis {
name 'foo'
values 'bar1', 'bar2', 'bar3'
}
}
stages{
stage("using $foo"){
steps{
step {
echo "using variable: $foo"
}
}
}
}
}
}
}
}
But when I run it, I get the following:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 14: Unknown stage section "matrix". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. # line 14, column 9.
stage("do something") {
^
WorkflowScript: 14: Expected one of "steps", "stages", or "parallel" for stage "do something" # line 14, column 9.
stage("do something") {
^
Has the Matrix section been deprecated?
Has the Matrix section been deprecated?
No it has not. The exception tells that it found a syntax error.
Your syntax error appears here:
steps{
step {
echo "using variable: $foo"
}
}
Quoting the official documentation:
The steps section defines a series of one or more steps to be executed
in a given stage directive.
Unfortunately there is no step-keyword directly, every command you execute in the steps is basically a step. To fix your syntax error try the following:
steps{
echo "using variable: $foo"
}

How to pass groovy variable to powershell in Jenkins pipeline?

I'm trying to pass groovy variable to powershell script inside of jenkins pipeline, all in the same place but i don't know how. i tried different ways without success.
I require this to obtain the name of the person who approved the step of PIPELINE and pass it to powershell, which connects with SQL SERVER
stage('Step1'){
steps{
script{
def approverDEV
approverDEV = input id: 'test', message: 'Hello', ok: 'Proceed?', parameters: [choice(choices: 'apple\npear\norange', description: 'Select a fruit for this build', name: 'FRUIT'), string(defaultValue: '', description: '', name: 'myparam')], submitter: 'user1,user2,group1', submitterParameter: 'APPROVER'
echo "This build was approved by: ${approverDEV['APPROVER']}"
}
}
}
stage('Step2'){
steps{
script{
powershell ('''
# Example echo "${approverDEV['APPROVER']}"
# BUT THIS DOESN'T WORK :(
''')
}
}
}
I expect the output is the name of the approver stored in the variable GROOVY approverDEV
Dagett is correct, use double-quotes around the powershell script, then the variables will be evaluated:
script{
powershell ("""
# Example echo "${approverDEV['APPROVER']}"
# BUT THIS DOESN'T WORK :(
""")
}
Using triple double quotes in Groovy is called 'multi-line GString'. In a GString, variables will be evaluated before creating the actual String.

How do I get ArtifactoryMavenBuild to run with a variable name as an argument for declarative Jenkins?

I am trying to write a Jenkins pipeline using declarative syntax (if I really can't make any progress, I'll switch to script). However, I can't figure out how to get the return value of functions to store to a variable so I can use that variable as an argument of the next function.
The stage of my pipeline looks like this:
stage ('Build') {
steps {
def artServer = getArtifactoryServer(artifactoryServerID: 'my-server')
def mvBuild = newMavenBuild()
def buildInfo = newBuildInfo()
ArtifactoryMavenBuild(mavenBuild: mvBuild, tool: "M3", pom: "pom.xml", goals: "-B clean test -Dmaven.test.failure.ignore", opts: "", buildInfo: buildInfo)
}
}
My error log is:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 19: Expected a step # line 19, column 17.
def artServer = getArtifactoryServer(artifactoryServerID: 'GE-Propel-Artifactory')
^
WorkflowScript: 20: Expected a step # line 20, column 17.
def mvBuild = newMavenBuild()
^
WorkflowScript: 21: Expected a step # line 21, column 17.
def buildInfo = newBuildInfo()
The ArtifactoryMavenBuild function works when I put it like this:
ArtifactoryMavenBuild(mavenBuild: newMavenBuild(), tool: "M3", pom: "pom.xml", goals: "-B clean test -Dmaven.test.failure.ignore", opts: "", buildInfo: newBuildInfo())
But I need to be able to reference mvBuild and buildInfo again for a later step.
The documentation for declarative jenkins for the Artifactory plugin is here: https://jenkins.io/doc/pipeline/steps/artifactory/
Try to wrap you script code into a script {} step like so:
stage ('Build') {
steps {
script {
def artServer = getArtifactoryServer(artifactoryServerID: 'my-server')
def mvBuild = newMavenBuild()
def buildInfo = newBuildInfo()
ArtifactoryMavenBuild(mavenBuild: mvBuild, tool: "M3", pom: "pom.xml", goals: "-B clean test -Dmaven.test.failure.ignore", opts: "", buildInfo: buildInfo)
}
}
}

Capturing results of Jenkins input step

I am playing around with the Jenkins Pipeline and I have some issues at the time of capturing the results of an input step. When I declare the input step as follows ...
stage('approval'){
steps{
input(id: 'Proceed1', message: 'Was this successful?',
parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
}
}
... everything seems to be working fine. However, as soon as I try to get the results from the capture (i.e. the answer given to the question), the script does not work. For example, an script like the following:
pipeline {
agent { label 'master' }
stages {
stage('approval'){
steps{
def result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'echo Se ha obtenido aprobacion! (como usar los datos capturados?)'
}
}
}
}
... results in the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 6: Expected a step # line 6, column 13.
result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1073)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:591)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
...
at hudson.model.Executor.run(Executor.java:404)
Finished: FAILURE
Something quite interesting is that if I moved the input outside the pipeline{}, it works perfectly fine. I noticed that same behaviour occurs with 'def' statement (I can define and use a variable outside pipeline{} but I cannot define it inside).
I think I must be missing something quite basic here but after few hours trying different configurations, I could not manage to make it work. Is it just that the logic to be used within pipeline{} is limited to very few commands? How people then build complex pipelines?
Any help would be highly appreciated.
The script block allows using the Scripted Pipeline syntax aka almost all Groovy functionality within a Declarative pipeline.
See https://jenkins.io/doc/book/pipeline/syntax/ for syntax comparision and restrictions of the declarative pipeline.
pipeline {
agent any
...
stages {
stage("Stage with input") {
steps {
script {
def result = input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'result: ' + result
}
}
}
}
}
I finally managed to make it work but I had to completely change the syntax to avoid pipeline, stages & steps tags as used above. Instead, I implemented something like:
#!/usr/bin/env groovy
node('master'){
// --------------------------------------------
// Approval
// -------------------------------------------
stage 'Approval'
def result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'Se ha obtenido aprobacion! '+result
}

Resources