Hiding Secrets from GitHub (or using ConfigParser)

As I get into the habit of using git and github for versioning I need to make sure that I hide personal settings and passwords. To do this I use ConfigParser in Python. It’s pretty easy.

Configuration is Fun
Configuration is Fun

Creating the Configuration File

First create a ‘config.ini’ file in your code directory. I generally use a text editor or program such as Geany to do this. Section heading are enclosed in square brackets ([]) and parameters are stored in “key = value” pairs.

[Section Heading]
setting name 1 =
setting name 2 = thisismypassword

To create the file programmatically you can use code such as:

import ConfigParser

parser = ConfigParser.SafeConfigParser()
parser.add_section('Section Heading')
parser.set('Section Heading', 'Setting Name 1' , '')
parser.set('Section Heading', 'Setting Name 2' , 'thisismypassword')

with open('config.ini', 'wb') as configfile:

Reading the Configuration File

I typically read the configuration file in the ‘__init__’ method of the class I am building. Alternatively, you can do this at the start of your function or script. The code is as follows:

import ConfigParser

parser = ConfigParser.SafeConfigParser()

ip = parser.get('Section Heading', 'Setting Name 1')
password = parser.get('Section Heading', 'Setting Name 2')

Ignoring the Configuration File

Finally to prevent the configuration file from being uploaded to github add a ‘.gitignore’ file to the directory with a line saying ‘*.ini’.

One thought on “Hiding Secrets from GitHub (or using ConfigParser)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s