Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for AWSHelperFn objects in Tags #1403

Merged
merged 2 commits into from
Jun 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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):
markpeek marked this conversation as resolved.
Show resolved Hide resolved
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