Skip to content

Instantly share code, notes, and snippets.

@bradyclifford
Last active March 2, 2022 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradyclifford/bb9b6a0d87df79c906d9041649d288f1 to your computer and use it in GitHub Desktop.
Save bradyclifford/bb9b6a0d87df79c906d9041649d288f1 to your computer and use it in GitHub Desktop.
Terraform Show to Terraform Import
// Run using node
// Output first before running this command terraform show -json > file.json
const tfShowOutput = require(process.argv.slice(2)[0]);
function parseChildModules(modules) {
for (const {address: parentAddress, child_modules : childModules, resources} of modules) {
if (childModules) parseChildModules(childModules);
if (!resources?.length) continue;
const managed = resources
.filter(({ mode }) => mode === 'managed');
if (!managed.length) continue;
console.log(`# ${parentAddress} ----`)
managed
.map(({ address, values, type }) => {
const {id} = values;
return {address, id, type}
})
.forEach(({address, id, type}) => {
let fixedId = id;
if (['azurerm_key_vault_secret'].includes(type)) {
fixedId = `${id.split('/').slice(0, -1).join('/')}/{{add-version-id}}`;
}
const mustManuallyModify = address.includes('|') || ['azurerm_key_vault_secret', 'azurerm_role_assignment'].includes(type);
if (mustManuallyModify) {
console.log();
console.log(`# ${parentAddress} - ${type}`);
}
console.log(`${mustManuallyModify ? '# ' : ''}terraform import -var="pagerduty_token=xyz" '${address}' "${fixedId}"`);
if (mustManuallyModify) console.log();
})
console.log()
}
}
parseChildModules(tfShowOutput.values.root_module.child_modules);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment