我有一个数据模块,我正在其中创建"aws_iam_policy_document"quot;信任策略,并且希望仅为某些模块而不是全部模块添加条件。
例如:
data "aws_iam_policy_document" "trust-policy" {
statement {
actions = [var.action]
principals {
type = var.type
identifiers = concat(var.trusted_arns)
}
count = var.git ? 1 : 0
condition {
test = "StringEquals"
variable = "abc"
values = ["sts.amazonaws.com"]
}
condition {
test = "StringLike"
variable = "dcf"
values = ["repo:var.org_name/var.repo_name:ref:refs/heads/var.branch_name"]
}
}
}
只有当模块是git时,我才想运行条件块。但计数失败,出现以下错误:
An argument named "count" is not expected here.
您可以使用dynamic
块。例如,声明一个新的变量trust_policy_conditions
,如下所示:
variable "trust_policy_conditions" {
description = "A list of trust policy conditions"
type = list(object({
test = string
variable = string
values = list(string)
}))
default = []
}
然后将动态块添加到数据源:
data "aws_iam_policy_document" "trust-policy" {
statement {
actions = [var.action]
principals {
type = var.type
identifiers = concat(var.trusted_arns)
}
dynamic "condition" {
for_each = var.git == true ? { for index, policy in var.trust_policy_conditions : index => policy } : {}
content {
test = condition.value.test
variable = condition.value.variable
values = condition.value.values
}
}
}
}
请注意,索引是关键,因为可能存在多个条件共享同一测试或变量属性的情况。