« Back to Index

Terraform: Modules

View original Gist on GitHub

Tags: #terraform #tf #modules

Terraform Modules.md

To use modules they must abide by the following directory structure:

.
├── modules
│   └── your_module_name_here
│       └── whatever_you_want_to_call_this.tf
│       └── outputs.tf
├── outputs.tf
├── service.tf

NOTE: multiple outputs.tf files. We’ll demonstrate below how to reference a module’s output variable from within our ‘root’ module (i.e. service.tf) .

You would then consume the module from within your root module like so:

module "foo" {
  source = "./modules/your_module_name_here"
  some_input_variable = "example"
}

The module itself would look like so:

// providers must be set in every module (not just the root module)
terraform {
  required_providers {
    fastly = {
      source  = "fastly/fastly"
      version = "0.25.0"
    }
  }
}

variable "some_input_variable" {
  type        = string
  description = "Some sort of value"
}

resource "fastly_service_v1" "test_service" {
  name = "testing_tf_modules"
  domain {
    name = "tfmodules-${var.some_input_variable}.integralist-test.com"
  }
  backend {
    address = "httpbin.org"
    name    = "httpbin"
  }
  force_destroy = true
}

The module’s outputs.tf would look like:

output "active" {
  value = fastly_service_v1.test_service_foo.active_version
}

While the root module’s outputs.tf would look like:

output "active" {
  value = fastly_service_v1.test_service.active_version
}

output "active_foo" {
  value = module.foo.active
}

Notice the syntax to reference the module’s output variable from within the root module: module.<module_name>.<module_output_variable_name>.