Skip to content

Instantly share code, notes, and snippets.

@svdgraaf

svdgraaf/parse.py

Last active Jun 27, 2018
Embed
What would you like to do?
Embed lambda functions in cloudformation
# pip install pyminifier
# pip install yaml
import subprocess
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
import yaml
# ignore all CF specific tags, and load them as-is
def get_attribute(loader, tag_suffix, node):
return {"Fn::GetAtt": [node.value.split('.')[0], '.'.join(node.value.split('.')[1:])]}
yaml.add_multi_constructor('!GetAtt', get_attribute)
def minimy_file(path, cwd):
proc = subprocess.Popen(
# ['pyminifier', '-O', path], cwd=cwd, stdout=subprocess.PIPE)
['pyminifier', path], cwd=cwd, stdout=subprocess.PIPE)
data, err = proc.communicate()
assert err is None
return data
template = None
with open("template.yml", 'r') as stream:
try:
template = yaml.load(stream)
except yaml.YAMLError as exc:
print(exc)
sys.exit(1)
# find all lambda functions, and inject the template
for logicalId, resource in template['Resources'].items():
if resource['Type'] == 'AWS::Lambda::Function':
if 'Source' in resource['Properties']:
filename = "%s/%s" % (current_dir, resource['Properties']['Source'])
source = minimy_file(filename, current_dir)
del template['Resources'][logicalId]['Properties']['Source']
template['Resources'][logicalId]['Properties']['Code'] = {
'ZipFile': source.decode()
}
print(yaml.dump(template))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment