create a runner python script that loops thorugh aws profiles and sets enviroment variables for credentitals that the python main script can use. UPDATE THE CODE TO USE: ~.aws/profiles instead of .aws/credentials
RUNNER CODE:
import os
import configparser
import subprocess
from pathlib import Path
def run_with_aws_profile(profile_name, main_script_path):
"""
Sets AWS environment variables for a given profile and executes a main script.
"""
aws_credentials_path = Path.home() / ".aws" / "credentials"
if not aws_credentials_path.exists():
print(f"Error: AWS credentials file not found at {aws_credentials_path}")
return
config = configparser.ConfigParser()
config.read(aws_credentials_path)
if profile_name not in config:
print(f"Error: Profile '{profile_name}' not found in {aws_credentials_path}")
return
# Get credentials for the specified profile
profile = config[profile_name]
access_key_id = profile.get('aws_access_key_id')
secret_access_key = profile.get('aws_secret_access_key')
session_token = profile.get('aws_session_token') # Optional
if not access_key_id or not secret_access_key:
print(f"Error: 'aws_access_key_id' or 'aws_secret_access_key' not found for profile '{profile_name}'.")
return
# Create a copy of the current environment and update it with AWS credentials
env = os.environ.copy()
env['AWS_ACCESS_KEY_ID'] = access_key_id
env['AWS_SECRET_ACCESS_KEY'] = secret_access_key
if session_token:
env['AWS_SESSION_TOKEN'] = session_token
else:
# Ensure session token is removed if not present for the current profile
env.pop('AWS_SESSION_TOKEN', None)
print(f"\n--- Running '{main_script_path.name}' with AWS Profile: '{profile_name}' ---")
print(f" AWS_ACCESS_KEY_ID: {access_key_id[:4]}...{access_key_id[-4:]}") # Masking for display
try:
# Execute the main script as a subprocess with the updated environment
result = subprocess.run(
['python', str(main_script_path)],
env=env,
check=True, # Raise an exception if the subprocess returns a non-zero exit code
capture_output=True, # Capture stdout and stderr
text=True # Decode stdout/stderr as text
)
print(" Main script stdout:")
print(result.stdout.strip())
if result.stderr:
print(" Main script stderr:")
print(result.stderr.strip())
except FileNotFoundError:
print(f"Error: Python interpreter or script '{main_script_path}' not found.")
except subprocess.CalledProcessError as e:
print(f"Error: Main script exited with an error (code {e.returncode}).")
print(f" Stdout:\n{e.stdout}")
print(f" Stderr:\n{e.stderr}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if name == "main":
# Define the path to your main script
# Make sure 'main_script.py' is in the same directory as 'aws_runner.py'
# or provide its full path.
main_script_to_run = Path(__file__).parent / "main_script.py"
if not main_script_to_run.exists():
print(f"Error: The 'main_script.py' was not found at '{main_script_to_run}'.")
print("Please ensure it is in the same directory or update the path in 'aws_runner.py'.")
exit(1)
# Path to your AWS credentials file (usually ~/.aws/credentials)
aws_credentials_path = Path.home() / ".aws" / "credentials"
if not aws_credentials_path.exists():
print(f"No AWS credentials file found at {aws_credentials_path}.")
print("Please ensure you have configured your AWS profiles.")
exit(1)
config = configparser.ConfigParser()
config.read(aws_credentials_path)
# Get all profile names (sections in the credentials file)
# The 'DEFAULT' section is often implicit and might not need to be processed
# separately if your code relies on explicit profile names.
# We will iterate through all sections except the 'DEFAULT' if it's there
# and not an actual profile you want to loop over explicitly.
profiles = [s for s in config.sections() if s != 'default'] # Exclude 'default' if you don't explicitly name it
if not profiles:
print("No AWS profiles found in your credentials file. Please configure some profiles.")
exit(1)
print(f"Found AWS profiles: {', '.join(profiles)}")
# Loop through each profile and run the main script
for profile in profiles:
run_with_aws_profile(profile, main_script_to_run)
print("\n--- All profiles processed. ---")