CloudFront Conditional Custom Error Response

I am using TF 0.11.14 to manage the Cloud Front Distributions of multiple environments for our applications.

I would like to make a change on certain CF distribution and only want add Custom Error Response if the given variable is exists in variables.tf file

I am wondering how can I do that ?

Below is the variable I have defined in my variables.tf file

variable "spa" {
  type        = "string"
  default     = ""
  description = "if spa is enable, Cloudfront will have the routing of the custom pages/endpoints in  client by modifying the Error Pages"
}

Below is the TF configs I have tried.

I have tried to put the count to enable/disable the resource for custom_error_response only however that is failing with the following error.

  custom_error_response = {
        count                 = "${var.spa == "enable" ?1:0 }"
        error_caching_min_ttl = 0
        error_code            = 404
        response_code         = 200
        response_page_path    = "index.html"
      }
    }

module.nightly-client.aws_cloudfront_distribution.cf: custom_error_response.0: invalid or unknown key: count

I have also tried the following way by enabling each sub resources of custom_error_response

  custom_error_response = {
    error_caching_min_ttl = "${var.spa == "enable" ? 0:0 }"
    error_code            = "${var.spa == "enable"? 404:0}"
    response_code         = "${var.spa == "enable" ? 200:0}"
    response_page_path    = "${var.spa == "enable" ? "/index.html":""}"
  }
}

The above doesn’t work and errors out because http code for the false evaluation is not valid.

  • aws_cloudfront_distribution.cf: error updating CloudFront Distribution (E2WYMYBXQLZC0Z): InvalidArgument: The parameter ErrorCode is invalid.
    status code: 400, request id: 61cabc92-6aee-44c8-ba4d-e7ff619682ac