07 Aug 2023 - rich
A collection of knowledge in a single place. How to generate an IAM policy document in JSON format for use with resources that expect policy documents, such as aws_iam_policy.
Using this data source to generate policy documents is optional. It is also valid to use literal JSON strings in your configuration or to use the file interpolation function to read a raw JSON policy document from a file.
AWS’s IAM policy document syntax allows for replacement of policy variables within a statement using ${…}-style notation, which conflicts with Terraform’s interpolation syntax. 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.
data "aws_iam_policy_document" "example" {
statement {
sid = "1"
actions = [
"s3:ListAllMyBuckets",
"s3:GetBucketLocation",
]
resources = [
"arn:aws:s3:::*",
]
}
statement {
actions = [
"s3:ListBucket",
]
resources = [
"arn:aws:s3:::${var.s3_bucket_name}",
]
condition {
test = "StringLike"
variable = "s3:prefix"
values = [
"",
"home/",
"home/&{aws:username}/",
]
}
}
statement {
actions = [
"s3:*",
]
resources = [
"arn:aws:s3:::${var.s3_bucket_name}/home/&{aws:username}",
"arn:aws:s3:::${var.s3_bucket_name}/home/&{aws:username}/*",
]
}
}
resource "aws_iam_policy" "example" {
name = "example_policy"
path = "/"
policy = data.aws_iam_policy_document.example.json
}
You can specify a condition with multiple keys and values by supplying multiple condition blocks with the same test value, but differing variable and values values.
Statements without a sid cannot be overridden. In other words, a statement without a sid from source_policy_documents cannot be overridden by statements from override_policy_documents.
statement
The following arguments are optional:
condition
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.
The following arguments are required: