Last active
January 21, 2021 08:25
-
-
Save bradymholt/17cb99185c7b80b0f34a to your computer and use it in GitHub Desktop.
Ansible module to replace values in JSON files https://www.geekytidbits.com/ansible-module-modify-json/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
var fs = require('fs'); | |
var args = fs.readFileSync(process.argv[2], 'utf8'); | |
var changed = false; | |
var jsonPath = null; | |
var json = null; | |
var keyValReplacementString = args.split(' '); | |
keyValReplacementString.forEach(function(i){ | |
var keyVal = i.split('='); | |
if (!keyVal[1]) { | |
return; | |
} else if (keyVal[0].indexOf('path') == 0) { | |
jsonPath = stripQuotes(keyVal[1]); | |
} | |
}); | |
if (jsonPath){ | |
json = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); | |
keyValReplacementString.forEach(function(i){ | |
var keyVal = i.split('='); | |
if (keyVal[0].indexOf('path') == -1 && json[keyVal[0]]) { | |
json[keyVal[0]] = stripQuotes(keyVal[1]); | |
} | |
}); | |
fs.writeFileSync(jsonPath, JSON.stringify(json, null, 2)); | |
changed = true; | |
} | |
function stripQuotes(text) { | |
return text.replace(/["']*([^'"]+)['"]*"/g, '$1'); | |
} | |
console.log(JSON.stringify({ changed: changed })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If value is having space then its considering only first letter . How to do that