import os
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def clean_env_vars(env_vars, timeout=5):
"""
Cleans environment variables for staging environments with a timeout.
Args:
env_vars (dict): A dictionary of environment variables.
timeout (int): The timeout in seconds for retrieving environment variables.
Returns:
dict: A dictionary containing cleaned environment variables.
Returns an empty dictionary if an error occurs or timeout is reached.
"""
cleaned_vars = {}
start_time = time.time()
for key, value in env_vars.items():
try:
# Attempt to retrieve the environment variable
os.environ[key]
# Check if the environment variable is None or empty
if value is None or value == "":
logging.warning(f"Environment variable '{key}' is empty or None. Skipping.")
continue
cleaned_vars[key] = value # Add the variable if it's valid
except Exception as e:
logging.error(f"Error processing environment variable '{key}': {e}")
continue # Skip to the next variable if there's an error
# Check for timeout
if time.time() - start_time > timeout:
logging.warning("Timeout reached during environment variable cleanup.")
return {} # Return an empty dictionary if timeout occurs
return cleaned_vars
Add your comment