Terraform Infra Launch Using the Modules

main.tf file , we have all the modules reference to be created from the resources , that are in the diffrenet folders , according to the resource formation

In main.tf file , we have the modules , in which , we have -

  • one directory named as EC2 and created the ec2 module and variable in the same file to create the EC2 from the resourse

  • Second for the ELB and created the elb.tf file in that directory for the load balancer creation

  • Third directory named as pubsub, in this, we are creating the two subnets in different availability zone to attach the load balancer in it ,internet gateway , Route table, route table assosiation

  • EC2

image

It will create the ec2 resource using the source file ec2.tf (in the module folder), instance_type, image, key_pair, and subnet_id we have to mention in the module itself

ec2.tf

image

  • VPC

image

This module VPC is taking the resource refrence from the source , VPC and cidr_block is the required field in the VPC module

vpc.tf

image

  • Public Subnet

image

here , it is taking reference from the pubsub folder files for the creation of the two diffrent subnet in diffrenet availability zones

pubsub.tf

image

here, we are using the count function for creating the 2 different subnet. (count is to access the index in the list , as we have taken the variable for the elb az in "list" format)

  • output function in terraform

image

we have taken two output in the pub-sub block for the creation of 2 subnets, and can use this output in the main.tf file for the input

  • ELB

image

For the ELB , we have to create the Subnets in 2 diffrent AZs, so here, we are creating the ELB , taking reference from the ELB folder

elb.tf

image

creating target groups in it

  • All the file structure we can see in the tree structure in the image attached below, we can create the variable file seperately for the variables or we can mention in the same tf file as well

image

Note For the provider in terraform file , we have to create the secret and access key from the aws console and have to add the keys in the given directory as shown in the Image given below

image

And then, give the provider as shown in the below image in the main.tf file

image

Terraform state lock file

image

  • Why do we need State locking and what is it ?

If the state file is stored remotely so that many people can access it, then you risk multiple people attempting to make changes to the same file at the exact same time. So we need to provide a mechanism that will “lock” the state if its currently in-use by another user. We can accomplish this by creating a dynamoDB table for terraform to use.

  • create the s3 backend resource -

image

then create a backend association like this -

image

  • Create the dynamoDB table and modified the Terraform S3 backend resource and add in the dynamoDB table -

image