Writing to a json file in workspace using Jenkins - 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.

Related

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

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)

Reading parameters in Jenkins from .js or Json file

I have a .js or json file where all my parameters are defined. I want to use this file and have Jenkins read these parameter name from file during build and display such that Suite1 is displayed one job and parameters for Suite2 in another.
For Suite1, jenkins should show smoke and default however for Suite 2 it should show default and Testing in drop down. Can anyone please suggest right way to do it?
module.exports = {
Suite1: {
smoke: ['file1.spec.js','file2.spec.js],
default: ['file3.spec.js']
},
Suite2: {
default: ['file2.spec.js'],
Testing: ['file2.spec.js']
}
}
I tried extended Choice parameter but not getting desired results as there is no way of importing Json file as parameter in there.

how to write to a file using DSL [Jenkins]?

I'm presently making a build flow using DSL.
After searching for I while I've been able to find how to read from a text file, but not how to write to one.
Is there a command for it in DSL?
And also I'd take the opportunity to ask where I can find a tutorial or command list for DSL?
Since the DSL is Groovy based I guess you can write any Groovy code and it should work, refer http://grails.asia/groovy-file-examples to get an example of how to write to a file. The DSL commands are provided at https://jenkinsci.github.io/job-dsl-plugin/ and you can try them out at the playground at http://job-dsl.herokuapp.com/.
By default, you cannot use new File(...).text for security reasons. You can use writefile instead:
writeFile file: "myfile.txt", text: "File content."
This is the best I've been able to come up with, it uses writeFile:
def readEscape(String file) {
return readFileFromWorkspace(file).replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\$", '\\$')
}
def Dockerfile = readEscape('./Dockerfile')
pipelineJob('sample-write-file') {
definition {
cps {
script('''
pipeline {
agent any
stages {
stage("prep-files") {
steps {
writeFile file: './Dockerfile', text: "''' + Dockerfile + '''"
}
}
}
}
''')
}
}
}
The question is unclear about whether the file needs to be written during the processing of the job dsl or during the generated job's execution. Since I needed this for the job execution, that is what my example shows. The file will be read while creating the job and embedded in the created job definition.

In Grails, how can I append a build number when using 'set-version'

I am using Jenkins (Hudson) with the Grails plugin to do builds as I update svn. I found this example script that allows you to incorporate a build number from an env var:
set-version 1.1.0.${env['BUILD_NUMBER']}
But as you see, the prefix is hard-coded. I'd like to use the version number set in the application.properties file. How can I do something like:
set-version ${app.version}.${env['BUILD_NUMBER']}
Have tried a variety of scopes/syntax to no avail.
It is not possible out of the box. Jenkins or specifically the Grails plugin does not read the content of the application.properties file and hence the existing application version is not available as a variable.
You might want to consider writing a custom script in your application (like append-version) that will read application.properties and append the value passed in. You can call the existing set-version script modifying the argument.
I have also created a simple script that should do the job:
includeTargets << grailsScript("Init")
target(main: "Append a string to the existing version number") {
depends(checkVersion, parseArguments)
def newVersion = metadata.'app.version' + '-' + args
metadata.'app.version' = newVersion
metadata.persist()
}
setDefaultTarget(main)

Resources