CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium

A developer is working on a Python script that needs to interact with a REST API. The script uses the `requests` library to make HTTP GET requests and processes the JSON response. During development, the developer wants to store the API key securely and avoid hardcoding it in the script. Which of the following is the MOST secure and flexible way to manage the API key in a Python script?

  1. AStore the API key directly in a string variable within the Python script.
  2. BWrite the API key to a plain text file (`api_key.txt`) and read it from the script.
  3. CPrompt the user to enter the API key every time the script runs using `input()`.
  4. DStore the API key in an environment variable and access it using `os.getenv()`.
Show answer & explanation

Correct answer: D. Store the API key in an environment variable and access it using `os.getenv()`.

Storing the API key in an environment variable is the most secure and flexible option among those given. It keeps the key out of the codebase, preventing accidental commits to version control, and allows for easy rotation and different keys for different environments without modifying the script.

Why the other options are wrong

  • A. Hardcoding the API key is insecure as it will be visible in the source code and potentially committed to version control.
  • B. Storing in a plain text file is better than hardcoding but still poses a security risk if the file is not properly secured, shared, or accidentally committed.
  • C. Prompting the user is inconvenient for automated scripts and doesn't scale well for multiple keys or non-interactive environments.

Secure Credential Management (Python)

Secure credential management involves methods to protect sensitive information like API keys, passwords, and tokens from being exposed in source code, version control, or insecure files. Environment variables are a common and effective method.

  • Environment variables separate credentials from code.
  • `os.getenv()` in Python retrieves environment variable values.
  • Avoid hardcoding sensitive data directly in scripts.

Memory trick: Environment Variables Guard All Secrets.

More Automation, Orchestration and Scripting questions