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

Some helper functions to work with boto3 #15183

Merged
merged 1 commit into from
Mar 28, 2016
Merged
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
92 changes: 92 additions & 0 deletions lib/ansible/module_utils/ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,95 @@ def camel_to_snake(name):
snake_dict[camel_to_snake(k)] = v

return snake_dict


def ansible_dict_to_boto3_filter_list(filters_dict):

""" Convert an Ansible dict of filters to list of dicts that boto3 can use
Args:
filters_dict (dict): Dict of AWS filters.
Basic Usage:
>>> filters = {'some-aws-id', 'i-01234567'}
>>> ansible_dict_to_boto3_filter_list(filters)
{
'some-aws-id': 'i-01234567'
}
Returns:
List: List of AWS filters and their values
[
{
'Name': 'some-aws-id',
'Values': [
'i-01234567',
]
}
]
"""

filters_list = []
for k,v in filters_dict.iteritems():
filter_dict = {'Name': k}
if isinstance(v, basestring):
filter_dict['Values'] = [v]
else:
filter_dict['Values'] = v

filters_list.append(filter_dict)

return filters_list


def boto3_tag_list_to_ansible_dict(tags_list):

""" Convert a boto3 list of resource tags to a flat dict of key:value pairs
Args:
tags_list (list): List of dicts representing AWS tags.
Basic Usage:
>>> tags_list = [{'Key': 'MyTagKey', 'Value': 'MyTagValue'}]
>>> boto3_tag_list_to_ansible_dict(tags_list)
[
{
'Key': 'MyTagKey',
'Value': 'MyTagValue'
}
]
Returns:
Dict: Dict of key:value pairs representing AWS tags
{
'MyTagKey': 'MyTagValue',
}
"""

tags_dict = {}
for tag in tags_list:
tags_dict[tag['Key']] = tag['Value']

return tags_dict


def ansible_dict_to_boto3_tag_list(tags_dict):

""" Convert a flat dict of key:value pairs representing AWS resource tags to a boto3 list of dicts
Args:
tags_dict (dict): Dict representing AWS resource tags.
Basic Usage:
>>> tags_dict = {'MyTagKey': 'MyTagValue'}
>>> ansible_dict_to_boto3_tag_list(tags_dict)
{
'MyTagKey': 'MyTagValue'
}
Returns:
List: List of dicts containing tag keys and values
[
{
'Key': 'MyTagKey',
'Value': 'MyTagValue'
}
]
"""

tags_list = []
for k,v in tags_dict.iteritems():
tags_list.append({'Key': k, 'Value': v})

return tags_list