Last active
December 14, 2021 20:29
-
-
Save dtelaroli/4761ccafe6f2050d074c77c9ce9cb560 to your computer and use it in GitHub Desktop.
Script in node to cleanup terraform state file based on terraform file
This file contains 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
# $1 parameter inverse (true|false) | |
# inverse true remove what is in tf file | |
# inverse false remove what is not in tf file | |
# command: node clean-tf-state.js [true|false] | |
const json = require("./state.json") | |
const fs = require('fs') | |
const inverse = process.argv[1] | |
const parse = (item) => { | |
if(item.module) { | |
return item.module.replace(/([^\.]+)\.([^\.]+).+/, '\$1 "\$2') | |
} | |
return `${item.type}" "${item.name}` | |
} | |
fs.readFile(`./main.tf`, 'utf8', (err, data) => { | |
if (err) { | |
return console.log(err); | |
} | |
console.log('original', json.resources.length) | |
const template = {...json} | |
const cache = [] | |
json.resources.map((item) => { | |
const custom = parse(item) | |
return {...item, custom} | |
}) | |
.forEach((item) => { | |
if(data.includes(item.custom) && !inverse || !data.includes(item.custom) && inverse) { | |
cache.push(item) | |
} | |
}) | |
template.resources = cache | |
console.log('resources', template.resources.length) | |
const file = inverse ? './new-state-inverse.json' : `./new-state.json` | |
fs.writeFile(file, JSON.stringify(template, null, 2), () => {}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment