07. Modules
Contents
Way to organize source code, allowing reusability.
Module sources
See: Module Sources
# On the Terraform registry repo
module "myVpc1" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2"
}
# On a Git repository 'git::https://' or 'git::ssh://'
# 'ref' can reference a tag name, a hash or a branch
module "myVpc2" {
source = "git::https://corporate-gitlab.com/tf-aws-vpc.git?ref=v1.2.0"
}
# Local module ALWAYS starts with './' or '../'
module "instance1" {
source = "./module-ec2"
}
→ A lot of sources can be used, such as S3 (s3::https://), GCS buckets (gcs::https://), GitHub (github.com/...),...
Key points
A module can be instantiated several times, with a different module instance name
module "myVpc1" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2"
}
module "myVpc2" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2"
}
Parameters can be provided to a module instance. They are mapped to the module variables
module "myVpc1" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.2"
# input variables
var1 = "val1"
var2 = "val2"
}
A module can send informations back to its caller using output
# inside the module
output "foo_name" {
description = "Name of ssth"
value = my_object.name
}
# inside the caller
module "module_instance1" {
source = "../module/my_module"
}
# later, use module.module_instance1.foo_name
Standard module structure
See: Module structure
$ tree minimal-module/ . ├── README.md ├── main.tf ├── variables.tf ├── outputs.tf
$ tree complete-module/ . ├── README.md ├── main.tf ├── variables.tf ├── outputs.tf ├── ... ├── modules/ │ ├── nestedA/ │ │ ├── README.md │ │ ├── variables.tf │ │ ├── main.tf │ │ ├── outputs.tf │ ├── nestedB/ │ ├── .../ ├── examples/ │ ├── exampleA/ │ │ ├── main.tf │ ├── exampleB/ │ ├── .../
Terraform registry
See: https://registry.terraform.io/browse/modules
Requirements for Publishing Module
- GitHub: The module must be on GitHub and must be a public repo. This is only a requirement for the public registry.
- Named: Module repositories must use this three-part name format terraform-<PROVIDER>-<NAME>
- Repository description: The GitHub repository description is used to populate the short description of the module.
- Standard module structure: The module must adhere to the standard module structure.
- x.y.z tags for releases: The registry uses tags to identify module versions. Release tag names must be a semantic version, which can optionally be prefixed with a v. For example, v1.0.4 or 0.9.2