简体   繁体   中英

How to add policy to access secret with lambda function AWS SAM

I am trying to give access permission of secret manager to my lambda function in SAM template but it is giving me error that policy statement is malformed.

     Policies:
      - Statement:
      - Sid: AWSSecretsManagerGetSecretValuePolicy
        Effect: Allow
        Action: secretsmanager:GetSecretValue
        Resource: <arn >

Can some one let me know the correct way of adding policy to my lambda function. I am using SAM template (Type: AWS::Serverless::Function)

There are SAM Policy Templates where one of them is AWSSecretsManagerGetSecretValuePolicy you can use them directly in the definition.

Or if you wanna manage the policies yourself.

    QueryFunction:
        Type: AWS::Serverless::Function
        Properties:
        Handler: lambda_handler.lambda
        Policies:
            - AmazonDynamoDBFullAccess
            - AWSLambdaVPCAccessExecutionRole
            - SSMParameterReadPolicy:
                ParameterName: parameter_name
            - Statement:
                - Effect: Allow
                Action:
                    - dynamodb:*
                Resource: 'resource_arn'
        Runtime: python3.7

Try this:

    Policies:
      - Version: '2012-10-17'
        Statement:
          - Sid: AWSSecretsManagerGetSecretValuePolicy
            Effect: Allow
            Action: secretsmanager:GetSecretValue
            Resource: <arn >

This policy on the lambda works for me (YAML)

Policies:
  - AWSSecretsManagerGetSecretValuePolicy:
      SecretArn:
        Ref: THE_NAME_YOU_GAVE_YOUR_SECRET_RESOURCE

This policy only accepts ARN of a secret, so secret name will not work. https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html#secrets-manager-get-secret-value-policy

Below works for me.

Resources:  
MyFunction:
Type: AWS::Serverless::Function
Properties:
  CodeUri: MyProject/
  Handler: app
  Policies:
    - AWSSecretsManagerGetSecretValuePolicy:
        SecretArn: 'arn:aws:secretsmanager:####'

or passing it as a parameter

    - AWSSecretsManagerGetSecretValuePolicy:
        SecretArn: !Ref RdsSecretArn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM