【问题标题】:Is there a condition in terraform same as CloudFormation?terraform 中是否有与 CloudFormation 相同的条件?
【发布时间】:2022-11-11 06:34:15
【问题描述】:

我看到人们使用 count 来阻止在 terraform 中创建资源。如果条件设置为真,我想创建一些资源。有没有和CloudFormation一样的东西?

【问题讨论】:

  • 有条件,但你必须表明你想用它们做什么。

标签: terraform


【解决方案1】:

你自己回答,最相似的是count

您可以将它与条件表达式, 喜欢

resource "x" "y"{
  count = var.tag == "to_deploy" ? 1 : 0
}

但这只是一个愚蠢的例子,你可以放任何东西,也可以使用函数

count = max(var.array) >= 3 ? 1 : 0

如果您需要对更复杂的事物设置条件,您可以评估以使用 locals 块来完成您需要的所有详细说明,并且只需使用一些 bool 或您想要的,从条件表达式中产生。

我想帮助你更多,但我应该知道你的具体情况,你会有什么条件。

【讨论】:

    【解决方案2】:

    在 CloudFormation 中,“条件”是与资源、输出、映射等一起的顶级对象类型。

    Terraform 语言采用了一种稍微更通用的方法,即仅具有各种数据类型的值,使用表达式组合和转换它们。因此,没有完全等同于 CloudFormation 的“条件”的概念,但您可以使用 Terraform 以其他方式实现类似的效果。

    例如,如果您只想在一个地方对决策规则进行编码,然后多次引用它,那么您可以定义一个布尔类型的Local Value,然后从多个resource 块中引用它。在撰写本文时,您链接到的 CloudFormation 文档页面有一个名为“简单条件”的示例,以下是该示例在 Terraform 语言中的大致等效版本:

    variable "environment_type" {
      type = string
    
      validation {
        condition     = contains(["prod", "test"], var.environment_type)
        error_message = "Must be either 'prod' or 'test'."
      }
    }
    
    locals {
      create_prod_resources = (var.environment_type == "prod")
    }
    
    resource "aws_instance" "example" {
      ami           = "ami-0ff8a91507f77f867"
      instance_type = "..."
    }
    
    resource "aws_ebs_volume" "example" {
      count = local.create_prod_resources ? 1 : 0
    
      availability_zone = aws_instance.example.availability_zone
    }
    
    resource "aws_volume_attachment" "example" {
      count = local.create_prod_resources ? 1 : 0
    
      volume_id   = aws_ebs_volume.example[count.index].id
      instance_id = aws_instance.example.id
      device      = "/dev/sdh"
    }
    

    两个不同的resource 块都可以引用local.create_prod_resources,就像CloudFormation 示例中MountPointNewVolume 两个资源可以引用共享条件CreateProdResources 一样。

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 2017-09-02
      • 2019-08-22
      • 2020-12-13
      • 2022-06-28
      • 2017-01-21
      • 2018-08-20
      • 1970-01-01
      相关资源
      最近更新 更多