The module resource allows you to package pieces of configuration and reference them in other configuration and resources. Modules can be referenced from the local file system or remotely.
All resources contained within a module are scoped to the name of the containing module. For example, if a module mine contains a kubernetes cluster called dev then the FQRN (fully qualified resource name), and the name within docker would be server.dev.mine.kubernetes-cluster.local.jmpd.in.
Modules can also contain modules, to ensure that resouce references are unique resources always take on the name of their module including any parent modules.
For example, if a module mine contains a kubernetes cluster called dev that was contained in module parent. Then the FQRN and the name within docker would be server.dev.parent.mine.kubernetes-cluster.local.jmpd.in.
The following example shows how a module can be used multiple times.
resource "network" "cloud" { subnet ="10.5.0.0/16"}module "consul_dc1" { source ="./module_k3s" variables = { network_id = resource.network.cloud.meta.id consul_port =18500 }}module "consul_dc2" {// CI has limited resources, add a manual dependency to ensure that only one module// is created at once depends_on = ["module.consul_dc1"] source ="./module_k3s" variables = { network_id = resource.network.cloud.meta.id consul_port =18501 }}output "dc1_addr" { value = module.consul_dc1.output.consul_http_addr}output "dc2_addr" { value = module.consul_dc2.output.consul_http_addr}
When creating a module, variable resources are used to define input variables for the module, and output resources are used to define outputs of the module.
variable "network_id" { default =""}variable "network_subnet" { description ="This should only be set if variable.network_id is not set" default ="10.0.10.0/24"}variable "website_path" { description ="This must be specified" default =""}resource "network" "main" { disabled = variable.network_id !="" subnet = variable.network_subnet}local "network_id" { value = variable.network_id ==""? resource.network.main.meta.id : variable.network_id}resource "container" "webserver" {image { name ="nginx" }network { id = local.network_id }volume { source = variable.website_path destination ="/usr/share/nginx/html" }port { local =80 host =80 }}output "webserver_address" { value ="http://${resource.container.webserver.container_name}:${resource.container.webserver.port.0.host}"}
The following example shows how to use the module and override the variables and use the outputs in other resources.