Skip to content

Instantly share code, notes, and snippets.

@hrmsk66
Created July 17, 2024 00:35
Show Gist options
  • Save hrmsk66/9f26835ecc013187aa7532917eac4fe8 to your computer and use it in GitHub Desktop.
Save hrmsk66/9f26835ecc013187aa7532917eac4fe8 to your computer and use it in GitHub Desktop.

Patterns for Writing Environment-Specific TF Configurations

Here are some patterns for writing environment-specific settings within TF modules used across all environments.

Pattern-A: Applying Snippet Only in Specific 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
    }
  }

Pattern-B: Applying Different Snippets in Each Environment

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

Pattern-C: Different Settings in Each Environment

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
  }

Pattern-D: Templating Snippets

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}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment