Terraform:基于 .tfvars 中的变量有条件地创建资源 [英] Terraform: Conditional creation of a resource based on a variable in .tfvars

查看:81
本文介绍了Terraform:基于 .tfvars 中的变量有条件地创建资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have resources defined in .tf files that are generic to several applications. I populate many of the fields via a .tfvars file. I need to omit some of the resources entirely based on variables in the .tfvars.

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

For example if I have a resource like:

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 的内容,我希望能够执行以下操作:

But then I declare something like cloudflare = false in my .tfvars file I'd like to be able to do something like this:

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
 }
}

我查看了动态块,但看起来您只能使用它们来编辑资源中的字段和块.我需要能够忽略整个资源.

I've looked at dynamic blocks but that looks like you can only use those to edit fields and blocks within a resource. I need to be able to ignore an entire resource.

推荐答案

使用 .tfvars 中声明的变量添加一个带有三元条件的 count 参数,如下所示:

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
}

在此示例中,var.cloudflare 是在 .tfvars 文件中声明的布尔值.如果为真,则将创建 1 个 record 计数.如果为 false,则将创建 0 个 record 计数.

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.

count申请资源后成为一个组,所以后面在引用中使用组的0-index:

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

这篇关于Terraform:基于 .tfvars 中的变量有条件地创建资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆