Skip to content

Instantly share code, notes, and snippets.

@andr1an
Created October 22, 2024 09:22
Show Gist options
  • Select an option

  • Save andr1an/79735bb4d84d814e0fb378835b01068d to your computer and use it in GitHub Desktop.

Select an option

Save andr1an/79735bb4d84d814e0fb378835b01068d to your computer and use it in GitHub Desktop.
Expand include directives in NGINX configuration files
#!/usr/bin/env python
from __future__ import print_function
import argparse
import glob
import os
import re
import sys
RE_INCLUDE = re.compile(r"^(?P<indent>\s*)include\s+(?P<pathspec>[^;]+)\s*;.*$")
def cat_config(filepath, indent="", basedir="/etc/nginx"):
try:
with open(filepath, "r") as fp_conf:
for line in fp_conf:
line = line.rstrip("\n")
match = RE_INCLUDE.match(line)
if match:
new_indent = match.group("indent")
pathspec = match.group("pathspec")
if not os.path.isabs(pathspec):
pathspec = os.path.join(basedir, pathspec)
for new_filepath in sorted(glob.glob(pathspec)):
print("{}#expanded: {}".format(indent + new_indent, new_filepath))
cat_config(new_filepath, indent=indent + new_indent, basedir=basedir)
print("{}#endof: {}".format(indent + new_indent, new_filepath))
else:
print("{}{}".format(indent, line))
except (IOError, OSError):
print("{}#error: can't open file {}".format(indent, filepath))
def parse_args(argv=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Expand include directives in NGINX configuration files")
parser.add_argument("file", help="Path to the config file")
parser.add_argument("--basedir", "-B", default="/etc/nginx", help="NGINX configuration directory")
return parser.parse_args(argv)
def main():
args = parse_args()
cat_config(args.file, basedir=args.basedir)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment