The other day I was asked:
How do I get usernames and passwords into my Python scripts? For example to use with Netmiko, Scrapli or Nornir.
The simple answer to this is the library python-dotenv
.
Whats python-dotenv?
python-dotenv is a library that loads your environment variables from a .env
file. You can then use these environment variables with your Python script using the os
module.
Example
Install
pip install python-dotenv
Create .env
DEVICE_USERNAME=user
DEVICE_PASSWORD=abc123
Create Script with python-dotenv
Below shows you how to use python-dotenv
in your script.
# Import os
import os
from dotenv import load_dotenv
# Load the .env file
load_dotenv()
cisco_device = {
"device_type": "cisco_ios",
"host": "172.29.151.3",
# Get the credentials from the environment variable using os.
"username": os.getenv("DEVICE_USERNAME"),
"password": os.getenv("DEVICE_PASSWORD"),
}
If we were to now print cisco_device
will would see our credentials. Like so:
>>> print(cisco_device)
{
"device_type": "cisco_ios",
"host": "172.29.151.3",
"username": "user",
"password": "abc123",
}
Best Practice
.gitignore
When dealing with source control ensure you are using a .gitignore
file.
This file will contain the various file names that will be ignored when adding your files into source control. Including .env
. This will prevent you from adding your .env
along with your credentials into source control!
.env.example
Because you won't be adding your .env
into source control you need a way to tell folks what environment variables your script(s) will expect. Therefore a common practice is to create an example .env
file with the environment variable names that folks can use as a template. e.g:
$ cat .env.example
DEVICE_USERNAME=<username>
DEVICE_PASSWORD=<password>
Well, that's a wrap from me. I hope you`ve found this useful, and happy Packet Coding!