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 environment variable substitution in conf file #1343

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ def get_parsed_args():
default=False, dest='use_forwarder')
parser.add_option('-n', '--disable-dd', action='store_true', default=False,
dest="disable_dd")

# Allow interpolation of environment variables
# This is opt-in initially to avoid recursive interpolation in ConfigParser.
# It could be made opt-out (--disable-env) at the next major version if the community prefers it.
parser.add_option('--enable-env', action='store_true', default=False,
dest="enable_env")

parser.add_option('-v', '--verbose', action='store_true', default=False,
dest='verbose',
help='Print out stacktraces for errors in checks')
Expand All @@ -85,6 +92,7 @@ def get_parsed_args():
'dd_url': None,
'clean': False,
'disable_dd':False,
'enable_env': False,
'use_forwarder': False}), []
return options, args

Expand Down Expand Up @@ -302,12 +310,21 @@ def get_config(parse_args=True, cfg_path=None, options=None):
path = os.path.dirname(path)

config_path = get_config_path(cfg_path, os_name=get_os())
config = ConfigParser.ConfigParser()
if options is not None and options.enable_env:
log.info("Interpolation of environment variables in config is enabled")
config = ConfigParser.ConfigParser(os.environ)
Copy link

@jonhosmer jonhosmer Aug 19, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@delitescere @LeoCavaille
You may want to add ConfigParser.ConfigParser.optionxform = str before config = ConfigParser.ConfigParser(os.environ) so that the keys in os.environ are treated as case sensitive.

For example:

>>> from ConfigParser import ConfigParser
>>> import os
>>> os.environ['XY'] = 'foo'
>>> os.environ['Xy'] = 'bar'
>>> os.environ['xY'] = 'baz'
>>> print '\n'.join(sorted([':'.join((k, v)) for k, v in os.environ.items() if k.lower() == 'xy']))
XY:foo
Xy:baz
xY:bar

>>> cfgp = ConfigParser(os.environ)
>>> print '\n'.join(sorted([':'.join((k, v)) for (k, v) in cfgp.defaults().items() if k.lower() == 'xy']))
xy:foo

>>> ConfigParser.optionxform = str
>>> cfgp_cs = ConfigParser(os.environ)
>>> print '\n'.join(sorted([':'.join((k, v)) for (k, v) in cfgp_cs.defaults().items() if k.lower() == 'xy']))
XY:foo
Xy:baz
xY:bar

>>> assert([(k, v) for (k, v) in cfgp_cs.defaults().items() if k.lower() == 'xy'] == [(k, v) for (k, v) in os.environ.items() if k.lower() == 'xy'])
>>> assert([(k, v) for (k, v) in cfgp.defaults().items() if k.lower() == 'xy'] == [(k, v) for (k, v) in os.environ.items() if k.lower() == 'xy'])
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-43-1f97baeb1e97> in <module>()
----> 1 assert([(k, v) for (k, v) in cfgp.defaults().items() if k.lower() == 'xy'] == [(k, v) for (k, v) in os.environ.items() if k.lower() == 'xy'])

AssertionError:

else:
config = ConfigParser.ConfigParser()

config.readfp(skip_leading_wsp(open(config_path)))

# bulk import
for option in config.options('Main'):
agentConfig[option] = config.get('Main', option)
try:
for option in config.options('Main'):
agentConfig[option] = config.get('Main', option)
except ConfigParser.InterpolationMissingOptionError:
sys.stderr.write("The configuration file contains invalid variable substitution. If you want to use environment variables, use the --enable-env option\n")
sys.exit(3)

#
# Core config
Expand Down
39 changes: 39 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import tempfile

from config import get_config
from optparse import Values
from ConfigParser import InterpolationMissingOptionError

from util import PidFile, is_valid_hostname, Platform, windows_friendly_colon_split

Expand All @@ -19,6 +21,43 @@ def testWhiteSpaceConfig(self):
self.assertEquals(agentConfig["graphite_listen_port"], 17126)
self.assertTrue("statsd_metric_namespace" in agentConfig)

def testEnvInterpolationDisabled(self):
os.environ["BAR"] = "bar"
test_options = Values({
'autorestart': False,
'dd_url': None,
'clean': False,
'disable_dd':False,
'enable_env': False,
'use_forwarder': False
})
with tempfile.NamedTemporaryFile() as conf_file:
with open(conf_file.name, "w") as f:
f.write("[Main]\n")
f.write("dd_url:\n")
f.write("api_key:\n")
f.write("tags: foo:%(BAR)s\n")
self.assertRaises(SystemExit, get_config, parse_args=False, cfg_path=conf_file.name, options=test_options)

def testEnvInterpolationEnabled(self):
os.environ["BAR"] = "bar"
test_options = Values({
'autorestart': False,
'dd_url': None,
'clean': False,
'disable_dd':False,
'enable_env': True,
'use_forwarder': False
})
with tempfile.NamedTemporaryFile() as conf_file:
with open(conf_file.name, "w") as f:
f.write("[Main]\n")
f.write("dd_url:\n")
f.write("api_key:\n")
f.write("tags: foo:%(BAR)s\n")
agentConfig = get_config(parse_args=False, cfg_path=conf_file.name, options=test_options)
self.assertEqual(agentConfig["tags"], "foo:bar")

def testGoodPidFie(self):
"""Verify that the pid file succeeds and fails appropriately"""

Expand Down