UP | HOME
Land of Lisp

Zhao Wei

How can man die better than facing fearful odds, for the ashes of his fathers and the temples of his Gods? -- By Horatius.

Terraform Note

1. Terraform module

  • Any set of Terraform configuration files in a folder is a module.
  • Different from regular Terraform .tf file, the provider is removed since providers should be configured by the user of the module and not by the module itself.
  • Syntax of using module

    module "<NAME>" {
      source = "<SOURCE>"
      [CONFIG ...]
    }
    
  • Example:
    • a module that is responsible for creating EC2 cluster

      zw@zw-dev:~/code/terraform-projects/intro-to-terraform/modules$ tree .
      .
      └── services
          └── webserver-cluster
              ├── main.tf
              ├── outputs.tf
              └── variables.tf
      
      2 directories, 3 files
      
    • You can create a new file in stage/services/webserver-cluster/main.tf and use the webserver-cluster module in it as follow:

      provider "aws" {
        region = "us-east-2"
      }
      module "webserver_cluster" {
        source = "<path>/modules/services/webserver-cluster"
      }
      
      • Notice the source specifies the folder contains the .tf files.
      • The module will be refered will be webserver_cluster.

1.1. Module inputs

  • As function in general programming language which has input variables, you can add input parameters in Terraform.
  • First, define variables in modules, such as cluster_name

    variable "cluster_name" {
      description = "The name to use for all the cluster resources"
      type        = string
    }
    
  • Second, set the new input variable accordingly

    module "webserver_cluster" {
      source = "<path>/modules/services/webserver-cluster"
      cluster_name = "webservers-prod"
    }
    
    • When use the module, we configure the cluster_name.

1.2. Module output

  • First, define output in modules,
  • Second, refer the output as same as refering resources outputs

    # module.<MODULE_NAME>.<OUTPUT_NAME>
    autoscaling_group_name = module.webserver_cluster.asg_name
    
  • (optinal), you could “pass through” output

    output "clb_dns_name" {
      value       = module.webserver_cluster.clb_dns_name
      description = "The domain name of the load balancer"
    }
    
  • The clb_dns_name is the output from module webserver_cluster and it is passed through from its usages place.