How can I use the Boto3 to assume a role in the target AWS account and then perform specific actions?

118    Asked by Daminidas in AWS , Asked on May 24, 2024

 I am currently working on a particular task that is related to accessing the resources in an AWS account different from your default one. How can I use the Boto3 to assume a role in the target AWS account and then perform specific actions, such as listing objects in an S3 bucket or launching an EC2 instance? 

Answered by Deepa bhawana

 In the context of AWS, here are the steps given:-

Import the required libraries

First, you would need to import the required libraries.

Create an STS client

You can initialize a Boto3 client for the security token service which would allow you to request temporary security credentials.

Specify the role of ARN

You can define the Amazon resources name of the IAM role for which you want to request temporary security credentials.

Assuming the role

You can use the “assume role” method of the STS client to request temporary Credentials for the specific role. You can provide a “Rolesessionname” to uniquely identify this session.

Extract the temporary Credentials

If the role assumption is successful extract the temporary security credentials and from the response.

Create an assumed session

You can use the extracted temporary Credentials to create a new Boto3 session which represents the assumed role.

Use the assume session

Now you can interact with the AWS services as if you are using the assumed role.

Here is the example given below which Includes error handling and more detailed comments:-

Import boto3

From botocore.exceptions import ClientError

Def assume_role_and_access_s3(role_arn, bucket_name):
    # Initialize the STS client
    Sts_client = boto3.client(‘sts’)
    Try:
        # Assume the specified role
        Assumed_role = sts_client.assume_role(
            RoleArn=role_arn,
            RoleSessionName=’AssumeRoleSession’
        )
    Except ClientError as e:
        Print(“Error assuming role:”, e)
        Return
    # Extract temporary credentials from the assumed role response
    Credentials = assumed_role[‘Credentials’]
    Try:
        # Create a new session using the assumed role credentials
        Assumed_session = boto3.Session(
            Aws_access_key_id=credentials[‘AccessKeyId’],
            Aws_secret_access_key=credentials[‘SecretAccessKey’],
            Aws_session_token=credentials[‘SessionToken’]
        )
        # Use the assumed session to access S3
        S3_client = assumed_session.client(‘s3’)
        Response = s3_client.list_objects(Bucket=bucket_name)
        # Print the S3 response
        Print(“List of objects in bucket:”, response)
    Except ClientError as e:
        Print(“Error accessing S3:”, e)
        Return
# Replace ‘arn:aws:iam::123456789012:role/MyRole’ with your actual role ARN
Role_arn = ‘arn:aws:iam::123456789012:role/MyRole’
# Replace ‘your-bucket-name’ with your actual S3 bucket name
Bucket_name = ‘your-bucket-name’
# Call the function to assume the role and access S3
Assume_role_and_access_s3(role_arn, bucket_name)

In this code, we define a function that assumes role and access S3 which takes the role ARN and S3 bucket name as parameters.

Inside the function, we can initialize the STS client and attempt to assume the specific role.

If the role assumption is successful, we can extract the temporary Credentials from the response and create a new session by using these credentials.

By using the assumed session we can create an S3 client and list objects in the specific bucket.

Error handling is included for catching any exceptions that may occur during the role assumption or S3 access.



Your Answer

Interviews

Parent Categories