Here are some patterns for writing environment-specific settings within TF modules used across all environments.
This is an example of creating a VCL snippet only when var.isProd is true. The number 1
in var.isProd ? [1] : []
has no specific meaning. The key point is passing a list with one element to for_each when true.
dynamic "snippet" {
for_each = var.isProd ? [1] : []
content {
content = file("${path.module}/vcl/recv_prod.vcl")
name = "snippet for prod"
type = "recv"
priority = 100
}
}
The if-else logic can be written as follows, similar to pattern A:
dynamic "snippet" {
for_each = var.isProd ? [1] : []
content {
content = file("${path.module}/vcl/recv_prod.vcl")
name = "snippet for prod"
type = "recv"
priority = 100
}
}
dynamic "snippet" {
for_each = var.isProd ? [] : [1]
content {
content = file("${path.module}/vcl/recv_stage.vcl")
name = "snippet for stage"
type = "recv"
priority = 100
}
}
The same logic as B can be written as follows:
snippet {
content = var.isProd ? file("${path.module}/vcl/recv_prod.vcl") : file("${path.module}/vcl/recv_stage.vcl")
name = "conditional snippet"
type = "recv"
priority = 100
}
For cases where only part of the snippet content differs by environment, using the templatefile function might be a good approach:
snippet {
content = templatefile("${path.module}/vcl/deliver_set_header.vcl", { header_value = var.header_value })
name = "set env specific header value in deliver"
type = "deliver"
priority = 100
}
Here, we're embedding the header_value variable into the VCL file:
if (req.http.fastly-debug) {
set resp.http.fastly-debug-env = "${header_value}";
}