Terraform: 基于.tfvars 中的变量有条件地创建资源

我有在 .tf文件中定义的资源,这些资源对于多个应用程序是通用的。我通过 .tfvars文件填充许多字段。我需要省略一些完全基于 .tfvars中的变量的资源。

例如,如果我有这样的资源:

resource "cloudflare_record" "record" {
zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
name    = "${var.subdomain}"
value   = "${var.origin_server}"
type    = "CNAME"
ttl     = 1
proxied = true
}

但是我在我的 .tfvars文件中声明了类似于 cloudflare = false的东西,我希望能够这样做:

if var.cloudflare {
resource "cloudflare_record" "record" {
zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
name    = "${var.subdomain}"
value   = "${var.origin_server}"
type    = "CNAME"
ttl     = 1
proxied = true
}
}

我已经研究过动态块,但是看起来您只能使用它们来编辑资源中的字段和块。我需要能够忽略整个资源。

94328 次浏览

Add a count parameter with a ternary conditional using the variable declared in .tfvars like this:

resource "cloudflare_record" "record" {
count = var.cloudflare ? 1 : 0
zone_id = "${data.cloudflare_zones.domain.zones[0].id}"
name    = "${var.subdomain}"
value   = "${var.origin_server}"
type    = "CNAME"
ttl     = 1
proxied = true
}

In this example var.cloudflare is a boolean declared in the .tfvars file. If it is true a count of 1 record will be created. If it is false a count of 0 record will be created.

After the count apply the resource becomes a group, so later in the reference use 0-index of the group:

cloudflare_record.record[0].some_field

An issue i'm seeing this with is if the resource your trying to create is already using a for_each then you can't use both count and for_each in the resource. I'm still trying to find an answer on this will update if I find something better.

Expanding on @Joel Guerra's answer, after you use count to determine whether to deploy the resource or not, you can use the one() function to refer to the resource without an index (i.e. without having to use [0]).

For example, after defining the resource like below

resource "cloudflare_record" "record" {
count = var.cloudflare ? 1 : 0
}

Define a local variable like below

locals {
cloudflare_record_somefield = one(cloudflare_record.record[*].some_field)
}

Now instead of cloudflare_record.record[0].some_field, you can use

local.cloudflare_record_somefield

If the count is 0 (e.g. var.cloudflare is false and the resource wasn't created) then local.cloudflare_record_somefield would return null (instead of returning an error when indexing using [0]).

Reference: https://developer.hashicorp.com/terraform/language/functions/one