Jenkins : [parameterized-trigger] Properties file - jenkins

I am using "Parameterized Trigger Plugin" to trigger child job. I am using "parametres from properties file" and in the "Use properties from file" in need to pass the name of the file as a variable...I get this error.
[parameterized-trigger] Properties file $propeties_file did not exist.
enter image description here

If you click on the ? you will see the usage / syntax for the property file:
Comma seperated list of absolute or relative paths to file(s) that
contains the parameters for the new project. Relative paths are
originated from the workspace. The file should have KEY=value pairs,
one per line (Java properties file format). Backslashes are used for
escaping, so use "\\" for a single backslash. Current build
paramenters and/or environment variables can be used in form: ${PARAM}
or $PARAM.
So your file needs to exist and you should put the path to the file to where you are putting your $properties_file - I don't believe it will accept a variable, you should put the file name in there.

A sample pipeline to trigger parameterize build using parameters from the properties file
pipeline {
agent any
stages {
stage('S1') {
steps {
echo 'In S1'
sh '''
echo "param1=value1" > my.properties
echo "param2=value2" >> my.properties
'''
}
}
stage('s2'){
steps {
script {
def props = readProperties file:"${WORKSPACE}/my.properties"
build job: 'called_job', parameters: props.collect {string(name: it.key, value: it.value)}
}
}
}
}
}

Related

Jenkins DSL custom config file folder

We are using DSL to build/setup our Jenkins structure.
In it, we create our folder structure and then all our jobs within the folders.
The jobs end up in the correct folders by including the folder name in the job name
pipelineJob('folder/subfolder/Job Name') {}
While the UI lets me create a config file within a folder, I cannot find a way within the dsl groovy script hierachy to put a custom config file in a folder.
While I can easily create a config file:
configFiles {
customConfig {
name('myCustom.yaml')
id('59f394fc-40fe-489d-989c-7556c1a01153')
content('yaml content goes here')
}
}
There seems to be no way to put this file into a folder / subfolder.
While the Job DSL plugin does not offer an easy way to do this, you can use a configure block to directly modify the xml.
folder('Config-File Example') {
description("Example of a Folder with a Config-File, created via Job DSL")
configure { folder ->
folder / 'properties' << 'org.jenkinsci.plugins.configfiles.folder.FolderConfigFileProperty'() {
configs(class: 'sorted-set') {
comparator(class: 'org.jenkinsci.plugins.configfiles.ConfigByIdComparator')
'org.jenkinsci.plugins.configfiles.json.JsonConfig'() {
id 'my-config-file-id'
providerId 'org.jenkinsci.plugins.configfiles.json.JsonConfig'
name 'My Config-File Name'
comment 'This contains my awesome configuration data'
// Use special characters as-is, they will be encoded automatically
content '[ "1", \'2\', "<>$%&" ]'
}
}
}
}
}

how to call property file syntax and define in JOB DSL in jenkins

I want to use property file in DSL job which will take my project name in job name and svn location . Can anyone have idea how to write and syntax?
For handling properties files stored outside your repository, you have a plugin called "Config File Provider Plugin".
You use it like this:
stage('Add Config files') {
steps {
configFileProvider([configFile(fileId: 'ID-of-file0in-jenkins', targetLocation: 'path/destinationfile')]) {
// some block
}
}
}
It is capable of replacing tokens in json and xml or the whole file (as in the example)
For handling data comming from the SVN or project name you can access the environment variables. See this thread and this link

Concatenate file name in pipeline steps script

I am trying to concatenate a file name by appending strings and the build number within the steps script in my Jenkinsfile and then pass it to create a zipFile, but the environment build number does not get recognized in the concatenated string. What is the correct syntax?
stage ('Publish Reports') {
steps {
script {
def fileName = "reportFiles/" + '${env.BUILD_NUMBER}' + ".zip"
zip zipFile: fileName, archive: false, dir: 'target/site/main'
}
}
}
With this syntax, the fileName gets saved as:
reportFiles/${env.BUILD_NUMBER}.zip,
instead of the actual build number, for example :
reportFiles/1.zip
Actually, i found a resolution of the issue, it was a silly syntax error. The correct declaration was:
def fileName = "reportFiles/${env.BUILD_NUMBER}.zip"

Jenkins...Modify XML Tag value in xml file using Groovy in Jenkins

I am using jenkins for automated deployment.
I needs to modify xml tag value in xml file using groovy script. I am using below groovy code. When I try to edit xml tag value I am receiving error unclassified field xml.uti.node error.
Node xml = xmlParser.parse(new File("c:/abc/test.xml"))
xml.DeployerServer.host[0] = '172.20.204.49:7100'
FileWriter fileWriter = new FileWriter("c:/abc/test.xml")
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)
I need to modify host tag value and host is available inside DeployerServer tag.
Any help will be much appreciated.
Here is the script, comments in-line:
//Create file object
def file = new File('c:/abc/test.xml')
//Parse it with XmlSlurper
def xml = new XmlSlurper().parse(file)
//Update the node value using replaceBody
xml.DeployerServer.host[0].replaceBody '172.20.204.49:7100'
//Create the update xml string
def updatedXml = groovy.xml.XmlUtil.serialize(xml)
//Write the content back
file.write(updatedXml)
I was wanting to read / manipulate the CSProj file and NUSPEC files in a Pipeline script. I could not get passed the parseText() without the dreaded "SAXParseException: Content is not allowed in prolog".
There are quite a few threads about this error message. What wasn't clear is that both CSProj and NUSPEC files are UTF-8 with BOM - BUT this is invisible!
To make it worse I've been trying to automate the NUSPEC file creation, and there is no way I can tell the tools to change file encoding.
The answers above helped solve my issue, and once I added code to look for 65279 as the first character (and deleted it). I could then parse the XML and carry out the above.
There didn't seem to be good thread to put this summary on, so added it to a thread about Jenkins, Groovy & XML files which is where I found this "known Java" issue.
I used powershell to do this change in app.config file.
My problem was with passwords. So, I created a Credential, in jenkins, to store the password.
If you do not need to work with credential, just remove the withCredentials section
Here is part of my jenkinsfile:
def appConfigPath = "\\server\folder\app.config"
stage('Change App.Config'){
steps{
withCredentials([string(credentialsId: 'CREDENTIAL_NAME', variable: 'PWD')]) {
powershell(returnStdout: true, script: '''
Function swapAppSetting {
param([string]$key,[string]$value )
$obj = $doc.configuration.appSettings.add | where {$_.Key -eq $key }
$obj.value = $value
}
$webConfig = "'''+appConfigPath+'''"
$doc = [Xml](Get-Content $webConfig)
swapAppSetting 'TAG_TO_MODIFY' 'VALUE_TO_CHANGE'
$doc.Save($webConfig)
''')
}
}
}
Don`t forget to update your powershell. (minimum version 3)

Writing to a json file in workspace using Jenkins

I've a jenkins job with few parameters setup and I've a JSON file in the workspace which has to be updated with the parameters that I pass through jenkins.
Example:
I have the following parameters which I'll take input from user who triggers the job:
Environment (Consider user selects "ENV2")
Filename (Consider user keeps the default value)
I have a json file in my workspace under run/job.json with the following contents:
{
environment: "ENV1",
filename: "abc.txt"
}
Now whatever the value is given by user before triggering a job has to be replaced in the job.json.
So when the user triggers the job, the job.json file should be:
{
environment: "ENV2",
filename: "abc.txt"
}
Please note the environment value in the json which has to be updated.
I've tried https://wiki.jenkins-ci.org/display/JENKINS/Config+File+Provider+Plugin plugin. But I'm unable to find any help on parameterizing the values.
Kindly suggest on configuring this plugin or suggest any other plugin which can serve my purpose.
Config File Provider Plugin doesn't allow you to pass parameters to configuration files. You can solve your problem with any scripting language. My favorite approach is using Groovy plugin. Hit a check-box "Execute system Groovy script" and paste the following script:
import groovy.json.*
// read build parameters
env = build.getEnvironment(listener)
environment = env.get('environment')
filename = env.get('filename')
// prepare json
def builder = new JsonBuilder()
builder environment: environment, filename: filename
json = builder.toPrettyString()
// print to console and write to a file
println json
new File(build.workspace.toString() + "\\job.json").write(json)
Output sample:
{
"environment": "ENV2",
"filename": "abc.txt"
}
With Pipeline Utility Steps plugin this is very easy to achieve.
jsonfile = readJSON file: 'path/to/your.json'
jsonfile['environment'] = 'ENV2'
writeJSON file: 'path/to/your.json', json: jsonfile
I will keep it simple. A windows batch file or a shell script (depending on the OS) which will read the environment values and open the JSON file and make the changes.

Resources