Terraform:如何从插值中获取布尔值?

时间:2018-12-11 15:29:36

标签: terraform

我想对prevent_destroy元参数使用内插值

我编码时

lifecycle {
   # never destroy the IP address of the production stage,
   prevent_destroy = "${var.stage_name == "global" ? true : false }"
}

我知道

* cannot parse 'prevent_destroy' as bool: strconv.ParseBool: parsing "${var.stage_name == \"global\" ? true : false }": invalid syntax

等效错误

lifecycle {
    prevent_destroy = "${var.stage_name == "global" ? 1 : 0 }"
}

当我定义本地定义时

locals  {
  booltest = "${var.stage_name == "global" ? true : false }"
}

似乎可以解决,但指的是本地

lifecycle {
    prevent_destroy = "${var.booltest}"
}

给我一​​个

* cannot parse 'prevent_destroy' as bool: strconv.ParseBool: parsing "${var.booltest}": invalid syntax

(也尝试使用0和1)

该怎么编码?我的版本是Terraform v0.11.10

1 个答案:

答案 0 :(得分:3)

不幸的是,生命周期属性不支持插值:

https://github.com/hashicorp/terraform/issues/3116 https://github.com/hashicorp/terraform/issues/17294

但是,您可以使用count解决此问题。大概是:

resource "aws_instance" "indestructible" {
  count = "${var.prevent_destroy ? "1" : "0"}"
  lifecycle {
    prevent_destroy = "true"
  }
  ...
}

resource "aws_instance" "destructible" {
  count = "${var.prevent_destroy ? "0" : "1"}"
  lifecycle {
    prevent_destroy = "false"
  }

  ...
}

我个人会在环境之间使用相同的prevent_destroy设置,并在需要时明确销毁它们。