From 4f3c863b42b0c9e0c8b03089621b43247ea9f17a Mon Sep 17 00:00:00 2001 From: Rene Moser Date: Wed, 12 Aug 2015 22:16:33 +0200 Subject: [PATCH] cloudstack: refactor get_result() * A commen dict of keys has been defined, which we look in results returned from the API. * self.returns dict can be use in subclass to extend this dict. * Optionally the key name can be replaced with a new key name, often used to make the return keys identical to the arguments passed. * Use new style class --- lib/ansible/module_utils/cloudstack.py | 42 +++++++++++++++++++------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/lib/ansible/module_utils/cloudstack.py b/lib/ansible/module_utils/cloudstack.py index 04f82d0742b..4a994434a4d 100644 --- a/lib/ansible/module_utils/cloudstack.py +++ b/lib/ansible/module_utils/cloudstack.py @@ -35,7 +35,7 @@ except ImportError: has_lib_cs = False -class AnsibleCloudStack: +class AnsibleCloudStack(object): def __init__(self, module): if not has_lib_cs: @@ -45,6 +45,22 @@ class AnsibleCloudStack: 'changed': False, } + # Common returns, will be merged with self.returns + # search_for_key: replace_with_key + self.common_returns = { + 'id': 'id', + 'name': 'name', + 'created': 'created', + 'zonename': 'zone', + 'state': 'state', + 'project': 'project', + 'account': 'account', + 'domain': 'domain', + } + + # Init returns dict for use in subclasses + self.returns = {} + self.module = module self._connect() @@ -370,14 +386,18 @@ class AnsibleCloudStack: def get_result(self, resource): if resource: - if 'id' in resource: - self.result['id'] = resource['id'] - if 'project' in resource: - self.result['project'] = resource['project'] - if 'domain' in resource: - self.result['domain'] = resource['domain'] - if 'account' in resource: - self.result['account'] = resource['account'] - if 'zonename' in resource: - self.result['zone'] = resource['zonename'] + returns = self.common_returns.copy() + returns.update(self.returns) + for search_key, return_key in returns.iteritems(): + if search_key in resource: + self.result[return_key] = resource[search_key] + + # Special handling for tags + if 'tags' in resource: + self.result['tags'] = [] + for tag in resource['tags']: + result_tag = {} + result_tag['key'] = tag['key'] + result_tag['value'] = tag['value'] + self.result['tags'].append(result_tag) return self.result