I have Lambda function written in Python 3.7.
This Lambda function is invoked by some users through AWS CLI using:
aws lambda invoke --function-name stXXX-XXX out --log-type Tail
I want to capture who invoked my Lambda function through AWS CLI in my code.
As there any way I can find who invoke my Lambda function in python boto3 code?
Yes. Generally for that you would have to enable logging data event in CloudTrail:
By default logging of lambda invocations is disabled as it can lead to a lot of logs.
The log event contains information about what IAM user or role invoked the function. For example:
"userIdentity": {
"type": "IAMUser",
"principalId": "A1B2C3D4E5F6G7EXAMPLE",
"arn": "arn:aws:iam::999999999999:user/myUserName",
"accountId": "999999999999",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE",
"userName": "myUserName"
},
It appears that your situation is:
Unfortunately, information about 'who' invoked the Lambda function (or, more specifically, which IAM entity invoked it) is not available.
The AWS Lambda context object in Python does not provide this information to the Lambda function.
A "more correct" way would be to control the IAM permissions that determine who can invoke this Lambda function. Only correctly authorized persons should have permission to call lambda:Invoke on this function. Similarly, it is important to limit who can use iam:PassRole on the IAM Role used by this function, since it has permissions to start the EC2 instance and it could be used on other functions unless PassRole is restricted.