DigitalOcean Referral Badge
Udit Vashisht
Author: Udit Vashisht


Set Passwords and Secret Keys in Environment Variables (Mac/Linux/Windows) - Python Quicktip

  • 3 minutes read
  • 17655 Views
Set Passwords and Secret Keys in Environment Variables (Mac/Linux/Windows) - Python Quicktip

    Table of Contents

Hide Passwords and Secret Keys in Environment Variables

If you are into python , there is a fair chance that you would have contributed to open-source or had your code snippets/projects on Github or BitBucket.Some time your code involves some important credentials like passwords or secret keys etc. like the code for our post on how to send emails using python uses google/app password. You surely do not want to hard code the password in your code and accidentaly push it to a remote repository. Hence, the safest way is to do so is saving your secret keys/password in envirnoment variables. In this post we will learn how to save/hide the passwords, secret keys in environment variables for MacOS, Linux and Windows.

The wrong way

Hard coding your username, passwords or secret keys in your code is wrong way and it exposes you to vulnerability. Have a look at the code below:-

# The wrong way 

user_name = 'my_user_name'
password = 'my_password'

print(user_name, password)

# output

my_user_name my_password

Set Passwords and Secret Keys in Environment Variables on Mac/Linux

To set password and secret keys in environment variable on Mac and Linux. You will need to open and modify .bash_profile . To do that open the terminal on your Mac or Linux and cd to the home directory. (You can read about useful terminal commands of mac here)

user desktop $ cd
user ~ $

Now open the .bash_profile using your favorite editor like nano , vim , sublime text , atom etc. You can read a bit more about the text editors here

user ~ $ nano .bash_profile

The following file will open . You may not have the same text like mine there.

set password secret key in environment variable python.png

Now we need to add our environment variables. For that we will have to write the following code. Remember that there is no whitespace on either side of =.

export USER="my_user_name"
export PASSWORD="my_password"

Press ctrl + x and Y to save the nano file.

Now either restart the terminal or use the following command to effect the changes.

user ~ $ source .bash_profile

Now to use these variables in our python script, we will be needing os module. Have a look at the following code. Here instead of hard coding the username and password like the example above, we have used the environment variables and still the result is same.

import os 

user_name = os.environ.get('USER')
password = os.environ.get('password')

print(user_name, password)

# output

my_user_name my_password

Set Passwords and Secret Keys in Environment Variables on Windows

To set the passwords and secret keys in environment variables on Windows, you will have to open Advance System Setting. You can either type ‘Advanced System Setting’ in search bar or browse to it by right clicking My Computer on desktop-> properties -> Advanced System Setting

set password and secret keys in environment variables python.PNG

Now in Advance System Setting you will have to click on Environment Variables and the following screen will appear.

set password and secret keys in environment variables python -.PNG

Now, here we need to add new user variable. So click on new and add both the variables.

set password and secret keys in environment variables python -!.PNG

Now using the same code as above, we can access the environmental variables.

import os 

user_name = os.environ.get('USER')
password = os.environ.get('password')

print(user_name, password)

# output

my_user_name my_password

If you like this tutorial, please feel free to share.


Related Posts

Difference between "==" and "is" in Python- Quick Tip
By Udit Vashisht

What is the difference between “==” and “is” variable in Python?

If you are new to python you must have seen programmers using “==” and “is”, sometimes even interchangeably. Prima-facie, they look similar and many times you will use any of them. But there is a big difference between them. ...

Read More
Python 3 useful tip-strip()-A useful built-in type.
By Udit Vashisht

Have you ever stumbled across a set of data that contains an extra underscore, character, or word as prefix or suffix, which you want to get rid of?

Python is known for having a resourceful standard library with lots of built-in types that can do a set of tasks in ...

Read More
Nested List to list - Python in just three lines of code
By Udit Vashisht

Nested list to list in Python

Nested list in python can be converted to a flat list in python in just three lines of code. Let us assume that you have a following nested list.

[1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]

Now, the above list ...

Read More
Search
Tags
tech tutorials automate python beautifulsoup web scrapping webscrapping bs4 Strip Python3 programming Pythonanywhere free Online Hosting hindi til github today i learned Windows Installations Installation Learn Python in Hindi Python Tutorials Beginners macos installation guide linux SaralGyaan Saral Gyaan json in python JSON to CSV Convert json to csv python in hindi convert json csv in python remove background python mini projects background removal remove.bg tweepy Django Django tutorials Django for beginners Django Free tutorials Proxy Models User Models AbstractUser UserModel convert json to csv python json to csv python Variables Python cheats Quick tips == and is f string in python f-strings pep-498 formatting in python python f string smtplib python send email with attachment python send email automated emails python python send email gmail automated email sending passwords secrets environment variables if name == main Matplotlib tutorial Matplotlib lists pandas Scatter Plot Time Series Data Live plots Matplotlib Subplots Matplotlib Candlesticks plots Tutorial Logging unittest testing python test Object Oriented Programming Python OOP Database Database Migration Python 3.8 Walrus Operator Data Analysis Pandas Dataframe Pandas Series Dataframe index pandas index python pandas tutorial python pandas python pandas dataframe python f-strings padding how to flatten a nested json nested json to csv json to csv python pandas Pandas Tutorial insert rows pandas pandas append list line charts line plots in python Django proxy user model django custom user model django user model matplotlib marker size pytplot legends scatter plot python pandas python virtual environment virtualenv venv python python venv virtual environment in python python decorators bioinformatics fastafiles Fasta python list append append raspberry pi editor cron crontab Cowin Cowin api python dictionary Python basics dictionary python list list ios development listview navigationview swiftui ios mvvm swift environmentobject property wrapper @State @Environm popup @State ios15 alert automation instagram instaloader texteditor youtubeshorts textfield multi-line star rating reusable swift selenium selenium driver requests-html youtube youtube shorts python automation python tutorial algo trading nifty 50 nifty50 stock list nifty50 telegram telegram bot dictionary in Python how to learn python learn python