-
Notifications
You must be signed in to change notification settings - Fork 17
/
deploy_api_function.py
executable file
·93 lines (72 loc) · 2.87 KB
/
deploy_api_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python
import yaml
import sys
import boto3
import os
from yaml import ScalarNode, SequenceNode
from six import string_types
from botocore.exceptions import ClientError
# This helper copied almost entirely from
# https://github.com/awslabs/serverless-application-model/blob/master/samtranslator/yaml_helper.py
def yaml_parse(yamlstr):
"""Parse a yaml string"""
yaml.SafeLoader.add_multi_constructor(
"!", intrinsics_multi_constructor)
return yaml.safe_load(yamlstr)
def intrinsics_multi_constructor(loader, tag_prefix, node):
# Get the actual tag name excluding the first exclamation
tag = node.tag[1:]
# Some intrinsic functions doesn't support prefix "Fn::"
prefix = "Fn::"
if tag in ["Ref", "Condition"]:
prefix = ""
cfntag = prefix + tag
if tag == "GetAtt" and isinstance(node.value, string_types):
# ShortHand notation for !GetAtt accepts Resource.Attribute format
# while the standard notation is to use an array
# [Resource, Attribute]. Convert shorthand to standard format
value = node.value.split(".", 1)
elif isinstance(node, ScalarNode):
# Value of this node is scalar
value = loader.construct_scalar(node)
elif isinstance(node, SequenceNode):
# Value of this node is an array (Ex: [1,2])
value = loader.construct_sequence(node)
else:
# Value of this node is an mapping (ex: {foo: bar})
value = loader.construct_mapping(node)
return {cfntag: value}
def main():
with open('api-template.yaml', 'r') as f:
tempalte = yaml_parse(f)
args = sys.argv
if not args[1:2]:
print('[Error]Function name was not set as an argument')
sys.exit(1)
function_resource_id = args[1]
function = tempalte['Resources'].get(function_resource_id)
if not function or function.get('Type') != 'AWS::Serverless::Function':
print('[Error]The Function does not exists')
sys.exit(1)
try:
stack_name = os.environ['ALIS_APP_ID'] + 'api'
cfn = boto3.client('cloudformation')
stack = cfn.describe_stack_resource(
StackName=stack_name,
LogicalResourceId=function_resource_id
)
function_name = stack['StackResourceDetail']['PhysicalResourceId']
zip_file = open(function['Properties']['CodeUri'], 'rb')
zip_file_contents = zip_file.read()
lambda_client = boto3.client('lambda')
lambda_client.update_function_code(
FunctionName=function_name,
ZipFile=zip_file_contents
)
print('[Success]'+function_resource_id+' function was uploaded')
sys.exit(0)
except ClientError as e:
print(e)
sys.exit(1)
if __name__ == '__main__':
main()