Terraform Classroom Series – 21/Sep/2019

Reusability in Terraform using Modules

  • Module: Reusable Terraform script/template is called as module
  • Things to know:
    • Module is nothing but organizing the same terraform script in a bit different
    • We have sample architecture terraform script. Now i want to convert that to module
    • Like all the components of Terraform. Module also has arguments & attributes
    • varaibles become arguments
    • outputs become attributes
    • In the calling script you will import module
    • There are many modules which you can use. These modules are available in Terraform Registry Refer.


Lets use aws-vpc module from terraform registry

  • Refer for documentation
  • module syntax in terraform
module "<module name>" {
    source = "<module location>"
    arg1  = value1
    argn = valuen

Refer the below sample usage of module

variable "accesskey" {
    type = "string"

# required variable secretkey
variable "secretkey" {
    type = "string"

# optional region
variable "region" {
    type = "string"
    default = "eu-west-3"

provider "aws" {
   region       = "${var.region}"
   access_key   = "${var.accesskey}"
   secret_key   = "${var.secretkey}"

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"
  name = "my-vpc"
  cidr = ""

  azs             = ["eu-west-3a", "eu-west-3b", "eu-west-3c"]
  private_subnets = ["", "", ""]
  public_subnets  = ["", "", ""]

  tags = {
    Terraform = "true"
    Environment = "dev"
    Name = "module demo"

output "vpcid" {
  value = "${module.vpc.vpc_id}"

How to Create Module

  1. Lets refactor simple architecture.

  2. Ensure all the variables are written in a file called as variables.tf (Recomendation)

  3. Ensuare all the outputs are written in a file called as outputs.tf (Recomended)

  4. whenever you are using local modules try to use the following directory structure ==> Terraform Script => Modules <Modulename> main.tf variables.tf outputs.tf

  5. Refer here for the whole template usage

Multi User Scenarios


As mentioned in the above images we need to solve this problem.

Why this problem

  • Whenever terraform apply command is executed, a state file gets created.
  • Default location of state file is current directory

Possible Solution

  • Try to store state file in common location which is accessible to both
  • This is called as backend Refer

What about backend with multiple Environments

  • Solution to this is Terraform Workspace

Azure Provider

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner