Jenkins: extended choice parameter - groovy - how to create file on the master - groovy

i have a json string defined in the groovy script part of the 'extended choice parameter' plugin. Additionally I want to write the json config in a file on the master side inside the groovy script area. I thought, maybe the job directory would be the best place?
http://hudson/hudson/job/MY_JOB/config.json
If you ask now, why i should do this; the reason behind is, i don´t want the config pre-saved somewhere else. I don´t like the idea of configuring the file outside of the job config. I want to see/adjust configs at one place - in the job config.
I need many other informations from the json config for later use in a python code section within the same job.
My questions are:
Am i following a wrong path here? Any suggestions?
can i write directly the json config on the master side? It doesn´t have to be the jenkins job directory. I don´t care about the device/directory.
if the approach is acceptable, how can i do this?
The following code doesn´t work:
def filename = "config.json"
def targetFile = new File(filename)
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
Remark:
hudson.FilePath looks interesting!
http://javadoc.jenkins-ci.org/hudson/FilePath.html
Thanks for your help, Simon

I got it:
import groovy.json.*
// location on the master : /srv/raid1/hudson/jobs
jsonConfigFile = new File("/srv/raid1/hudson/jobs/MY_JOB/config.json")
jsonConfigFileOnMaster = new hudson.FilePath( jsonConfigFile )
if( jsonConfigFileOnMaster.exists() ){
jsonConfigFileOnMaster.delete()
}
jsonConfigFileOnMaster.touch( System.nanoTime())
jsonFormatted = JsonOutput.toJson( localJsonString )
jsonConfigFile.write jsonFormatted

Related

How do I push an object to a JSON file with javascript?

So, I have my JSON file:
{
HomeWork: []
}
And I want to push an object:
{Title: T, Due: D, Description: Desc} To the JSON file, How should I do that? I am using this right now:
async function AddWork(obj) {
workData.HomeWork.push(obj);
//RNFS.writeFile('../../json/work.js', JSON.stringify(workData));
}
I tried whit the RNFS line, but it did not help.
If you want to do that, there is no edit mode ! so be careful .
If you read it and modify it , you are doing it locally, so you need override the file you are working on.
you need to read it using Read File in fs and then after you do the modification you need to Write it on the top of the file you are working with
I hope it helps <3

Script execution failed error in aem groovy console

I am trying to update sling:resourceType and node name in aem using groovy script. Everytime when I run the script I am getting "Script execution failed error".
List<String> pages= new ArrayList<String>();
getNode('/content').recurse {rootNode ->
if (rootNode.hasProperty('property')) {
pages.add(rootNode.getParent().getPath());
}
}
#rmac, your script seems to be fine, Please try to navigate to locale level and execute the script.
I am assuming, it is getting timed out. Iterating through '/content' will take lot of time and might time out sometimes.
Try updating your path to '/content/sitename/en' or even deep in the hierarchy if you have a lot of content.
Please share the complete error in case if it is not working.
If it still helps:
import org.apache.sling.api.resource.ResourceResolver
import javax.jcr.Node
import javax.jcr.Session
session = resourceResolver.adaptTo(Session.class);
Node node = session.getNode("/content/we-
retail/us/en/jcr:content/root/hero_image");
node.getSession().move(node.getPath(), node.getParent().getPath() + "/" +
"test");
node.setProperty("prop", "value");
save()

Node.js Writing into YAML file

I'm using Node.js and I'm having trouble figuring out how could I read a YAML file, replace a value in it, and write the updated value to the YAML file.
I'm currently using the module "yamljs" which allows me to load the YAML file and I've managed to edit the value in the loaded Object.
The only part I need help with, is how to write to the YAML file.
Cause for some reason, I can't find the solution for that anywhere, and I'm not even sure if I could use the module for that.
The module does have some command line tools, but I'm not too sure how to use those either.
The module "js-yaml" worked for my case. https://github.com/nodeca/js-yaml
Here's the code I used:
const yaml = require('js-yaml');
...
let doc = yaml.safeLoad(fs.readFileSync('./Settings.yml', 'utf8'));
doc.General.Greeting = newGreet;
fs.writeFile('./Settings.yml', yaml.safeDump(doc), (err) => {
if (err) {
console.log(err);
}
});

how to create environment variables to store data in a file?

Hey actually i am doing some project in Nodejs. I need a configuration file in order to store the data to file system but i do not know how to write a configuration file to store data to file. please help me with this. thanks in advance
Sounds to me that you are looking for the following NPM module/library - dotenv. You simply require('dotenv').config(); which is probably best placed at the top (after use strict;) and create a text file which would read as an example:
url_prefix='mongodb://'
url_ip='#localhost'
port=':27017/'
dbase='NameofDB'
Of course you can add anything you like to this file. Just remember it is a text file and should not contain spaces etc.
Though the default for the .env file is in the root of your project you can actually place it wherever you like, and simply put:
require('dotenv').config({path: '/custom/path/to/your/env/vars'});
(Above was taken from the dotenv documentation and it works as I use it in projects.)
To acquire any Global variable you would simply type:
process.env.url_prefix
Obviously from there you can build the needed entry code to your DB from process.env statements such as:
process.env.url_prefix+process.env.url_ip etc. OR
${process.env.url_prefix}${process.env.url_ip}
Using dotenv allows you to keep sane control over those process.env globals.
Be aware there is a gotcha! Be careful not to overwrite any of those globals in your code. As they will remain overwritten as long as your Node process is running.
If you mean you need some constants and business logic/data file to read from, you can simply include the file in your script using the require module.
Ex: Your file name is test.json, then:
var test = require('test.json');
Further, you can use a CONSTANT in the file as 'test.CONSTANT'
Note: Please make sure you use module.exports wherever needed. Details are here
Usually people use JSON to store configurations and stuff, since it is very javascripty.. You can simply make a JSON config file. In case you need to store some special data like SECRET URL, just use environment variables. FYI I found your question unclear. Does this answer your question.
const fs = require("fs");
// Example Config
let config = {
DB: "mongodb://blahblah:idhdiw#jsjsdi",
secret: "thisandthat",
someScript: "blah.js"
};
// Write to file.
fs.writeFile('config.cfg', JSON.stringify(config), err => {
if (err) throw err;
console.log("[+] Config file saved!");
// Retrieve
let confData = JSON.parse(fs.readFileSync('config.cfg'));
console.log(confData.secret);
});
// To save variables in environment variables
// Generally You will not set environment variables like this
// You will have access to setting environment variables incase
// you are using heroku or AWS from dash board. Incase of a machine
// you can use ** export SOME_ENV_VAR="value" ** in your bash profile
process.env.IP = "10.10.10.10";
// Too risky to put else where.
process.env.API_KEY = "2ke9u82hde82h8";
// Get Data
console.log(process.env.IP);
console.log(process.env.API_KEY);

Standalone PHP script using Expression Engine

Is there a way to make a script where I can do stuff like $this->EE->db (i.e. using Expression Engine's classes, for example to access the database), but that can be run in the command line?
I tried searching for it, but the docs don't seem to contain this information (please correct me if I'm wrong). I'm using EE 2.4 (the link above should point to 2.4 docs).
The following article seems to have a possible approach: Bootstrapping EE for CLI Access
Duplicate your index.php file and name it cli.php.
Move the index.php file outside your DOCUMENT_ROOT. Now, technically, this isn’t required, but there’s no reason for prying
eyes to see your hard work so why not protect it.
Inside cli.php update the $system_path on line 26 to point to your system folder.
Inside cli.php update the $routing['controller'] on line 96 to be cli.
Inside cli.php update the APPPATH on line 96 to be $system_path.'cli/'.
Duplicate the system/expressionengine directory and name it system/cli.
Duplicate the cli/controllers/ee.php file and name it cli/controllers/cli.php.
Finally, update the class name in cli/controllers/cli.php to be Cli and remove the methods.
By default EE calls the index method, so add in an index method to do what you need.
#Zenbuman This was useful as a starting point although I would add I had issues with all of my requests going to cli -> index, whereas I wanted some that went to cli->task1, cli->task2 etc
I had to update *system\codeigniter\system\core\URI.php*so that it knew how to extract the parameters I was passing via the command line, I got the code below from a more recent version of Codeigniter which supports the CLI
// Is the request coming from the command line?
if (php_sapi_name() == 'cli' or defined('STDIN'))
{
$this->_set_uri_string($this->_parse_cli_args());
return;
}
// Let's try the REQUEST_URI first, this will work in most situations
and also created the function in the same file
private function _parse_cli_args()
{
$args = array_slice($_SERVER['argv'], 1);
return $args ? '/' . implode('/', $args) : '';
}
Also had to comment out the following in my cli.php file as all routing was going to the index method in my cli controller and ignoring my parameters
/*
* ~ line 109 - 111 /cli.php
* ---------------------------------------------------------------
* Disable all routing, send everything to the frontend
* ---------------------------------------------------------------
*/
$routing['directory'] = '';
$routing['controller'] = 'cli';
//$routing['function'] = '';
Even leaving
$routing['function'] = '';
Will force requests to go to index controller
In the end I felt this was a bit hacky but I really need to use the EE API library in my case. Otherwise I would have just created a separate application with Codeigniter to handle my CLI needs, hope the above helps others.
I found #Zenbuman's answer after solving my own variation of this problem. My example allows you to keep the cron script inside a module, so if you need your module to have a cron feature it all stays neatly packaged together. Here's a detailed guide on my blog.

Resources