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.

env = openstack

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


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():'deployment.cfg')
return config.get('environment', 'env')

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


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