How to create Lambda using AWS Serverless Application Model (SAM) without an AWS managed IAM policy?

0

Hi,

I want to create a Lambda function in Serverless Application Model (SAM) without any AWS managed policies so that I can have fine-grained control over permissions to resources and to enforce a least permissive model. My existing code looks like this:

  GetAllOrdrersFunction:
	Type: AWS::Serverless::Function
	Properties:
	  CodeUri: orders_api/
	  Handler: orders.get_all_orders
	  Runtime: python3.9
	  Policies:
		- CloudWatchPutMetricPolicy: {}
		- DynamoDBCrudPolicy:
			TableName: !Ref OrdersTable

When I deploy it to AWS, I see that an execution role sam-app-GetAllOrdersFunctionRole-3VGCZYIGQNGK is automatically generated consisting of the following policies:

  • AWSLambdaBasicExecutionRole - AWS Managed
  • GetAllOrdersFunctionRolePolicy0 - Customer inline
  • GetAllOrdersFunctionRolePolicy1 - Customer inline

How can I modify my template to only deploy my lambda function with my policies and not the default AWS managed policy?

Thanks.

1 Answer
0

Use the Role property instead of Policies in the AWS::Serverless::Function.

When you use the Policies property, the policies that you've specified will be appended to the default role for this function. Since you didn't specify a role in the template, one is created for you, which has the AWSLambdaBasicExecutionRole.

So, create an IAM role that contains the least privilege polies that you need and then just reference the ARN of that role in the AWS::Serverless::Function. Note that if the Role property is set, the Policies property is ignored.

More info: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-policies

profile picture
joahna
answered 2 years ago
  • Thanks, I understand this much. Can you please point me in the right direction on how I can write a role with my own custom policies for a Lambda function? When I attempt to do so I get a circular dependency error as my policies are referencing my lambda function which has the role attached. Please help.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions