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.

Preview

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 = "10.0.0.0/16"

  azs             = ["eu-west-3a", "eu-west-3b", "eu-west-3c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  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

Preview

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