Search code examples
amazon-web-servicesaws-lambdaamazon-iamroles

Get information about about the role that creates an AWS resource


Im creating a lambda function to tag resources with a specific tag depending on the role that creates the resource:

if role = dev:  
then 
ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'environnement','Value':'dev'}]) 
elif role = prod: 
ec2.create_tags(Resources=instance_ids,Tags=[{'Key':'environnement','Value':'prod'}])

.....

My question: How can I get information about the role that creates the resource?

Thanks in advance !!


Solution

  • AWS resources do not store "who" created the resource.

    When an API call is sent to AWS to create a resource, AWS will check whether the provided credentials are permitted to create the resource (eg an Amazon EC2 instance). If they are permitted, then the resource is created and the resource is associated with an AWS account. No indication of who made the API request is stored on the resource.

    However, you can use AWS CloudTrail to view an audit log of API calls, including the identity that made the API call. This identity might be associated with an IAM User or an IAM Role, or even the root credentials of the AWS account.

    From Using AWS Lambda with Amazon CloudWatch Events - AWS Lambda:

    Amazon CloudWatch events help you to respond to state changes in your AWS resources. When your resources change state, they automatically send events into an event stream. You can create rules that match selected events in the stream and route them to your AWS Lambda function to take action.

    Thus, you can configure CloudWatch Events to trigger the Lambda function whenever a specific event happens (eg RunInstances). Full details of the event will be passed to the Lambda function, so it can determine who triggered that event.