Skip to content

Instantly share code, notes, and snippets.

@ankona
Created May 4, 2016 17:41
Show Gist options
  • Save ankona/818cee1abeb569020f0355f7dd01245f to your computer and use it in GitHub Desktop.
Save ankona/818cee1abeb569020f0355f7dd01245f to your computer and use it in GitHub Desktop.
script to alter a templatized swagger file so it can be pasted into a cloudformation script as a ::RestApi body value
import re
import json
p = re.compile("\{\{[\w]+\}\}")
input_path = '/path/to/swagger.json'
add_whitespace = False
f = open(input_path)
fw = open(input_path + '.notokens', 'w')
# use the join/split trick to get rid of whitespace greater than a single space
file_content = json.dumps(" ".join(f.read().split()))
print file_content
arr = p.findall(file_content)
working_part = file_content[1:-1]
match_doc = "{\"Fn::Join\": [\"\", ["
for a in arr:
# split the content of the json / swagger file on a template item like {{lambda_function_name}}.
# part[0] = [some json without any templates]
# part[1] = {{some_template}}
# part[2] = everything after the first match to the regex in the document/string
partitions = working_part.partition(a)
# just append the non-template string to our output string
if add_whitespace:
match_doc = match_doc + '\t\t"' + partitions[0] + '",\n'
else:
match_doc = match_doc + '"' + partitions[0] + '", '
# rewrite the template token we found so it ties into the cloudformation script
# (note that i'm just stripping off the first & last 2 charactrs of the token '{{' and '}}')
token = partitions[1]
script_resource_name = token[2:-2]
if add_whitespace:
template_reformat = '\t\t{ "Fn::GetAtt": [ "' + script_resource_name + '", "Arn" ] },\n'
else:
template_reformat = '{ "Fn::GetAtt": [ "' + script_resource_name + '", "Arn" ] },'
# append the rewritten template token to the non-template sections before it
match_doc = match_doc + template_reformat
#start the token search & replace process over with the remainder of the document.
working_part = partitions[2]
# append the last working_part (document content after the last {{token}})
if add_whitespace:
match_doc = match_doc + "\n\t\t\"" + working_part + "\"] ] }"
else:
match_doc = match_doc + "\"" + working_part + "\"] ] }"
fw.write(match_doc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment