Home > database >  How to write Resource-based policy in Cloudformation
How to write Resource-based policy in Cloudformation

Time:12-02

I want to invoke a Lambda from an external AWS account, and I managed to do it by creating a Policy statement in the Resource-based policy tab of the console (Lambda > Configuration > Permissions > Resource-based policy). Although, I cannot find a way to write a policy like this in my CloudFormation template. Here is what I wrote:

InvokePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: 'InvokeLambdaFromGateway'
      Roles: 
        - !Sub "arn:aws:iam::${AWS::AccountId}:role/NameOfLambda"
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: InvokeLambdaExternally
            Effect: Allow
            Resource:
              - !Ref NameOfLambda
            Action:
              - lambda:InvokeFunction
            Principal:
              AWS: ["arn:aws:iam::AccountIUseToInvokeTheLambda:root"]

But I get this error: IAM Resource Policy statement shouldnt have Principal or NotPrincipal.

How can I attach that policy to my Lambda with a Principal definition?

CodePudding user response:

This error is because you don't add the principal to the policy. You need to add a permission:

  permission:
    Type: AWS::Lambda::Permission
    Properties:
      FunctionName: !GetAtt function.Arn
      Action: lambda:InvokeFunction
      Principal: 123456789012

Read more in the documentation.

  • Related