How to attach a managed policy to a lambda function in serverless framework

9k views Asked by At

How can I attach a managed policy to a lambda function?

I tried:

provider:
  name: aws
  role: arn:aws:iam::aws:policy/AmazonCognitoReadOnly

But this resulted in the following error:

An error occurred while provisioning your stack: GaDashextractLambdaFunction - 1 validation error detected: Value 'arn:aws:iam::aws:policy/AmazonCognitoReadOnly' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@-_/]+.

2

There are 2 answers

1
Anthony Neace On BEST ANSWER

Note the error -- it expects role instead of policy.

IAM Policies are documents that define permissions and can't be attached directly to lambda functions. Create an IAM Role and attach the managed policy to the role. Think of the role as a container for your policy; policies can't be attached directly to lambda functions, but roles can. You can freely attach and detach managed and inline policies to your roles.

Option 1: Fix this error from AWS Console with a pre-defined policy:

  • Create a new IAM Role for your lambda function.
  • During creation, attach the AmazonCognitoReadOnly managed policy.
  • Replace the ARN in your role definition with your new role's ARN.

Option 2: Define actions of AmazonCognitoReadOnly policy in serverless.yml:

This effectively converts the managed policy to an inline policy. Warning: this is untested.

provider:
  ...
  iamRoleStatements:
    - Effect: Allow
      Action:
        - cognito-identity:Describe*
        - cognito-identity:Get*
        - cognito-identity:List*
        - cognito-idp:Describe*
        - cognito-idp:AdminGetUser
        - cognito-idp:List*
        - cognito-sync:Describe*
        - cognito-sync:Get*
        - cognito-sync:List*
        - iam:ListOpenIdConnectProviders
        - iam:ListRoles
        - sns:ListPlatformApplication
      Resource: *

Further Reading:

1
Yan On

You can. Just provide the ARN in the ManagedPolicyArns of a Role resource.

Resources:
  RoleName:
    ManagedPolicyArns:
      - "arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess"

For policies applied to all functions:

provider:
  name: aws
  iamManagedPolicies:
    - "arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess"