Whether you are building a data pipeline in Airflow or a simple AI bot, you should never hard-code your API keys directly in your Python script. If you push that code to a public repository, hackers will find it in seconds using automated scanners.
Here is the professional way to handle secrets using Environment Variables and .env files.
1. The Tool: python-dotenv
The industry standard for managing local secrets is a library called python-dotenv. It allows you to store your keys in a separate file that never gets uploaded to the internet.
Install it via terminal:
2. Create your .env File
In your project’s root folder, create a new file named exactly .env. Inside, add your secrets like this:
3. Access Secrets in Python
Now, you can load these variables into your script without ever typing the actual key in your code.
4. The Most Important Step: .gitignore
This is where the "Security" part happens. You must tell Git to ignore your .env file so it never leaves your computer.
Create a file named .gitignore and add this line:
Why this is a "DevSecOps" Win:
Security: Your keys stay on your machine.
Flexibility: You can use different keys for "Development" and "Production" without changing a single line of code.
Collaboration: Your teammates can create their own local
.envfiles with their own credentials.

No comments:
Post a Comment