Skip to content

Instantly share code, notes, and snippets.

@djhaskin987
Created October 6, 2023 17:56
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 djhaskin987/b856c157bcfce6d2e4ee19f9732e5194 to your computer and use it in GitHub Desktop.
Save djhaskin987/b856c157bcfce6d2e4ee19f9732e5194 to your computer and use it in GitHub Desktop.
from Levenshtein import distance
import subprocess
import re
import sys
import pprint
print("Running terraform plan...", file=sys.stderr)
proc = subprocess.run(
["terraform", "plan", "-no-color"],
capture_output=True,
text=True,
check=True,
)
print("Parsing output...", file=sys.stderr)
find_modification = re.compile(
r"(?P<resource>[^ ]+) will be (?P<cord>created|destroyed)")
created = []
destroyed = []
for line in proc.stdout.split("\n"):
if '#' in line:
print(f"line: `{line}`", file=sys.stderr)
m = find_modification.search(line)
if m:
if m.group("cord") == "created":
created.append(m.group("resource"))
else:
destroyed.append(m.group("resource"))
print(f"Matched {len(created)} creations and {len(destroyed)} destructions.",
file=sys.stderr)
print("Computing Levenshtein Distances...", file=sys.stderr)
moved = {}
for d in destroyed:
others = []
for c in created:
others.append((distance(d, c), c))
others.sort(key=lambda tuple: tuple[0])
if len(others) > 0:
moved[d] = others[0][1]
print("Writing moved blocks...", file=sys.stderr)
for d, c in moved.items():
print(
f"""
moved {"{"}
from = {d}
to = {c}
{"}"}
"""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment