How to conditionally include a resource in terraform

1 min read | by Jordi Prats

On terraform modules sometimes it make sense to completely get rid of some resources using some condition. Since we don't have an if statement, we can use count instead

To make it easy to follow, we are going to assume we have an boolean input variable, but obviously you can use any condition or local variable in the same way

variable "enable_kube_prometheus_stack" {
  type        = bool
  description = "Controls the deployment of kube-prometheus-stack"
  default     = true

On the resource we want to enable or disable we will have to set the count option to 1 when we want to have the resource or to 0 if we want it to be removed:

module "kube-prometheus-stack" {
  count = var.enable_kube_prometheus_stack ? 1 : 0
  source = "./modules/kube-prometheus-stack"

  namespace = var.namespace

Posted on 27/01/2021