jenkins pipeline - both of groovy and powershell variables in powershell command - powershell

I trying to define powershell variable inside jenkins pipeline with the WORKSPACE variable in value. Is there a way to do this?
stage ('BUILD') {
steps {
powershell ("""Write-Output ${WORKSPACE}\\One\\Two\\""")
}
}
Output:
[Pipeline] powershell
18:18:15 C:\buildenv\Jenkins\workspace\project\One\Two\
[Pipeline] }
[Pipeline] // stage
That's nice. Now i need to wrap it into variable:
stage ('BUILD') {
steps {
powershell ("""$name02=${WORKSPACE}\\One\\Two\\""")
}
}
Output now:
groovy.lang.MissingPropertyException: No such property: name02 for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:288)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:292)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:268)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:268)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:50)
at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.delegateAndExecute(jar:file:/C:/buildenv/Jenkins/plugins/pipeline-model-definition/WEB-INF/lib/pipeline-model-definition.jar!/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy:134)
at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.executeSingleStage(jar:file:/C:/buildenv/Jenkins/plugins/pipeline-model-definition/WEB-INF/lib/pipeline-model-definition.jar!/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy:679)
at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.catchRequiredContextForNode(jar:file:/C:/buildenv/Jenkins/plugins/pipeline-model-definition/WEB-INF/lib/pipeline-model-definition.jar!/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy:414)
at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.catchRequiredContextForNode(jar:file:/C:/buildenv/Jenkins/plugins/pipeline-model-definition/WEB-INF/lib/pipeline-model-definition.jar!/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy:412)
at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.executeSingleStage(jar:file:/C:/buildenv/Jenkins/plugins/pipeline-model-definition/WEB-INF/lib/pipeline-model-definition.jar!/org/jenkinsci/plugins/pipeline/modeldefinition/ModelInterpreter.groovy:678)

name02=''
pipeline {
agent any
stages{
stage ('BUILD') {
steps {
script{
name2 = powershell label: '', returnStdout: true, script: "return \"${Workspace}\\One\\Two\\\""
}
}
}
stage ('Print') {
steps {
echo "name2 = ${name2}"
}
}
}
}

pipeline {
agent any
stages{
stage ('BUILD') {
steps {
script{
powershell """
\$5name2 = "${Workspace}\\One\\Two\\"
Write-Output "name2 = \$5name2"
"""
}
}
}
}
}

def result = powershell returnStdout: true, script: '''
$result = ${WORKSPACE}\\One\\Two\\
return $result
'''

Related

Run two Jenkins alongside agents

we have a multibranch pipeline that triggers sup-build
the syntax for this like
pipeline {
stages{
stage('main') {
agent { label "k8s" }
sh 'echo hello.'
}
}
}
I need to add another alongside agent that runs the selenium grid - this agent needs to be active the whole time that the pipeline is active and needs to be deleted after
pipeline {
stages{
stage('main') {
agent { label "k8s" }
sh 'echo hello.'
}
stage('SG') {
agent { label "k8s" }
sh 'run selenuim-grid'
}
}
}
Try with below code
Pipeline {
Agent none
Stages {
stage(‘main’)
{
Agent { labe; “k8s”}
Steps {
Sh ‘echo hello.’
}
}
Stage (‘SG’)
{
Agent {
Kubernetes
{
Label ‘selenium-grid’
Cloud ‘kubernetes’
containerTemplate {
Name ‘selenium’
Image ‘selenium/standalone-chrome’
ttyEnabled true
Command ‘cat’
}}}
Steps
Sh ‘run selenium-grid’
}}}
‘SG’ stage has been added to run selenium grid. Once this stage is completed, the pod and container will be automatically deleted.
Please check Jenkins official page 1 and Pipeline for further reference.

How to view script output (specifically PowerShell) from a Jenkinsfile?

I'm pretty new to Jenkins, so not totally clear on how to assign/read variables.
I have a jenkinsfile with a couple stages and a bunch of steps. In one of the steps, I want to run a PowerShell script but it isn't accomplishing the intent. The problem is, when I'm in Jenkins and I go to the Console Output to troubleshoot why the PowerShell script isn't working, I don't see any of the output from the powershell script, I just see this:
[Pipeline] {
[Pipeline] powershell (Test PowerShell Script)
[Pipeline] }
Here's a trimmed-down version of my code:
stages {
stage('Stage 1') {
agent { node {
label "Windows"
customWorkspace "D:\\Path"
}}
steps {
dir('Directory') {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
}
}
}
}
}
I tried using the code provided in this Jenkins article:
steps {
dir('Directory') {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
def msg = powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
println msg
}
}
}
This threw an error:
WorkflowScript: 135: Expected a step # line 135, column 25.
def msg = powershell(
^
I also tried putting it inside a node:
steps {
dir('Directory') {
node {
withCredentials(
[usernameColonPassword(
credentialsId: 'credential1',
variable: 'BasicCred'
)]
) {
def msg = powershell(
label: 'Test PowerShell Script',
returnStdout: true,
script: 'echo Test'
)
println msg
}
}
}
}
But it threw an error that the node is missing a label, and when I tried adding a label it threw another error.
So what's the right way to go about this? I just want to capture the output from the PowerShell script and see it so I can troubleshoot why it isn't working.

Jenkinsfile with Docker PowerShell image is getting hanged

When the Docker powershell gets invoked from a jenkinsfile it keeps executing and the job doesn't gets terminated.
pipeline {
agent {
docker {
image 'mcr.microsoft.com/azure-powershell'
args "--mount type=bind,src=/opt,dst=/opt -i -t --entrypoint=''"
}
}
stages {
stage('PwShell') {
steps {
powershell(returnStdout: true, script: 'Write-Output "PowerShell is mighty!"')
}
}
}
}
jenkin-job-hang
As you have not provided any log details it's tough to pin point the error as why it is stuck. Generally, for Jenkins declarative pipeline like the following -
pipeline {
agent {
docker { image '...abc.com' }
}
stages {
stage('Test') {
steps {
sh 'node --version'
}
}
}
}
When the Pipeline executes, Jenkins will automatically start the specified container and execute the defined steps within it:
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
[guided-tour] Running shell script
+ node --version
v14.15.0
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
And since you are stuck in the PowerShell line in the steps, it means the steps is not correctly set.
If you check this Microsoft PowerShell Support for Pipeline document then you will find that by default returnStdout returns the standard output stream with a default encoding of UTF-8. And Write-Output cmdlet returns an output stream.
You should be able to solve your problem by following the changing your PowerShell line as the code snippet shown below.
steps {
def msg = powershell(returnStdout: true, script: 'Write-Output "PowerShell is mighty!"')
println msg
}
Check this example section of the same above mentioned document for more detailed operations on the PowerShell steps.
I would also suggest to read this Using Docker with Pipeline document for more information.

how to pass variable from powershell script to an other step?

I use Jenkins and pipeline Jenkinsfile with a Windows agent. I want set a veriable from powershell in a 1st step and use this value in a 2nd step after.
my pipeline is:
def MSVERSION
pipeline {
stages {
stage('Clean workspace') {
steps {
deleteDir()
}
}
stage('package') {
steps {
script {
def stdout = powershell(returnStdout: true, script: '''
$MSVERSION="1234"
write-host "MSVERSION is $MSVERSION"
''')
println stdout
}
}
}
stage('deploy') {
steps {
script {
bat 'echo MSVERSION is ${MSVERSION}'
}
bat 'echo MSVERSION is ${MSVERSION}'
}
}
}
}
but my result is:
MSVERSION is 1234
MSVERSION is ${MSVERSION}
MSVERSION is ${MSVERSION}
EDIT
I find a workaroud but is not my question today:
in powershell I write a var.propertie file:
set-Content -path "var.properties" -Value "MSVERSION=$($VERSION)"
and in my script I read this var.properties file:
properties = readProperties file: 'var.properties'
echo "MSVERSION is ${properties.MSVERSION}"
bat 'echo MSVERSION is ${MSVERSION}'
does not do string interpolation, but this does:
bat "echo MSVERSION is ${MSVERSION}"

Pass bool param to a powershell script in Jenkinsfile multiline parameterised pipeline

In my Jenkinsfile I have something like:
def addDollar(param) {
return "\$" + param
}
parameters {
booleanParam(
defaultValue: false,
name: 'FORCE_UPGRADE'
)
}
environment {
FORCE_UPGRADE = addDollar(params.FORCE_UPGRADE)
}
stages {
stage('Test') {
steps {
powershell script: ".\\test.ps1 -forceUpgrade ${env:FORCE_UPGRADE}"
}
}
stage('Test Multiline') {
steps {
powershell script: '''
.\\test.ps1 `
-forceUpgrade $env:FORCE_UPGRADE
'''
}
}
}
and the powershell script is
param (
[Parameter(Mandatory=$true)][boolean]$forceUpgrade=$false
)
if($forceUpgrade) {
Write-Host "Forcing upgrade"
}
This jenkins stage Test works as expected but Test Multiline erorrs with ParameterBindingArgumentTransformationException:
Cannot process argument transformation on parameter 'forceUpgrade'. Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and
numbers, such as $True, $False, 1 or 0.
I get the same error if I run
.\test.ps1 -forceUpgrade false rather than
.\test.ps1 -forceUpgrade $false
Any ideas how to get the Jenkins Test Multiline stage working? I have a script where i need to pass a number of args, would be ideal to prevent horizontal scrolling using multiline powershell
Change the powershell input to a [string] instead of a [boolean]
[string]$forceUpgrade = $false
you will still be able to use the $forceUpgrade variable as a bool in the conditional in the powershell also.