Last active
December 25, 2015 05:39
-
-
Save jaimegago/6926304 to your computer and use it in GitHub Desktop.
A script that detects unmodified templates Ansible files and adds the ansible_managed commented out. Deals with XML files comment syntax by reading first line.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#A script that detects unmodified templates Ansible files and adds the ansible_managed commented | |
# out. Deals with XML files comment syntax by reading first line. | |
import fileinput | |
import os | |
import re | |
#Defining different headers as commenting syntax is different for XML | |
headers_text = '##### ANSIBLE INFO ######\n# {{ ansible_managed }}\n## END ANSIBLE INFO ##' | |
headers_xml = '<!-- - - - - - - - - ANSIBLE INFO - - - - - - - - - - - - - - - -->\n<!-- {{ ansible_managed }} -->\n<!-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -->' | |
#First get files in templates directories | |
for root, dirs, files in os.walk("git_checkout_ansible_dir"): | |
if re.search('templates',root): | |
for file in files: | |
#Detect if the file already has been modified for Ansible | |
f = open(str(root)+'/'+str(file),'r') | |
if '{{ ansible_managed }}' not in open(str(root)+'/'+str(file)).read(): | |
f = open(str(root)+'/'+str(file),'r') | |
for line in f: | |
#Deal with XML files by reading first line | |
#Yes this is ugly and should be done with something like ElementTree to validate the xml | |
if line.startswith('<?xml version='): | |
for line in fileinput.input(str(root) + '/' + str(file), inplace=True): | |
if fileinput.lineno() == 2: | |
print headers_xml | |
print line, | |
#Now that XML files have been modified do the other ones (XML ones will already contain ANSIBLE INFO and will be filtered out | |
f = open(str(root)+'/'+str(file),'r') | |
if '{{ ansible_managed }}' not in open(str(root)+'/'+str(file)).read(): | |
for line in fileinput.input(str(root) + '/' + str(file), inplace=True): | |
if fileinput.isfirstline(): | |
print headers_text | |
print line, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment