Search code examples
amazon-web-servicesaws-lambdaterraformaws-secrets-manager

Attaching resource policy to my lambda function for AWS secrets manager using terraform


I'm trying to attach a lambda permission so that AWS secrets manager can invoke my lambda function to rotate multiple secrets.

resource "aws_lambda_permission" "allow_rotate_secrets_permission" {
    statement_id  = "AllowExecutionFromSecretsManager"
    action        = "lambda:InvokeFunction"
    function_name = "UserCredentialsRotationLambda"
    principal     = "secretsmanager.amazonaws.com"
    source_arn    = ["secret.arn", "secret.arn2", "secret.arn3"]
}

The problem is source_arn is throwing an error saying "expecting a string". I'm not sure if my syntax is correct. Can you please help me with the right syntax?


Solution

  • The source_arn argument expects a single ARN in a form of a string. You can use for_each to keep your code simple:

    resource "aws_lambda_permission" "allow_rotate_secrets_permission" {
        for_each = toset(["secret.arn", "secret.arn2", "secret.arn3"])
    
        statement_id  = "AllowExecutionFromSecretsManager"
        action        = "lambda:InvokeFunction"
        function_name = "UserCredentialsRotationLambda"
        principal     = "secretsmanager.amazonaws.com"
        source_arn    = each.value
    }
    

    This will create 3 instances of the aws_lambda_permission resource.