代码之家  ›  专栏  ›  技术社区  ›  Jatin Mehrotra

Terraform命令行参数不适用于条件表达式

  •  0
  • Jatin Mehrotra  · 技术社区  · 4 年前

    我试图根据变量使用条件表达式将资源块部署到dev或prod中,为此我尝试使用命令行参数。 这适用于terraform.tfvars,但不适用于CMD参数,这意味着当我试图运行 terraform plan 它没有任何其他变化。

    理想情况下应该添加1个实例。

    这是我的资源块

    main.tf文件

    resource "aws_instance" "dev" {
    
      ami           = "ami-0ca285d4c2cda3300"
      instance_type = var.instanceType
      count         = var.istest == true ? 1 : 0
    }
    
    resource "aws_instance" "prod" {
    
      ami           = "ami-0ca285d4c2cda3300"
      instance_type = "t2.micro"
      count         = var.istest == false ? 1 : 0
    }
    

    变量.tf

    variable "istest" {
      default = true
    }
    

    terraform。tf vars为空,运行terraform的命令

    terraform plan -var="istest=false"
    
    0 回复  |  直到 4 年前
        1
  •  3
  •   Tolis Gerodimos    4 年前

    我建议使用以下语法,而不是检查文字 true false 价值

    resource "aws_instance" "dev" {
    
      ami           = "ami-0ca285d4c2cda3300"
      instance_type = var.instanceType
      count         = var.istest ? 1 : 0
    }
    
    resource "aws_instance" "prod" {
    
      ami           = "ami-0ca285d4c2cda3300"
      instance_type = "t2.micro"
      count         = var.istest ? 0 : 1
    }
    

    如果istest变量为 真的 它将部署 dev 例子

    如果是 虚假的 它将创建 prod 例子

    尝试

    terraform plan -var="istest=false"
    

    更新

    核心问题似乎是terraform执行类型转换

    引用自: https://www.terraform.io/language/expressions/type-constraints#conversion-of-primitive-types

    Terraform语言将 automatically convert number and bool values to string values when needed ,反之亦然,只要 字符串包含数字或布尔值的有效表示形式。

    true converts to "true", and vice-versa false converts to "false"

    因此,您应该显式设置 type

    在您的 variables.tf 文件

    variable "istest" {
      default = true
      type    = bool
    }
    

    那么它应该按预期工作

    地形图-var=“istest=false”