Search code examples
pythonpasswordsfabric

Python Fabric load config from separate file


I am use python fabric with all configuration in one .fab file.
How can I put sensitive data as password to separate file and then import/load to fab main file?


Solution

  • Define a simple function within your fabfile.py to read your passwords out of a separate file. Something along the lines of:

    def new_getpass(username):
        with open("/etc/passwd", "r") as f:
            for entry in [l.split(":") for l in f.readlines()]:
                if entry[0] == username:
                    return entry
        return None
    

    This will return None in the event that the username cannot be found and the entire user's record as a list in the event the user is found.

    Obviously my example is getting its data from /etc/passwd but you can easily adapt this basic functionality to your own file:

    credentials.dat

    database1|abcd1234
    database2|zyxw0987
    

    And then the above code modified to use this file like this, with the slight variation to return only the password (since we know the database name):

    def getpass(database):
        with open("credentials.dat", "r") as f:
            for entry in [l.split("|") for l in f.readlines()]:
                if entry[0] == username:
                    return entry[1]
        return None
    

    While not as simple as an import, it provides you flexibility to be able to use plaintext files to store your credentials in.