vultr.py: fix env var handling (#42659)

pull/43136/head
Yanis Guenane 6 years ago committed by Matt Clay
parent d9f5eb69d5
commit 26be841b23

@ -0,0 +1,2 @@
bugfixes:
- vultr - Do not fail trying to load configuration from ini files if required variables have been set as environment variables.

@ -43,9 +43,9 @@ class Vultr:
# For caching HTTP API responses # For caching HTTP API responses
self.api_cache = dict() self.api_cache = dict()
# Reads the config from vultr.ini
try: try:
config = self.read_ini_config() config = self.read_env_variables()
config.update(self.read_ini_config())
except KeyError: except KeyError:
config = {} config = {}
@ -61,6 +61,9 @@ class Vultr:
"in section '%s' in the ini config file has not an int value: timeout, retries. " "in section '%s' in the ini config file has not an int value: timeout, retries. "
"Error was %s" % (self.module.params.get('api_account'), to_native(e))) "Error was %s" % (self.module.params.get('api_account'), to_native(e)))
if not self.api_config.get('api_key'):
self.module.fail_json(msg="The API key is not speicied. Please refer to the documentation.")
# Common vultr returns # Common vultr returns
self.result['vultr_api'] = { self.result['vultr_api'] = {
'api_account': self.module.params.get('api_account'), 'api_account': self.module.params.get('api_account'),
@ -76,18 +79,18 @@ class Vultr:
'Accept': 'application/json', 'Accept': 'application/json',
} }
def read_ini_config(self): def read_env_variables(self):
ini_group = self.module.params.get('api_account')
keys = ['key', 'timeout', 'retries', 'endpoint'] keys = ['key', 'timeout', 'retries', 'endpoint']
env_conf = {} env_conf = {}
for key in keys: for key in keys:
if 'VULTR_API_%s' % key.upper() not in os.environ: if 'VULTR_API_%s' % key.upper() not in os.environ:
break continue
else: env_conf[key] = os.environ['VULTR_API_%s' % key.upper()]
env_conf[key] = os.environ['VULTR_API_%s' % key.upper()]
else: return env_conf
return env_conf
def read_ini_config(self):
ini_group = self.module.params.get('api_account')
paths = ( paths = (
os.path.join(os.path.expanduser('~'), '.vultr.ini'), os.path.join(os.path.expanduser('~'), '.vultr.ini'),
@ -95,11 +98,13 @@ class Vultr:
) )
if 'VULTR_API_CONFIG' in os.environ: if 'VULTR_API_CONFIG' in os.environ:
paths += (os.path.expanduser(os.environ['VULTR_API_CONFIG']),) paths += (os.path.expanduser(os.environ['VULTR_API_CONFIG']),)
if not any((os.path.exists(c) for c in paths)):
self.module.fail_json(msg="Config file not found. Tried : %s" % ", ".join(paths))
conf = configparser.ConfigParser() conf = configparser.ConfigParser()
conf.read(paths) conf.read(paths)
if not conf._sections.get(ini_group):
return dict()
return dict(conf.items(ini_group)) return dict(conf.items(ini_group))
def fail_json(self, **kwargs): def fail_json(self, **kwargs):

Loading…
Cancel
Save