"""Lambda snowflake-refresh function module.""" import tempfile import os import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration from lambdacommon.common_config import logger import config from src.logic import snowflake from src.connectors.boto_clients import secrets_manager_client as sm if config.SENTRY_DSN: sentry_sdk.init( dsn=config.SENTRY_DSN, environment=config.ENVIRONMENT, integrations=[AwsLambdaIntegration(timeout_warning=True)] ) def write_key_to_file(private_key_content): """Write the private key to a temporary file and return its path.""" temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.p8') temp_file.write(private_key_content.encode('utf-8')) temp_file.close() return temp_file.name def get_snowflake_credentials(db_name): """Fetch Snowflake credentials from AWS Secrets Manager.""" prefix = config.SNOWFLAKE_SECRET_PREFIX secrets = { 'user': f'{prefix}{db_name}/SNOWFLAKE_USER', 'private_key': f'{prefix}{db_name}/SNOWFLAKE_PRIVATE_KEY', 'key_pwd': f'{prefix}{db_name}/SNOWFLAKE_PRIVATE_KEY_PASSPHRASE' } try: return { key: sm.get_secret_value(SecretId=value)['SecretString'] for key, value in secrets.items() } except Exception as e: logger.error(f'Failed to retrieve secrets for {db_name}: {str(e)}') raise def handler(event, context): """Lambda entry point.""" try: db_name = event.get('db_name') if not db_name: logger.error("Missing 'db_name' in event payload") raise ValueError("Missing 'db_name' in event payload") scripts_dir = os.path.join(config.SCRIPT_BASE_DIR, db_name) logger.info(f'Fetching credentials for {db_name}') credentials = get_snowflake_credentials(db_name) private_key_file = write_key_to_file(credentials['private_key']) if os.path.exists(scripts_dir) and os.listdir(scripts_dir): logger.info(f'Running SQL scripts from {scripts_dir} in order') scripts_run = snowflake.run_scripts( scripts_dir, credentials['user'], private_key_file, credentials['key_pwd'] ) else: logger.info( f'No scripts found in {scripts_dir}, skipping script execution' ) scripts_run = 0 return { 'scripts_run': scripts_run } except Exception as e: logger.exception(str(e)) raise e