Monday, December 15, 2014

Python load configurations from a file

Say you have a file deployment.cfg with configurations which are nicely grouped in sections.

[environment]
env = openstack

[envconfig]
image = suhan-daf-agentv4-ubuntu14.04
flavor = m2.small
network = qaa-net
instancePassword = suhan
keyPair = mycloudkey

[nodes]
appserver-mgr2
appserver-wkr2

This is how you should read this configuration file in python.

import ConfigParser
import collections

# Global variables
config = ConfigParser.RawConfigParser(allow_no_value=True)

# Get environment
def get_environment():
config.read('deployment.cfg')
return config.get('environment', 'env')

# Load environment configuration
def get_openstack_image():
config.read('deployment.cfg')
return config.get('envconfig', 'image')

.
.
.

# Nova credentials are loaded from OS environmental variables
def load_server_config():
serverList = []
config.read('deployment.cfg')
orderedDic = collections.OrderedDict(config.items('nodes'))
for node, ip in orderedDic.iteritems():
    serverList.append(node)
print serverList
return serverList

Reference:
[1] http://stackoverflow.com/questions/27483096/python-config-parser-array-sort-according-to-file-content-sequence

No comments:

Post a Comment