inventory/vultr: Few minor improvements (#44622)

pull/44636/merge
Yanis Guenane 6 years ago committed by René Moser
parent 34c582287a
commit 9869f378fd

@ -31,7 +31,7 @@ DOCUMENTATION = r'''
env:
- name: VULTR_API_KEY
hostname:
description: Field to match the hostname
description: Field to match the hostname. Note v4_main_ip corresponds to the main_ip field returned from the API and name to label.
type: string
default: v4_main_ip
choices:
@ -54,7 +54,7 @@ from ansible.plugins.inventory import BaseInventoryPlugin
from ansible.module_utils.six.moves import configparser
from ansible.module_utils.urls import open_url
from ansible.module_utils._text import to_native
from ansible.module_utils.vultr import Vultr, VULTR_USER_AGENT
from ansible.module_utils.vultr import Vultr, VULTR_API_ENDPOINT, VULTR_USER_AGENT
SCHEMA = {
@ -105,7 +105,7 @@ def _load_conf(path, account):
def _retrieve_servers(api_key):
api_url = 'https://api.vultr.com/v1/server/list'
api_url = '%s/v1/server/list' % VULTR_API_ENDPOINT
try:
response = open_url(
@ -113,11 +113,9 @@ def _retrieve_servers(api_key):
http_agent=VULTR_USER_AGENT,
)
servers_list = json.loads(response.read())
if not servers_list:
return []
return [server for id, server in servers_list.items()]
except ValueError as e:
return servers_list.values() if servers_list else []
except ValueError:
raise AnsibleError("Incorrect JSON payload")
except Exception as e:
raise AnsibleError("Error while fetching %s: %s" % (api_url, to_native(e)))
@ -130,16 +128,13 @@ class InventoryModule(BaseInventoryPlugin):
super(InventoryModule, self).parse(inventory, loader, path)
self._read_config_data(path=path)
api_account = self.get_option('api_account') or 'default'
conf = _load_conf(self.get_option('api_config'), api_account)
conf = _load_conf(self.get_option('api_config'), self.get_option('api_account'))
try:
api_key = self.get_option('api_key') or conf.get('key')
except Exception as e:
raise AnsibleError('Could not find an API key. Check the configuration files.')
hostname_preference = self.get_option('hostname') or 'v4_main_ip'
except Exception:
raise AnsibleError('Could not find an API key. Check inventory file and Vultr configuration files.')
hostname_preference = self.get_option('hostname')
for server in _retrieve_servers(api_key):
server = Vultr.normalize_result(server, SCHEMA)
for group in ['region', 'os']:
@ -148,4 +143,6 @@ class InventoryModule(BaseInventoryPlugin):
for attribute, value in server.items():
self.inventory.set_variable(server['name'], attribute, value)
if hostname_preference != 'name':
self.inventory.set_variable(server['name'], 'ansible_host', server[hostname_preference])

Loading…
Cancel
Save