Skip to content

Instantly share code, notes, and snippets.

@vo
Last active June 9, 2022 22:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vo/85ccc69d0747a7ecf821aead64923bb7 to your computer and use it in GitHub Desktop.
Save vo/85ccc69d0747a7ecf821aead64923bb7 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
####
#
# Usage:
# ./add_var.py [key] [value]
#
####
import re
import sys
replacement = sys.argv[1] + '\t' + sys.argv[2]
group = None
replaced = False
found_defaults_group = False
indent = ''
for line in open('haproxy.cfg'):
if replaced:
# we have finished replacements, nothing else needed
print line,
continue
found_group = re.search('^(\S+).*',line)
if found_group:
# we found a new group
new_group = found_group.group(1)
if new_group == 'defaults':
found_defaults_group = True
elif group == 'defaults' and new_group != 'defaults' and not replaced:
# we left the 'global' group without replacing something
print indent + replacement
replaced = True
group = new_group
elif found_defaults_group:
found_indented_line = re.search('^(\s+)(.*)', line)
if found_indented_line and len(found_indented_line.group(2).strip()) != 0:
indent = found_indented_line.group(1)
# we found a indented line
val = found_indented_line.group(2)
if val.startswith(sys.argv[1]):
# the key in that line matches the replacement key
print indent + replacement
replaced = True
continue
elif replaced == False:
# we got to a line that's neither a group nor an indented line
# so print the replacement plus the line
print indent + replacement
replaced = True
print line,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment