1. import os
  2. import time
  3. import logging
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. def clean_env_vars(env_vars, timeout=5):
  6. """
  7. Cleans environment variables for staging environments with a timeout.
  8. Args:
  9. env_vars (dict): A dictionary of environment variables.
  10. timeout (int): The timeout in seconds for retrieving environment variables.
  11. Returns:
  12. dict: A dictionary containing cleaned environment variables.
  13. Returns an empty dictionary if an error occurs or timeout is reached.
  14. """
  15. cleaned_vars = {}
  16. start_time = time.time()
  17. for key, value in env_vars.items():
  18. try:
  19. # Attempt to retrieve the environment variable
  20. os.environ[key]
  21. # Check if the environment variable is None or empty
  22. if value is None or value == "":
  23. logging.warning(f"Environment variable '{key}' is empty or None. Skipping.")
  24. continue
  25. cleaned_vars[key] = value # Add the variable if it's valid
  26. except Exception as e:
  27. logging.error(f"Error processing environment variable '{key}': {e}")
  28. continue # Skip to the next variable if there's an error
  29. # Check for timeout
  30. if time.time() - start_time > timeout:
  31. logging.warning("Timeout reached during environment variable cleanup.")
  32. return {} # Return an empty dictionary if timeout occurs
  33. return cleaned_vars

Add your comment