Scripting Best Practices
Writing a script is easy; writing a script that survives production is hard. Follow these standards to ensure your automation remains reliable.
1. Robust Error Handling
Never assume a network call or file operation will succeed. Use try-except-finally blocks.
import boto3
from botocore.exceptions import ClientError
def delete_s3_bucket(bucket_name):
s3 = boto3.client('s3')
try:
s3.delete_bucket(Bucket=bucket_name)
except ClientError as e:
print(f"API Error: {e.response['Error']['Message']}")
except Exception as e:
print(f"Unexpected error: {e}")2. Structured Logging
Stop using print() for production scripts. Use the built-in logging module.
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("Starting backup process...")
logging.error("Failed to connect to database.")3. Configuration Management
Don't hardcode variables. Use environment variables or arguments.
Using os.environ
import os
API_KEY = os.environ.get("MY_APP_API_KEY")Using argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--env", help="Target environment (prod/stage)", required=True)
args = parser.parse_args()
print(f"Running in {args.env}")Checklist for DevOps Scripts
- Does it have basic error handling?
- Are sensitive keys kept out of the code (using env vars)?
- Is there meaningful logging?
- Does it have a help menu (
--help)? - Is the code PEP 8 compliant (readable)?
[!TIP] Use Docstrings Always include a docstring at the top of your function to explain what it does. Future-you (and your teammates) will thank you.