Is there a way to conditionally add statement
blocks in aws_iam_policy_document
? I'm looking for something like:
data "aws_iam_policy_document" "policy" {
statement {
sid = "PolicyAlways"
...
}
if (var.enable_optional_policy) {
statement {
sid = "PolicySometimes"
...
}
}
}
In order to use AWS policy variables with this data source, use & {...} notation for interpolations that should be processed by AWS rather than by Terraform. For more information about building AWS IAM policy documents with Terraform, see the AWS IAM Policy Document Guide.
A condition constrains whether a statement applies in a particular situation. Conditions can be specific to an AWS service. When using multiple condition blocks, they must all evaluate to true for the policy statement to apply. In other words, AWS evaluates the conditions as though with an "AND" boolean operation.
To have Terraform render JSON containing "Principal": "*", use type = "*" and identifiers = ["*"]. To have Terraform render JSON containing "Principal": {"AWS": "*"}, use type = "AWS" and identifiers = ["*"]. For more information about AWS principals, refer to the AWS Identity and Access Management User Guide: AWS JSON policy elements: Principal.
Terraform has a cool resource block called the 'dynamic' block that allows generating multiple nested blocks for a resource. This tutorial will show you how to generate multiple IAM policy statements using this dynamic block.
Yes. You can (ab)use a dynamic
block with a boolean to optionally include the block.
data "aws_iam_policy_document" "policy" {
statement {
sid = "PolicyAlways"
...
}
dynamic "statement" {
# The contents of the list below are arbitrary, but must be of length one.
# It is only used to determine whether or not to include this statement.
for_each = var.enable_optional_policy ? [1] : []
content {
sid = "PolicySometimes"
...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With