|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import boto3 |
| 4 | + |
| 5 | +def get_temp_credentials(profile_name, token_code, mfa_serial): |
| 6 | + # Create a session with the specified profile |
| 7 | + session = boto3.Session(profile_name=profile_name) |
| 8 | + |
| 9 | + # Get temporary credentials using the STS client and MFA token code |
| 10 | + client = session.client('sts') |
| 11 | + response = client.get_session_token( |
| 12 | + DurationSeconds=3600, |
| 13 | + SerialNumber=mfa_serial, |
| 14 | + TokenCode=token_code |
| 15 | + ) |
| 16 | + |
| 17 | + # Return the temporary credentials |
| 18 | + return response['Credentials'] |
| 19 | + |
| 20 | +if __name__ == '__main__': |
| 21 | + # Parse command line arguments |
| 22 | + parser = argparse.ArgumentParser(description='Get temporary AWS credentials using MFA') |
| 23 | + parser.add_argument('--profile', required=True, help='Name of the AWS CLI profile to use') |
| 24 | + parser.add_argument('--token', required=True, help='MFA token code') |
| 25 | + parser.add_argument('--mfa-serial', required=True, help='ARN of the MFA device') |
| 26 | + args = parser.parse_args() |
| 27 | + |
| 28 | + # Get temporary credentials |
| 29 | + temp_creds = get_temp_credentials(args.profile, args.token, args.mfa_serial) |
| 30 | + |
| 31 | + # Set environment variables with the temporary credentials |
| 32 | + os.environ['AWS_ACCESS_KEY_ID'] = temp_creds['AccessKeyId'] |
| 33 | + os.environ['AWS_SECRET_ACCESS_KEY'] = temp_creds['SecretAccessKey'] |
| 34 | + os.environ['AWS_SESSION_TOKEN'] = temp_creds['SessionToken'] |
| 35 | + |
| 36 | + # Print a message indicating that the environment variables have been set |
| 37 | + print("Temporary credentials obtained with MFA. Environment variables have been set.") |
| 38 | + |
| 39 | + # Print the temporary credentials |
| 40 | + print(f"AWS_ACCESS_KEY_ID={temp_creds['AccessKeyId']}") |
| 41 | + print(f"AWS_SECRET_ACCESS_KEY={temp_creds['SecretAccessKey']}") |
| 42 | + print(f"AWS_SESSION_TOKEN={temp_creds['SessionToken']}") |
0 commit comments