forked from caktus/aws-web-stacks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtags.py
65 lines (48 loc) · 2.12 KB
/
tags.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
from troposphere import AWS_STACK_NAME, Ref, Tags, autoscaling
from .template import template
common_tags = Tags({"aws-web-stacks:stack-name": Ref(AWS_STACK_NAME)})
def tags_types_of_resource(resource):
"""
return an iterable of the acceptable types for
the Tags property on this resource.
"""
tags_type = resource.props["Tags"][0]
if isinstance(tags_type, tuple):
return tags_type
return [tags_type]
def tags_type_of_resource(resource):
"""
Return the type that this resource expects its Tags
property to be. E.g. list, Tags, autoscaling.Tags.
If there are multiple possibilities, returns the first.
"""
return tags_types_of_resource(resource)[0]
def add_empty_tags(resource):
# Put an empty tags prop on this resource, of the right type.
tags_type = tags_type_of_resource(resource)
resource.Tags = tags_type()
def add_common_tags(template):
for resource in template.resources.values():
if "Tags" not in resource.propnames:
continue
# WARNING: adding two Tags() objects together modifies and returns
# the second object, giving it the concatenation of the
# tags from the first and second objects, in that order.
if not hasattr(resource, "Tags"):
# resource.Tags = common_tags
# return
add_empty_tags(resource)
if isinstance(resource.Tags, (Tags, autoscaling.Tags)):
resource.Tags = common_tags + resource.Tags
elif isinstance(resource.Tags, dict):
tags = common_tags.to_dict() # actually returns a list. Sigh.
tags = dict(tags) # convert to a dict.
tags.update(**resource.Tags) # override with any tags from this resource.
resource.Tags = tags # and set the result on the resource again.
elif isinstance(resource.Tags, list):
tags = tags_type_of_resource(resource)()
tags.tags = resource.Tags
resource.Tags = common_tags + tags
else:
raise TypeError("Unknown type %s for Tags on %s" % (type(resource.Tags), resource))
add_common_tags(template)