Created
April 1, 2025 03:26
-
-
Save csirmazbendeguz/1f19a8b3f4f9a22dc50458371f00284b to your computer and use it in GitHub Desktop.
A Python script to destroy a Terragrunt unit recursively
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
| import argparse | |
| import json | |
| import subprocess | |
| from dataclasses import dataclass, field | |
| from typing import Self | |
| def find() -> list[dict]: | |
| args = [ | |
| "terragrunt", | |
| "find", | |
| "--dependencies", | |
| "--format=json", | |
| "--experiment=cli-redesign", | |
| ] | |
| print(" ".join(args)) | |
| result = subprocess.run( | |
| args, | |
| stderr=subprocess.STDOUT, | |
| stdout=subprocess.PIPE, | |
| ) | |
| return json.loads(result.stdout) | |
| def destroy(path: str) -> None: | |
| args = [ | |
| "terragrunt", | |
| "run-all", | |
| "destroy", | |
| f"--working-dir={path}", | |
| "--queue-exclude-external", | |
| "--non-interactive", | |
| ] | |
| print(" ".join(args)) | |
| subprocess.run(args) | |
| @dataclass | |
| class Unit: | |
| path: str | |
| children: list[Self] = field(default_factory=lambda: []) | |
| is_destroyed: bool = False | |
| def destroy(self) -> None: | |
| if self.is_destroyed: | |
| return | |
| for child in self.children: | |
| child.destroy() | |
| destroy(self.path) | |
| self.is_destroyed = True | |
| def parse_units(units: list[dict]) -> dict[str, Unit]: | |
| result = {} | |
| for unit in units: | |
| path = unit["path"] | |
| result[path] = Unit(path) | |
| for unit in units: | |
| path = unit["path"] | |
| dependencies = unit.get("dependencies", []) | |
| for dependency in dependencies: | |
| result[dependency].children.append(result[path]) | |
| return result | |
| def destroy_unit(unit: str): | |
| units = parse_units(find()) | |
| units[unit].destroy() | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('unit', help='The Terragrunt unit to destroy') | |
| args = vars(parser.parse_args()) | |
| unit = args['unit'] | |
| destroy_unit(unit) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment