Skip to content

Commit

Permalink
Allow for AWSHelperFn objects in Tags (#1403)
Browse files Browse the repository at this point in the history
  • Loading branch information
John Titus authored and markpeek committed Jun 4, 2019
1 parent 66cea00 commit 86435bf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
15 changes: 14 additions & 1 deletion tests/test_tags.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import unittest
from troposphere import Sub, Tags
from troposphere import If, Sub, Tag, Tags
from troposphere.autoscaling import Tags as ASTags


Expand All @@ -15,6 +15,19 @@ def test_TagAddition(self):
]
self.assertEqual(tags.to_dict(), result)

def test_TagConditional(self):
tags = Tags(
{'foo': 'foo'},
If('MyCondition', Tag('bar', 'bar'), Tag('baz', 'baz'))
)
result = [
{"Fn::If": ["MyCondition",
{"Key": "bar", "Value": "bar"},
{"Key": "baz", "Value": "baz"}]},
{'Value': 'foo', 'Key': 'foo'},
]
self.assertEqual(tags.to_dict(), result)

def test_ASTagAddition(self):
tags = ASTags(foo=('fooval', True))
tags += ASTags(bar=('barval', False))
Expand Down
26 changes: 17 additions & 9 deletions troposphere/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,25 +525,33 @@ def __init__(self, data):
self.data = {'Fn::ImportValue': data}


class Tag(AWSHelperFn):
def __init__(self, k, v):
self.data = {'Key': k, 'Value': v, }


class Tags(AWSHelperFn):
def __init__(self, *args, **kwargs):
self.tags = []
if not args:
# Assume kwargs variant
tag_dict = kwargs
else:
if len(args) != 1:
raise(TypeError, "Multiple non-kwargs passed to Tags")

# Validate single argument passed in is a dict
if not isinstance(args[0], dict):
raise(TypeError, "Tags needs to be either kwargs or dict")
tag_dict = args[0]
tag_dict = {}
for arg in args:
# Validate argument passed in is an AWSHelperFn or...
if isinstance(arg, AWSHelperFn):
self.tags.append(arg)
# Validate argument passed in is a dict
elif isinstance(arg, dict):
tag_dict.update(arg)
else:
raise(TypeError, "Tags needs to be either kwargs, "
"dict, or AWSHelperFn")

def add_tag(tag_list, k, v):
tag_list.append({'Key': k, 'Value': v, })

self.tags = []

# Detect and handle non-string Tag items which do not sort in Python3
if all(isinstance(k, basestring) for k in tag_dict):
for k, v in sorted(tag_dict.items()):
Expand Down

0 comments on commit 86435bf

Please sign in to comment.