mohammad Naimi
mohammad Naimi

Reputation: 2359

How to add policy to AWS SAM file to put value in secrets manager with Lambda

Policies:
        - AWSXrayWriteOnlyAccess
        - AWSSecretsManagerGetSecretValuePolicy:
            SecretArn: !Sub 
        - AWSSecretsManagerRotationPolicy:
            SecretArn: !Sub arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:/${EnvironmentTagName}/*
            Effect: Allow
            FunctionName: !Sub ${AWS::StackName}-****
            Action:
              - secretsmanager:UpdateSecret
              - secretsmanager:GetSecretValue
              - secretsmanager:PutSecretValue
            Resource:

I want to change secrets value by lambda , but I got this error:-

AccessDeniedException: User: arn:aws:sts:::assumed-role/LambdaName is not authorized to perform: secretsmanager:PutSecretValue on resource: /**/API_TOKEN because no identity-based policy allows the secretsmanager:PutSecretValue action

Upvotes: 1

Views: 921

Answers (1)

Arpit Jain
Arpit Jain

Reputation: 4043

There are 3 ways to specify policies for a Lambda function in the AWS SAM template:-

  1. AWS managed policy named
  2. AWS SAM policy template
  3. Inline policy document defined

AWSSecretsManagerRotationPolicy is AWS SAM Policy template that already includes secretsmanager:DescribeSecret, secretsmanager:GetSecretValue, secretsmanager:PutSecretValue, secretsmanager:UpdateSecretVersionStage, so you don't need to explicitly specify these actions, you can simply use the policy template directly:-

MyFunction:
  Type: 'AWS::Serverless::Function'
  Properties:
    CodeUri: ${codeuri}
    Handler: hello.handler
    Runtime: python2.7
    Policies:
      - AWSSecretsManagerRotationPolicy: # AWS SAM Policy template
          SecretArn: !Sub "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:your_secret_value"

In case you need to specify the policies(inline) explicitly for the Lambda function, you can do like so:-

Policies:
    - AWSXrayWriteOnlyAccess # AWS Managed Policy
    - Version: '2012-10-17' # Inline Policy Document
      Statement:
        - Effect: Allow
          Action:
            - secretsmanager:UpdateSecret
            - secretsmanager:GetSecretValue
            - secretsmanager:PutSecretValue
          Resource: !Sub "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:your_secret_value"

Useful Resources:-

Upvotes: 1

Related Questions