Linux and Nagios‎ > ‎

Storing Credentials for Scripts Outside of Version Control (Environment Variables Example)

posted 5 Sept 2020, 00:48 by Tristan Self
So you have a Python script (for example), and you need to store some access credentials for an API it accesses (for example), now you could put the username and password in the script. There's lots of reasons not to do this however, a key one being that if you are using a version control system like GIT or SVN to store your script files in, it would end up within this, where it could find its way to people who you don't want to see your access credentials. The same is true for API keys and other such access credentials that you want to keep secret.

There's a few option for how to do this, you can store the credentials in a file or as environment variables, or use a method such a Vault system (e.g. Hashicorp Vault) amongst others. In this example, i'll be showing how to put environment variables into your script's environment (manually), then a simple script to show how you can read these into your script at runtime.

You can also do things like hashing the values stored in the environment variables to make them less easy to "see", i.e. not storing them in plain text for example.

So let's say we're going to have a script that is used for accessing an API, but you don't want the username and password stored in the script.

So first we create ourselves the environment variables and populate with a value.

export API_USER="bob"
export API_PASSWORD="rosebud"

If you run a "env" you'll now see them listed within the environment.

So let's create a Python script called "env-test.py" and put the following in it.

import os

# Get environment variables from nevironment.
strUsername = os.getenv('API_USER')
strPassword = os.environ.get('API_PASSWORD')

print()
print(strUsername)
print(strPassword)

To run the script:

python3 env-test.py

And we see this output:

root@testmachine:~/scratch# python3 env-test.py
bob
rosebud

A very simple example, but this illustrates the point, you could now store the env-test.py script within GIT or other version control repository without a concern that you'd be exposing credentials.

Additional Information
  • https://able.bio/rhett/how-to-set-and-get-environment-variables-in-python--274rgt5
Comments