Shai Hirsch
Shai Hirsch

Reputation: 11

How can I define aws resource tags in terraform conditionally?

I would like to define resource tags (e.g., for a DynamoDB table) only in certain environments, but not all.

I am familiar with count trick: setting the count to 0 so that a resource will not get created. But this is a field within a resource.

tags {
    count = "${var.is_production == "T" ? 1 : 0}"
    MyProductionOnlyTag = "${var.prod_tag_value}"
}

Upvotes: 1

Views: 2681

Answers (1)

cfelipe
cfelipe

Reputation: 350

A bit hacky, but you could use dynamic blocks (requires terraform => 0.12):

dynamic "tags" {
  iterator = my_prod_tag_value
  for_each = "${var.my_prod_tag == null ? 0 : 1 }"
  content {
    MyProductionOnlyTag = "${my_prod_tag_value}"
  }
}

Also, when declaring var.my_prod_tag, you must explicitly allow it to be null:

variable "my_prod_tag" {
    type = "string"
    default = null
}

Upvotes: 1

Related Questions