Creating environment variables and making changes to a JSON file with the Power Shell Script Plugin in Jenkins: A step-by-step guide

The JSON file is located at

%Workspace%\solution\config\appsettings.json

{
"appName": "Test",
"appId": "1",
"env" : "Test",
"url" : "https://url.com",
"client_id": "",
"client_secret": "",
"QAEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="452c3131202428052028242c296b262a28">[email protected]</a>",
"Preuri" : "https://preuri.com",
"Ravuri" : "https://Ravuri.com",
"Q&A"    : "https://QandA.com"
}

In order to keep client id and client secret secure, I cannot commit them to git. However, they are needed to run API test scripts through Jenkins.

To address this issue, we can modify the above json file using environment variables. I have set up two global credentials with secret text for CLIENT_ID and CLIENT_SECRET.

I am looking for assistance in creating a windows batch command that can replace the values of CLIENT_ID and CLIENT_SECRET in the JSON file.

For instance, if CLIENT_ID = 123456 and CLIENT_SECRET = 654321, the updated json file should look like this:

{
"appName": "Test",
"appId": "1",
"env" : "Test",
"url" : "https://url.com",
"client_id": "123456",
"client_secret": "654321",
"QAEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb928f8f9e9a96bb9e969a92">[email protected]</a>",
"Preuri" : "https://preuri.com",
"Ravuri" : "https://Ravuri.com",
"Q&A"    : "https://QandA.com"
}

Any guidance or support on this matter would be greatly appreciated.

Answer №1

Here is a little script that I put together:

set "file=data.json"
set "tmp=%TEMP%\settingsJSON_%time:~9,2%.json"
set "tab=    "
for /F "tokens=1* delims=: " %%V in (%file%) do if %%V=="user_id" ( echo %tab%%%V:"%USER_ID%">>%tmp% ) else ( if %%V=="password" ( echo %tab%%%V:"%PASSWORD%">>%tmp% ) else ( if [%%W]==[] ( echo %%V>>%tmp% ) else ( echo %tab%%%V:%%W>>%tmp% ) ) )
move "%tmp%" "%file%"

This worked for me, but remember to change "data.json" to the specific path of your JSON file.

Answer №2

I gave this method a try and it worked like a charm.

Step 1: Update your JSON file as shown below

{
"appName": "Test",
"appId": "1",
"env" : "Test",
"url" : "https://url.com",
"client_id": "CLIENT_ID_VALUE",
"client_secret": "CLIENT_SECRET_VALUE",
"QAEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="79100d0d1c1814391c14181015572s324do">[email protected]</a>",
"Preuri" : "https://preuri.com",
"Ravuri" : "https://Ravuri.com",
"Q&A"    : "https://QandA.com"
}

Step 2: Install the following Jenkins plugins

   **1)** Credentials plugin 

   **2)** Credential Binding Plugin

   **3)** Windows Power Shell Plugin

Step 3: Set up secret text with values Client_Id = "12345", Client_Secret = "54321" using Credentials Plugin (located on the left side of Jenkins). Create Environment variables "CLIENT_ID_VALUE" and "CLIENT_SECRET_VALUE" in the Bindings Tab.

Step 4: Add a step to execute Windows Power Shell and include the following script

(gc 'C:\Documents\application.json') -replace 'CLIENT_ID_VALUE', $env:CLIENT_ID_VALUE | Out-File 'C:\Documents\application.json'

(gc 'C:\Documents\application.json') -replace 'CLIENT_SECRET_VALUE', $env:CLIENT_SECRET_VALUE | Out-File
 'C:\Documents\application.json'

Answer №3

  1. Install a command-line editor that suits your needs (such as SED found in CygWin, UnixUtils, GnuWin32, etc)

  2. Add easily identifiable placeholders where you need to make changes:

{ "client_id": "@client@" "client_secret": "@secret@" "Environment" : "Dev" "Username" : "jenny" "Password" " "pwd123" }

  1. Use your editor to replace the placeholders in your files.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to iterate through JSON objects stored in a single location?

Currently, I am dealing with a single JSON object structured as follows: Object --> text --> body --> div Array[20] --> 0 Object --> text --> body --> div Array[20] --> 1 Object --> text --> body --> div Array[20] --> . ...

Transformation of a Python dataframe into a JSON structure

Trying to convert a python dictionary into JSON. Here is an example of the input dataframe: user_id |last_update_time |states| tile | update_time | message 11 |1571737828 |S231 |{'Action1': [200, 250, 300],|1571 ...

``There seems to be an issue decoding the JSON array

I am currently working on a PHP script to decode JSON data and insert the objects into my database. However, I am encountering an error: Fatal error: Cannot use object of type stdClass as array in phptest.php on line 21 $postdata = file_get_contents("php: ...

What's the most effective method: Utilizing generic code generation or hardcoding API calls?

Currently, I find myself in a situation where I am contemplating the best practice for handling my work on an Ecommerce website that involves orders, shipments, invoices, and more. In addition to creating the UI for my application, I also have the capabil ...

Tips for storing and replicating jQuery events

I am working on saving jQuery events in a database. // This Function is called On Click function trackevent(event){ window.events.push(event) } $.each(window.events, function(i, item){ console.log(i +" - "+ $.parseJSON(item)); }); The events a ...

The proper way to validate JSON data

After making an API call, I received the following response: [{ "1": { "name": "Euro", "iso": "EUR", "sign": "€" }, "2": { "name": "Dollar", "iso": "USD", "sign": "$" }, "3": { ...

You cannot convert a function to a string while utilizing axios get in nuxtServerInit

While attempting to connect my app to the backend using Udemy's Nuxt.js course, I encountered a GET http://localhost:3000/ 500 (Internal Server Error) on the client side with the following code: import Vuex from 'vuex'; import axios from &a ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

Guide on parsing a JavaScript file and converting the default export module to JSON with Node.js

What I'm trying to accomplish in my Node.js project is reading a sample.js file with ES Module syntax and extracting the default export from it. sample.js import foo from "foo"; const bar = [ { name: "Homer", }, { n ...

How can JSON be parsed in Android?

I am utilizing openstreetmap to retrieve the current city name. Here is the URL provided: The JSON result obtained is as follows: {"place_id":"62762024","licence":"Data \u00a9 OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetma ...

Retrieving a PHP value from a JSON string

Need help extracting the value from 'status' within a JSON Array named 'orders' { "orders": [ { "orderId": "F3MXBWMG61151028GUEST000P01", "orderCreateDate": "2015-10-28T09:2 ...

Unable to send data using GET method after implementing passportjs integration

In the route.js file, I have implemented the following REST method: app.get('/api/todos', isAuthenticated, function(req, res) { DB.TodoTable.find() .exec(function(err, todos) { res.json(todos, function(err){ if (err) ...

Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format: [ { "id": 12, "acf": { "address": { "city": "Bandar Penawar", "state": "Johor", "country ...

Transferring JSON encoded information from a controller to a view via ajax within the CodeIgniter framework

After selecting data from the controller, I want to display it on the view using a Bootstrap template. To achieve this, I need to place the following code in my controller: $data['sidebar']='member/dokter/sidebar_psn'; $data['cont ...

Interpret a JavaScript array response

Currently, I am working on an API request where I receive an HTTP response that contains an array with a single JSON object. However, when attempting to parse or stringify it using the following code: var response = http.response; try{ var json = J ...

JSON schema - validating objects with consistent data types

After generating this JSON structure: { "someString" : "example", "obj1" : { "opt1" : 1, "opt2" : 1, "opt3" : "aaa" }, "obj2" : { "opt1" : 55, "opt2" : 55, "opt3" : "bbb" } } I anticipate there will be additional object ...

Issue with populating JSON data into jQuery Datatable

Upon receiving a JSON response from the Django backend, I am facing difficulty in getting the datatable to read and display it properly. Any suggestions on how to achieve this? [{ "model": "model name", "pk": 2, "fields": { "name1 ...

Unable to retrieve a valid JSON from a freemaker collection

I am attempting to generate a functional JSON output (an array with x number of objects) from a freemaker ftl file. The code provided below works perfectly when there is only one object in the "loggedInUsers" array. However, if there is more than one obj ...

An error occurred when trying to convert a com.google.gson.JsonObject to a com.google.gson.JsonArray

I am encountering an issue with parsing a JSON response. Here is the response data: { "deal": { "categorie": { "description": "Offres Shopping", "idcategorie": "1", "nom": "Shopping" }, "cond ...

Issue with Google Calendar: Unable to locate com.google.api.client.json.JsonFactory.fromInputStream

Currently, I'm developing a Spring-MVC application and I'm facing an issue while trying to integrate Calendar functionality. The problem seems to be related to authentication due to a json error. I have been using Googles sample code but it appea ...