Skip to content

Instantly share code, notes, and snippets.

@andymotta
Created April 18, 2019 19:17
Show Gist options
  • Save andymotta/010551586235e7403c561c5e3ec7a4f0 to your computer and use it in GitHub Desktop.
Save andymotta/010551586235e7403c561c5e3ec7a4f0 to your computer and use it in GitHub Desktop.
IaC Pipeline: Detect changes/errors in Terraform Plan
#!/usr/bin/python
from subprocess import call, check_output, CalledProcessError
import subprocess
import fnmatch
import os
from datetime import datetime
logfile = "changes_" + datetime.now().strftime("%Y%m%d-%H%M%S") + ".log"
matches = []
for root, dirnames, filenames in os.walk('/Users/andymotta/git'):
for filename in fnmatch.filter(filenames, 'main.tf'):
matches.append(root)
with open(logfile, "a") as f:
for d in matches:
try:
os.chdir(d)
call(["terraform", "init"])
out = check_output(["terraform", "plan", "-input=false", "-detailed-exitcode"], stderr=subprocess.STDOUT)
except CalledProcessError as e:
if e.returncode == 1:
# message = "DETECTED ERROR IN " + d + "\n"
message = "DETECTED ERROR IN " + d + "\n" + e.output + "\n\n\n"
if e.returncode == 2:
# message = "DETECTED CHANGES IN " + d + "\n"
message = "DETECTED CHANGES IN " + d + "\n" + e.output + "\n\n\n"
f.write(message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment