Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Created November 1, 2024 11:56
Show Gist options
  • Save huynhbaoan/e527a35cb3c0e9003e9fa230da5bf49d to your computer and use it in GitHub Desktop.
Save huynhbaoan/e527a35cb3c0e9003e9fa230da5bf49d to your computer and use it in GitHub Desktop.
def verify_authentication(credentials: Dict[str, str]) -> bool:
"""Verify the authentication by calling GetCallerIdentity using temporary credentials."""
try:
# Create a session using temporary SSO credentials
session = boto3.Session(
aws_access_key_id=credentials['AccessKeyId'],
aws_secret_access_key=credentials['SecretAccessKey'],
aws_session_token=credentials['SessionToken']
)
sts_client = session.client('sts')
# Call to confirm if the token is valid
identity = sts_client.get_caller_identity()
print(f"Authenticated as: {identity['Arn']}")
return True
except Exception as e:
print(f"Failed to verify authentication: {str(e)}")
return False
def main():
parser = argparse.ArgumentParser(description='AWS SAML Authentication and Role Switching Tool')
parser.add_argument('--env', nargs='+', choices=['np', 'preprod', 'prod'],
required=True, help='Service environments to authenticate (e.g., np preprod)')
parser.add_argument('--csv', required=True,
help='Path to CSV file containing account mappings')
parser.add_argument('--username', '-u', help='Username (optional, defaults to $USER)')
parser.add_argument('--quiet', '-q', action='store_true', help='Minimize output')
parser.add_argument('--mfa-token', help='MFA Token (optional)')
args = parser.parse_args()
print("CDNXHG HIS AWS CLI Access Tool")
print("===========================\n")
# Map environment arguments to target environments
selected_envs = {ENV_CONFIGS[env]['environment'] for env in args.env}
# Load and filter CSV content based on selected environments
print("\nLoading and validating CSV content...")
account_mappings = load_and_filter_csv(args.csv, selected_envs)
# Get username and prompt for password
username = args.username or os.environ.get('USER') or input("Enter username: ")
password = getpass.getpass("Password: ")
mfa_token = args.mfa_token or input("MFA Token (Optional): [Press enter to skip] ")
# Authenticate and process each environment
for env_code in args.env:
env_config = ENV_CONFIGS[env_code]
env_name = env_config['environment']
print(f"\nAuthenticating to {env_config['account_name']} for environment '{env_name}'")
# Initial authentication
session, response = get_session(env_config['account_name'], env_config['account_id'], args.quiet)
saml_response = authenticate(session, username, password, mfa_token, args.quiet)
# Parse the SAML response to obtain temporary credentials (assume these are obtained from `authenticate`)
credentials = {
'AccessKeyId': 'temporary_access_key',
'SecretAccessKey': 'temporary_secret_key',
'SessionToken': 'temporary_session_token'
} # Replace with actual parsing of SAML response
# Verify authentication using the temporary credentials
if not verify_authentication(credentials):
sys.exit("Authentication verification failed. Please check your credentials and try again.")
# Write verified service account credentials to the AWS credentials file
write_credentials(env_config['account_name'], credentials)
print(f"Service account credentials for {env_config['account_name']} saved successfully.")
print(f"\nSwitching roles for environment '{env_name}'")
for account in account_mappings.get(env_name, []):
try:
print(f"\nSwitching to role in account: {account['account_name']} ({account['account_id']})")
credentials = switch_role(
source_profile=env_config['account_name'],
target_role_arn=account['switch_role_arn'],
session_name=f"{username}-session",
env_config=env_config # Pass env_config for re-authentication if needed
)
write_credentials(account['account_name'], credentials)
print(f"Successfully switched to role in {account['account_name']}")
print(f"To use these credentials: export AWS_PROFILE={account['account_name']}")
print(f"Credentials expire: {credentials['Expiration']}")
except Exception as e:
print(f"Error switching to account {account['account_name']}: {str(e)}")
print("Continuing with next account...")
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment