How to use Jenkins P4 plugin publish for declarative pipeline - jenkins

stage('Publish Assets')
{
when{
expression { //some condition }
}
steps{
p4publish(
credential: 'abcd',
publish: [$class: 'SubmitImpl', delete: false, description: 'Submitted by Jenkins. Build: ${BUILD_TAG}', onlyOnSuccess: true, purge: '', reopen: false],
workspace: [$class: 'ManualWorkspaceImpl', charset: 'none', name: 'jenkins-abcd-publish', pinHost: false, spec: [allwrite: true, backup: false, clobber: false, compress: false, line: 'LOCAL', locked: false, modtime: false, rmdir: false, serverID: '', streamName: '//abcd/efg', type: 'WRITABLE', view: '']])
}
}
I tried a couple of things and placing it under script block as well but no luck. Is it not suppose to work with declarative pipelines or am I missing something? It would be nice if I could get some help on this

Found this guide in the P4 plugin repo that might help. They seem to suggest using the snippet generator to help with getting the syntax correct. The examples they show are written with the imperative syntax, but I don't see why it wouldn't work for declarative.
node {
stage('Sync') {
// sync files from //streams/st1-main/...
p4sync(charset: 'none',
credential: 'phooey1666',
populate: [$class: 'AutoCleanImpl',
delete: true,
modtime: false,
pin: '',
quiet: true,
replace: true],
stream: '//streams/st1-main')
}
}
p4 publish https://github.com/jenkinsci/p4-plugin/blob/master/WORKFLOW.md#using-standard-freestyle-jobs-steps
p4publish(credential: 'phooey1666',
publish: [$class: 'SubmitImpl',
delete: false,
description: 'Submitted by Jenkins. Build: ${BUILD_TAG}',
onlyOnSuccess: false,
purge: '',
reopen: false],
workspace: [$class: 'StreamWorkspaceImpl',
charset: 'none',
format: 'jenkins-${NODE_NAME}-${JOB_NAME}-publish',
pinHost: false,
streamName: '//streams/st2-rel1'])
https://github.com/jenkinsci/p4-plugin/blob/master/WORKFLOW.md

Related

How to create custom workspace in Jenkins pipeline running in same machine

I'm upgrading my jenkins job from freestyle to a pipeline job. I have only one machine and no remote machines are being used.
In the freestyle job, I configured the custom workspace using the "use custom workspace" option. In the pipeline job, I'm not getting any option to use custom workspace. I didn't used any agents or nodes.
I'm using the below pipeline script
pipeline {
agent any
options {
disableConcurrentBuilds()
}
stages {
stage('checkout') {
steps {
// Get some code from a GitHub repository
checkout([$class: 'SubversionSCM', additionalCredentials: [], excludedCommitMessages: '', excludedRegions: '', excludedRevprop: '', excludedUsers: '', filterChangelog: false, ignoreDirPropChanges: false, includedRegions: '', locations: [[cancelProcessOnExternalsFail: true, credentialsId: 'creds', depthOption: 'infinity', ignoreExternalsOption: true, local: '.', remote: "https://******"]], quietOperation: true, workspaceUpdater: [$class: 'UpdateUpdater']])
}
post {
success {
echo "checkout success"
echo "version ${BUILD_NUMBER}"
}
}
}
stage('Build') {
steps {
// Get some code from a GitHub repository
withAnt(installation: 'ant', jdk: 'jdk8') {
bat "ant -DBUILD_NUMBER = ${BUILD_NUMBER} -f AV/build.xml build"
//bat "ant -f AVANCE/build.xml build"
//bat "ant -f AVANCE/build.xml -d dist"
bat 'XCOPY %WORKSPACE%\\AV\\dist\\AV.war %WORKSPACE%\\BUILD_DEPLOYMENT\\ /H /Y'
}
}
post {
success {
echo "build success"
}
}
}
stage('Commit to SVN') {
steps {
bat '''cd %WORKSPACE%\\BUILD_DEPLOYMENT
svn add . --force
svn commit --non-interactive --trust-server-cert -m "committing AV war" --username admin --password admin AVANCE.war'''
}
post {
success {
echo "Committed to SVN"
}
}
}
stage('Copy to jumpbox') {
steps {
// Copy the war file to woodhouse folder
sshPublisher(publishers: [sshPublisherDesc(configName: 'jumpbox', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'Releases/AVPIPELINE/$BUILD_NUMBER/', remoteDirectorySDF: false, removePrefix: 'AV/dist/', sourceFiles: 'AV/dist/AV.war')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
}
post {
success {
echo "Successfully copied to jumpbox"
}
}
}
stage('Deploy in Dev') {
input{
message "Do you want to deploy in DEV ?"
}
steps {
echo "deploying in dev"
sshPublisher(publishers: [sshPublisherDesc(configName: 'jumpbox', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: 'sh /shared/BUILD_DEPLOYMENT_SCRIPTS/PUSH-Development.sh /shared/Releases/AVPIPELINE/$BUILD_NUMBER/', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
}
}
}
}

How to call httpRequest from parameter script

I'm trying to make HTTP request from Active Choices Reactive Parameter
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
filterLength: 1,
filterable: true,
name: 'HTTP_TEST',
referencedParameters: '',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["ERROR"]'
],
script: [
classpath: [],
sandbox: true,
script: """
def url = "https://example.com/api/v1"
def credentialsId = 'mycredential'
try {
// Make HTTP request
def response = httpRequest authentication: credentialsId, url: url
return [response.status]
} catch (Exception e) {
// handle exceptions like timeout, connection errors, etc.
return [e.toString()]
}
""".stripIndent()
]
]
],
but get error
groovy.lang.MissingMethodException: No signature of method: Script1.httpRequest() is applicable for argument types: (java.util.LinkedHashMap) values: [[authentication:mycredential, url:https://example.com/api/v1]]
I also tried HttpURLConnection but it doesn't take Jenkins credentials (or I don't know how).
So, is it possible to call httpRequest from parameter script?

Reference part of the parameter in Jenkins plugin "publish over cifs"

ALL
Below is my jenkinsfile. I defined a parameter "SVN_TAG" for listing SVN tags. The format of SVN tag is "VERSION-Digit.Digit.Digit". Now I can only only reference the whole parameter in the cifsPublisher "RemoteDirectory" settings. But I want only reference the digit part of the parameter(like "2.2.2"), how should I do this? thanks.
// Jenkins Declarative Pipeline
def PRODUCT_VERSION
pipeline {
agent { label 'Windows Server 16 Node' }
options {
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10'))
}
environment {
TAG = '${SVN_TAG.substring(SVN_TAG.indexOf(\'-\')+1)}'
}
stages {
stage('Initialize') {
steps {
script {
PRODUCT_VERSION = "3.2.0.1"
}
}
}
stage('Setup parameters') {
steps {
script {
properties([
parameters([
[ $class: 'ListSubversionTagsParameterDefinition',
credentialsId: 'xxxxxxxxxxx',
defaultValue: 'trunk', maxTags: '',
name: 'SVN_TAG',
reverseByDate: false,
reverseByName: true,
tagsDir: 'https://svn-pro.xxxx.net:xxxxxx',
tagsFilter: ''
],
])
])
}
}
}
stage('Build') {
steps {
cleanWs()
checkoutSource()
buildSource()
buildInstaller()
}
}
stage('Deploy') {
steps {
copyArtifacts()
}
}
}
}
def copyArtifacts() {
cifsPublisher(publishers: [[configName: 'Server', transfers: [[cleanRemote: false, excludes: '', flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: 'builds\\$JOB_BASE_NAME\\${SVN_TAG}', remoteDirectorySDF: false, removePrefix: '\\unsigned', sourceFiles: '\\unsigned\\*.exe']], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true]])
}
Your environment variable idea is the correct way, just use double quotes ("") instead of single ones ('') to allow string interpolation, is it only works on double quotes in groovy. You can read more in the Groovy String Documentation.
So just use something like TAG = "${SVN_TAG.split('-')[1]}".
Then use that tag wherever you need it, you can pass it to relevant functions like copyArtifact or just use it as is: "builds\\$JOB_BASE_NAME\\${TAG}".

Jenkinsfile is not taking the build job parameter from job

I don't why Jenkinsfile is not taking the parameterized value from the job. I have this parameter $BUILD_UI.
Jenkinsfile:
stages {
stage("Prepare") {
when {
expression { return $BUILD_UI == 'true' }
}
steps {
checkout([$class: 'GitSCM',
branches: [[name: '$UI_BRANCH_NAME' ]],
extensions: [[$class: 'CleanCheckout'],
[$class: 'SubmoduleOption',
disableSubmodules: false,
parentCredentials: true,
recursiveSubmodules: true,
reference: '',
trackingSubmodules: false],
[$class: 'RelativeTargetDirectory',
relativeTargetDir: 'defender-ui/']],
userRemoteConfigs: [[
url: 'git#bitbucket.org:xxx/xxxxx.git',
credentialsId: 'xxxxxx-xxxxx-xxxx-xxxx'
]]
])
}
}
But I keep getting this error. This is not working return $BUILD_UI == 'true' :
groovy.lang.MissingPropertyException: No such property: $BUILD_UI for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:291)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:295)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:271)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:271)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:271)
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:13)
You must remove the $ from the variable name, so it will read:
return BUILD_UI == 'true'
This is because you are accessing the variable directly on groovy, without needing to expand it

Jenkins declarative pipeline: if-else statement inside parameters directive

I'm trying to display a choice parameter if I have options to choose from, or else display an input text, something like this (which does not work):
pipeline {
agent any
parameters {
if (someOptions) {
choice(name: 'FIELD_NAME', choices: "$someOptions", description: 'Field description')
} else {
string(name: 'FIELD_NAME', defaultValue: '', description: 'Field description')
}
}
environment {
// environment params
}
stages {
// stages
}
}
Is there a way of doing this?
To expand on #Matt Schuchard's comment, here's what this might look like:
def my_param = []
if (someOptions) {
my_param = [$class: 'ChoiceParameter',
name: 'FIELD_NAME',
choiceType: 'PT_SINGLE_SELECT',
description: 'Choose the desired option',
script:
[$class: 'GroovyScript',
fallbackScript:
[classpath: [], sandbox: false, script: 'return ""'],
script:
[classpath: [], sandbox: false, script: "return $someOptions"]
]
]
} else {
my_param = [$class: 'StringParameterDefinition',
name: 'FIELD_NAME',
defaultValue: false,
description: '']
}
properties([
parameters([my_param,
// other parameters
Don't forget to approve Groovy scripts in script approval console.

Resources