Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform: How to get a boolean from interpolation?

Tags:

terraform

I want to use an interpolated value for the prevent_destroy meta-parameter

When I code

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

I get

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

Equivalent error for

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

When I define a local the definition

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

seems to go through, but referring to the local

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

gives me a

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

(also tried with 0 and 1)

How can this be coded? My version is Terraform v0.11.10

like image 911
Uwe Geuder Avatar asked Dec 11 '18 15:12

Uwe Geuder


1 Answers

Unfortunately lifecycle attributes do not support interpolation:

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

However, using count you may work around this. Roughly:

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

  ...
}

Personally I would use the same prevent_destroy setting between environments and destroy them explicitly when needed.

like image 147
bkconrad Avatar answered Oct 13 '22 05:10

bkconrad