Skip to content

Instantly share code, notes, and snippets.

@lordjabez
Created May 24, 2023 19:45
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 lordjabez/7efad392277784a9c1756a93103c97f1 to your computer and use it in GitHub Desktop.
Save lordjabez/7efad392277784a9c1756a93103c97f1 to your computer and use it in GitHub Desktop.
Run terraform against a set of files
#!/usr/bin/env python3
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--files', action='append')
file_arguments, other_arguments = parser.parse_known_args()
terraform_filenames = file_arguments.files or []
def get_target_name(line):
items = line.replace('"', '').split()
if not items:
return
if items[0] == 'resource':
return f'{items[1]}.{items[2]}'
elif items[0] == 'module':
return f'module.{items[1]}'
def get_target_names(terraform_filename):
with open(terraform_filename) as terraform_file:
target_lines = (get_target_name(n) for n in terraform_file)
return [t for t in target_lines if t is not None]
target_names = [t for f in terraform_filenames for t in get_target_names(f)]
target_arguments = [a for t in target_names for a in ('--target', t)]
terraform_command = ['terraform'] + other_arguments + target_arguments
subprocess.run(terraform_command)
@lordjabez
Copy link
Author

Example usage:

terraform-files apply --file my-stuff.tf --file my-other-stuff.tf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment