G
GuideDevOps
Lesson 14 of 15

Python Best Practices & Security

Part of the Python for DevOps tutorial series.

In a DevOps environment, Python scripts often have elevated permissions. Writing clean, secure, and maintainable code is not just a preference; it's a security requirement.

1. Code Style (PEP 8)

PEP 8 is the official style guide for Python. It makes code readable and consistent across teams.

Linting with Ruff

Ruff is the modern, extremely fast linter and formatter that's becoming the industry standard.

Action:

pip install ruff
ruff check .

Result:

Checking 10 files...
src/deploy.py:5:10: F401 `os` imported but unused
Found 1 error.

2. Managing Secrets Safely

NEVER hardcode credentials in your scripts. Use environment variables.

Using python-dotenv

This tool loads variables from a .env file into os.environ.

Action:

import os
from dotenv import load_dotenv
 
load_dotenv() # Load from .env
 
API_KEY = os.getenv("GITHUB_TOKEN")
print(f"Token length: {len(API_KEY)}")

Result:

Token length: 40

3. Handling Configuration

For larger DevOps tools, use YAML or JSON for configuration.

Best Practice Example:

import yaml
 
with open('config.yaml', 'r') as f:
    config = yaml.safe_load(f)
 
# safe_load is critical to prevent arbitrary code execution!

4. Error Handling and Logging

Don't use print for debugging in production scripts. Use the logging module.

Action:

import logging
 
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
logger.info("Starting deployment...")
try:
    # deploy code...
    pass
except Exception as e:
    logger.error(f"Failed: {e}")

Result:

INFO:__main__:Starting deployment...

5. Security: Input Validation

When taking inputs from users or APIs, always validate them to prevent command injection.

Bad:

import os
user_input = "file.txt; rm -rf /"
os.system(f"ls {user_input}") # DANGEROUS!

Good:

import subprocess
user_input = "file.txt"
subprocess.run(["ls", user_input]) # SAFE

Summary: The DevOps Python Checklist

  1. Always use a virtual environment.
  2. Never hardcode secrets (use .env or Vault).
  3. Use Ruff for linting.
  4. Use logging instead of print.
  5. Write Unit Tests for your automation logic.