I built a Terraform module ‘aws-lambda-with-role’ that pretty much does what it says. I’ve used it quite a bit and it suits my needs well.
The module accepts in an input variable an array of IAM policy statements. In the module, the lambda function is created, the log group for the lambda function is created, a role is created, a role policy is created, policy statements to allow creating and writing to log streams is created, and then the array of IAM policy statements provided to the module are added to the policy, and the policy is attached to the role.
Now I want to be able to specify conditions on the policy statements. As input to the module, I want to have:
iam_inline_policy = [
{
sid = "AllowPutUserItem"
effect = "Allow"
action = [
"dynamodb:PutItem"
]
resource = [
local.workspace.dynamodb_user_table_arn
]
condition = {
test = "ForAllValues:StringEquals"
variable = "dynamodb:LeadingKeys"
values = ["USEROBJECT#"]
}
},
{
sid = "AllowPutEvents"
effect = "Allow"
action = [
"events:PutEvents"
]
resource = [
aws_cloudwatch_event_bus.app_event_bus.arn
]
},
You can see the added ‘condition’ in the AllowPutUserItem statement. That’s what I’m trying to integrate here. In the module, I am building the policy with:
data "aws_iam_policy_document" "lambda_policy_document" {
for_each = {
for index, value in local.iam_inline_policy : value.sid => value
}
statement {
sid = each.value.sid
effect = each.value.effect
actions = each.value.action
resources = each.value.resource
#Some IAM statements will have a condition, some won't.
#Some may have more than one condition.
dynamic "condition" {
for_each = can(each.value.condition) ? each.value.condition : []
content {
test = condition.value.test
variable = condition.value.variable
values = condition.value.values
}
}
}
}
The ‘dynamic condition’ is what I’m trying to get to work. Currently this seems to just ignore any conditions in the policy statements passed to the module.
How can I write the module to build policy statements from input variables?