How can I use the “RoleSessionName” parameters effectively within the lambda function?

262    Asked by CrownyHasegawa in AWS , Asked on Apr 17, 2024

I am currently tasked with implementing an AWS lambda function which would assume an IAM role for performing specific actions on AWS resources. How can I use the “RoleSessionName” parameters effectively within the lambda function to ensure proper auditing, logging, and identification of the role session in AWS cloudTrail and AWS cloudWatch logs? 

Answered by Dorine Hankey

 In the context of AWS, here is how you can use the “RoleSessionName” within an AWS lambda function:-

Choosing an appropriate Rolesessionname

You can use a unique name for the parameters of Rolesessionname which would help you in identifying the purpose or context of the role assumption. You can incorporate relevant information such as the name of the function, details of the event, or the user's context to make the session name meaningful and traceable.

Implement in AWS lambda function

You should specify the Rolesessionname parameters in your lambda function when assuming the IAM role by using the AWS SDK or even you can use the AWS lambda runtime environment.

Here is an example given below by using the Python programming language and Boto3 in AWS lambda function:-

Import boto3
Import json
Import logging

# Initialize logger

Logger = logging.getLogger()
Logger.setLevel(logging.INFO)
Def lambda_handler(event, context):

    # Specify RoleSessionName based on Lambda function context and event details

      Role_session_name = f”{context.function_name}-Session-{event[‘request_id’]}”

    # Initialize AWS clients

    Sts_client = boto3.client(‘sts’)
    S3_client = boto3.client(‘s3’)

    Try:

        # Assume the IAM role with RoleSessionName

        Response = sts_client.assume_role(
            RoleArn=’arn:aws:iam::123456789012:role/my-role’,
            RoleSessionName=role_session_name
        )

        # Use the assumed credentials to perform actions on AWS resources

        S3_key = f”example-{event[‘request_id’]}.txt”        S3_client.put_object(
            Bucket=’my-bucket’,
            Key=s3_key,
            Body=json.dumps(event)
        )
        Logger.info(f”Object ‘{s3_key}’ uploaded successfully to S3.”)
        Return {
            ‘statusCode’: 200,
            ‘body’: json.dumps({‘message’: ‘Role assumed and object uploaded successfully’})
        }

    Except Exception as e:

        Logger.error(f”Error occurred: {str€}”)

        Return {
            ‘statusCode’: 500,
            ‘body’: json.dumps({‘error’: ‘Internal Server Error’})
        }

Here is the same example given in java programming language:-

Import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
Import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
Import software.amazon.awssdk.regions.Region;
Import software.amazon.awssdk.services.sts.StsClient;
Import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
Import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
Import software.amazon.awssdk.services.sts.model.StsException;
Import software.amazon.awssdk.services.s3.S3Client;
Import software.amazon.awssdk.services.s3.model.PutObjectRequest;
Import software.amazon.awssdk.services.s3.model.S3Exception;
Import java.io.IOException;
Import java.io.InputStream;
Import java.io.OutputStream;
Import com.amazonaws.services.lambda.runtime.Context;
Import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
Import com.fasterxml.jackson.databind.JsonNode;
Import com.fasterxml.jackson.databind.ObjectMapper;
Public class LambdaFunctionHandler implements RequestStreamHandler {
    Private static final String ROLE_ARN = “arn:aws:iam::123456789012:role/my-role”;
    Private final StsClient stsClient = StsClient.builder().region(Region.US_EAST_1).build();
    Private final S3Client s3Client = S3Client.builder().region(Region.US_EAST_1).build();

    @Override

    Public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode eventNode = objectMapper.readTree(input);
        String requestId = eventNode.get(“request_id”).asText();
        String functionName = context.getFunctionName();
        String roleSessionName = functionName + “-Session-“ + requestId;
        Try {
            AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
                    .roleArn(ROLE_ARN)
                    .roleSessionName(roleSessionName)
                    .build();
            AssumeRoleResponse assumeRoleResponse = stsClient.assumeRole(assumeRoleRequest);
            AwsSessionCredentials sessionCredentials = assumeRoleResponse.credentials();
            // Use the assumed credentials to perform actions on AWS resources
            String s3Key = “example-“ + requestId + “.txt”;
            PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                    .bucket(“my-bucket”)
                    .key(s3Key)
                    .build();
            S3Client.putObject(putObjectRequest, InputStream.nullInputStream());
            // Return success response
            String responseJson = “{”statusCode”: 200, ”body”: {”message”: ”Role assumed and object uploaded successfully”}}”;
            Output.write(responseJson.getBytes());
        } catch (StsException | S3Exception | IOException e) {
            // Log and return error response
            String errorJson = “{”statusCode”: 500, ”body”: {”error”: ”Internal Server Error”}}”;
            Output.write(errorJson.getBytes());
            Context.getLogger().log(“Error occurred: “ + e.getMessage());
        }
    }
}

Your Answer

Interviews

Parent Categories