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

    Proudly Powered by Zim 0.75.2.

    Template by Etienne Gandrille, based on ZeroFiveEight and using JQuery Toc Plugin.