Em *_* Ma 2 resources count conditional-statements terraform
我很想知道是否有人知道在 Terraform 中使用条件计数语句的更好替代方法。我所说的“条件计数语句”是指根据变量输入等条件,计数将计算以创建 0 或 1 个资源的语句。
一个简单的例子:
resource "xxxxxxxx" "example" {
count = var.example != null ? 1 : 0
}
Run Code Online (Sandbox Code Playgroud)
在这里,只有当 var.example 有值(不为空)时才会创建资源,否则不会创建。
条件计数在实践中通常工作正常,但有时在比上述更复杂的用途中,它会带来在 Terraform Plan 期间出现错误的风险,因为它无法评估预应用计数的结果。
The "count" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.
To work around this, use the -target argument to first apply only the
resources that the count depends on.
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法可以达到在 Terraform 中按条件创建资源的相同效果?
它因情况而异,但在某些情况下您需要解决这个问题。有一个聪明的技巧,但在单个项目(二进制存在或不存在)的情况下似乎很迟钝。但在实际有多个项目的情况下,这应该会有所帮助。
这是一个完全人为的例子,但我实际上经常使用这个方法。简而言之,在应用之前未知的事物列表可以替换为具有您不关心的键的对象列表。目的是for_each
不介意值在计划时是否未知,只要密钥未知。
考虑以下具有这四个模块的根模块。
resource "aws_s3_bucket" "this" {
bucket = "h4s-test-bucket"
}
# module "with_count" { # cannot be determined until apply
# source = "./with-count"
# x = aws_s3_bucket.this.id
# }
module "with_for_each_over_item" { # handy workaround
source = "./with-for-each-over-item"
x = aws_s3_bucket.this.id
}
output "with_for_each_over_item" {
value = module.with_for_each_over_item
}
# module "with_for_each_list" { # cannot be determined until apply
# source = "./with-for-each-list"
# x = [aws_s3_bucket.this.id]
# }
module "with_for_each_list_better" { # handy workaround
source = "./with-for-each-list-better"
x = [{ y = aws_s3_bucket.this.id }]
}
output "with_for_each_list_better" {
value = module.with_for_each_list_better
}
module "with_for_each_list_best" { # handier workaround
source = "./with-for-each-list-best"
x = [aws_s3_bucket.this.id]
}
output "with_for_each_list_best" {
value = module.with_for_each_list_best
}
Run Code Online (Sandbox Code Playgroud)
variable "x" {
type = string
default = null
}
resource "null_resource" "this" {
count = var.x != null ? 1 : 0
}
output "this" {
value = null_resource.this
}
Run Code Online (Sandbox Code Playgroud)
variable "x" {
type = string
default = null
}
resource "null_resource" "this" {
for_each = { for i, v in [var.x] : i => v }
}
output "this" {
value = null_resource.this
}
Run Code Online (Sandbox Code Playgroud)
variable "x" {
type = list(string)
default = []
}
resource "null_resource" "this" {
for_each = toset(var.x)
}
output "this" {
value = null_resource.this
}
Run Code Online (Sandbox Code Playgroud)
variable "x" {
type = list(object({ y = string }))
default = []
}
resource "null_resource" "this" {
for_each = { for i, v in var.x : i => v }
}
output "this" {
value = null_resource.this
}
Run Code Online (Sandbox Code Playgroud)
variable "x" {
type = list(string)
default = []
}
resource "null_resource" "this" {
for_each = { for i, v in var.x : i => v }
}
output "this" {
value = null_resource.this
}
Run Code Online (Sandbox Code Playgroud)
如果变量的值在计划时未知,请考虑使用键已知的对象。