« Back to Index

Fastly: Terraform Multiple Environments using Modules

View original Gist on GitHub

Tags: #terraform #environments #hcl #fastly

1. README.md

Terraform Environments using Modules

.
├── modules
│   ├── service-compute
│   │   ├── main.tf
│   │   ├── package-built-locally-via-cli.tar.gz
│   │   ├── provider.tf
│   │   └── variables.tf
│   └── service-vcl
│       ├── main.tf
│       ├── provider.tf
│       ├── variables.tf
│       └── vcl
│           └── main.vcl
├── prod
│   ├── inputs.tfvars
│   ├── main.tf
│   ├── provider.tf
│   └── variables.tf
└── stage
    ├── inputs.tfvars
    ├── main.tf
    ├── provider.tf
    └── variables.tf

Within each directory (prod and stage) run terraform init.

Then inside each directory run terraform plan -var-file="inputs.tfvars".

NOTE: I don’t show the contents for every file as most are the same as others. For example, provider.tf is the same across all directories. The stage and prod directories are all the same with the exception of the inputs.tfvars (e.g. I use the default variable value in prod, where I provide my own value for the variable in stage) and the variables.tf (where I set different default values for each environment).

2. modules - service-compute - main.tf

resource "fastly_service_compute" "service" {
  name = "Compute Service"

  domain {
    name = "${var.subdomain}-compute.example.com"
  }

  package {
    filename         = "${path.module}/package-built-locally-via-cli.tar.gz"
    source_code_hash = filesha512("${path.module}/package-built-locally-via-cli.tar.gz")
  }

  backend {
    address = "httpbin.org"
    name    = "httpbin"
  }

  force_destroy = true
}

3. modules - service-compute,service-vcl - variables.tf

variable "subdomain" {
  type = string
}

4. modules - service-vcl - main.tf

resource "fastly_service_v1" "service" {
  name = "Example Service"

  domain {
    name = "${var.subdomain}.example.com"
  }

  backend {
    address = "httpbin.org"
    name    = "httpbin"
  }

  vcl {
    content = file("${path.module}/vcl/main.vcl")
    main    = true
    name    = "custom_vcl"
  }

  force_destroy = true
}

5. stage - inputs.tfvars

subdomain = "staging"

6. stage - main.tf

module "www" {
  source    = "../modules/service-vcl"
  subdomain = var.subdomain
}

module "compute" {
  source    = "../modules/service-compute"
  subdomain = var.subdomain
}

7. stage - provider.tf

terraform {
  required_providers {
    fastly = {
      source  = "fastly/fastly"
      version = "0.27.0"
    }
  }
}

8. stage - variables.tf

variable "subdomain" {
  type    = string
  default = "stage"
}

9. prod - variables.tf

variable "subdomain" {
  type    = string
  default = "www"
}