Created
January 21, 2025 16:08
-
-
Save filipeandre/07e4eff6a1aa737625174854ad5dc27f to your computer and use it in GitHub Desktop.
Script used to validate tag session permission
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import boto3 | |
| from botocore.exceptions import BotoCoreError, ClientError | |
| def assume_role_with_tags(aws_access_key, aws_secret_key, role_arn, session_name, tags): | |
| """ | |
| Assumes an AWS IAM Role with the specified tags. | |
| :param aws_access_key: AWS access key ID | |
| :param aws_secret_key: AWS secret access key | |
| :param role_arn: ARN of the role to assume | |
| :param session_name: Name for the assumed session | |
| :param tags: Dictionary of tags to apply to the session (e.g., {"Key": "Value"}) | |
| :return: Credentials for the assumed role | |
| """ | |
| try: | |
| # Initialize the STS client | |
| sts_client = boto3.client( | |
| 'sts', | |
| aws_access_key_id=aws_access_key, | |
| aws_secret_access_key=aws_secret_key | |
| ) | |
| # Convert the tags dictionary to a format STS expects | |
| sts_tags = [{"Key": k, "Value": v} for k, v in tags.items()] | |
| # Assume the role | |
| response = sts_client.assume_role( | |
| RoleArn=role_arn, | |
| RoleSessionName=session_name, | |
| Tags=sts_tags | |
| ) | |
| # Extract credentials from the response | |
| credentials = response['Credentials'] | |
| print("Assumed role successfully!") | |
| print("Access Key:", credentials['AccessKeyId']) | |
| print("Secret Key:", credentials['SecretAccessKey']) | |
| print("Session Token:", credentials['SessionToken']) | |
| return credentials | |
| except (BotoCoreError, ClientError) as error: | |
| print(f"Error assuming role: {error}") | |
| return None | |
| if __name__ == "__main__": | |
| # User-provided inputs | |
| AWS_ACCESS_KEY = "" | |
| AWS_SECRET_KEY = "" | |
| ROLE_ARN = "" | |
| SESSION_NAME = "test-session-1" | |
| TAGS = { | |
| "Environment": "Test", | |
| "Project": "Tag" | |
| } | |
| # Call the function | |
| credentials = assume_role_with_tags(AWS_ACCESS_KEY, AWS_SECRET_KEY, ROLE_ARN, SESSION_NAME, TAGS) | |
| if credentials: | |
| print("You can now use these credentials for further AWS API calls.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment