Skip to content

Instantly share code, notes, and snippets.

@svdgraaf
Last active June 27, 2018 06:27
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 svdgraaf/596667220a82f151d7d1f2d3cc4118ed to your computer and use it in GitHub Desktop.
Save svdgraaf/596667220a82f151d7d1f2d3cc4118ed to your computer and use it in GitHub Desktop.
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