How to use sensitive information in your code

Soumya Sen
2 min readSep 13, 2020

As a developer one of the major mistakes I used to do was writing secure information (like passwords, API tokens, keys etc.) inside the code repository. Now the problem with this approach is leakage of secured information. A Lot of times when we push the code to the online repository (ex. GitHub or BitBucket) we push the secured information along with the code. And users who can access your repository can easily get the access of your secured information. Now there are several ways to avoid this. Here I am explaining you one of the simplest ways you can follow. And the method is storing this sensitive information inside your OS environment variables. This way only you will be able to access them and other users who will access your code, if they need they can set the environment variables inside their systems. In this way, you will be able to keep sensitive information safe. Following are the methods to create environment variables inside your operating system.

Mac / Linux -

For the operating systems like Mac or Linux you can follow the following steps-

1. Open the terminal

2. Navigate to the home directory

3. Open the bash profile in text editor. you can use any editor like vi, vim or nano whatever you like. bash_profile is the file where you can store your environment variables. if you don’t have the file, create one.
$ nano ~/.bash_profile
or
$ vi ~/.bash_profile

4. Now declare the environment variable at the top of the file.
export ENV_VAR_NAME=”value”

5. Save the file and exit.

6. Now to verify whether environment variable is properly set, run the following command.
echo $ENV_VAR_NAME
It will display the value of the variable.

7. If you are not getting any value, restart the terminal and run the following command.
$ source ~/.bash_profile

8. Now if you again use the command mentioned in step number 6 you will definitely get the value.

Windows -

  1. From start menu, open the control Panel
  2. Open the System and Security section
  3. Navigate to System
  4. Click on the Advanced system settings link displayed in the left panel
  5. Click on Environment Variables button present at the bottom
  6. Now for this purpose, you can set User variables (System variables need not be updated. In this way you won’t need the admin access as well)
  7. Click on New in User Variable section
  8. Give the environment variable name in the Variable name section and the value in the Variable value section
  9. Click on OK. Now your environment variable is set. You may need to restart your system if you are unable to fetch the variable

Accessing environment variables inside your code -

Python -
import os
os.environ.get(“ENV_VAR_NAME”)

Java -
System.getenv(“ENV_VAR_NAME”)

JavaScript -
process.env.ENV_VAR_NAME

--

--

Soumya Sen

Software Development Engineer in Test | DevOps Engineer | Python Developer