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
$ vi ~/.bash_profile
4. Now declare the environment variable at the top of the file.
5. Save the file and exit.
6. Now to verify whether environment variable is properly set, run the following command.
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.
- From start menu, open the control Panel
- Open the System and Security section
- Navigate to System
- Click on the Advanced system settings link displayed in the left panel
- Click on Environment Variables button present at the bottom
- 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)
- Click on New in User Variable section
- Give the environment variable name in the Variable name section and the value in the Variable value section
- 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 -