Securely Managing Sensitive Information

Aug 15, 2024

Lecture Notes: Using Environment Files for Sensitive Information

Introduction

  • Many online lessons demonstrate hardcoding sensitive information (e.g., API keys, passwords) directly in scripts.
  • Directly including sensitive information is risky and should be avoided in actual projects.
  • This lecture explains how to use environment files to securely store and access sensitive information in your projects.

Installing Required Package

  • Install the necessary package using pip:
    pip install python-dotenv
    
  • This package allows you to load environment variables into your script.

Setting Up the Environment File

  • Create a new file named .env.
    • You can include a prefix if managing multiple environments.
  • Add sensitive information to the .env file:
    • Example format:
      API_KEY=abc123LOL
      USERNAME=Luigi123
      PASSWORD=MarioBro123
      
    • No quotation marks are needed around values.

Loading Environment Variables in Python

  • Import necessary modules:
    from dotenv import load_dotenv
    import os
    
  • Load the environment using load_dotenv().
  • Retrieve variables using os.getenv():
    username = os.getenv('USERNAME')
    password = os.getenv('PASSWORD')
    
  • Print or use these variables as needed.

Using Environment Variables in Code

  • Demonstration of accessing an API key:
    api_key = os.getenv('API_KEY')
    result = api_call_function(api_key)
    
  • Print results to verify retrieval:
    print(result)
    

Benefits of Using .env Files

  • Easy update mechanism: change values in .env without modifying code.
  • Enhances security by keeping sensitive data out of scripts and version control.

Important Considerations

  • Add .env to your .gitignore:
    • Prevents accidental sharing of sensitive information.
  • Collaboration Challenge: Manually communicate changes with team members if not using a private repository.

Using Templates for .env Files

  • Create a template .env file for collaborators:
    TEMPLATE.env
    
  • Include placeholders without actual values to guide others in setting up their environment.

Conclusion

  • Environment files are a secure way to manage sensitive information in projects.
  • Always ensure .env is excluded from public repositories.
  • Use templates to communicate necessary environment configurations to other developers.

Thank you for attending the lecture. See you in the next session!