Terraform continued
-
Loops:
-
Loops with the count parameter:
- Basic psudeo code
for(i=0; i<3 ; i++) { resource "" "" { } }- Refer Here for the changeset to create 3 subnets by using count property
-
Terraform has lot of inbuilt functions. Lets try to use the length function to make our count dynamic
-
Made use of length and create 3 more subnets by changing variable values in values.tfvars file Refer Here
-
Terraform has inbuilt functions for ip address. In this example we are using cidrsubnet function to calculate subnet range Refer Here for the changes
-
-
Architecture realized so far

-
So we need to add the following to the aws architecture
-
Add internet gateway and attach it to the vpc
-
For manual steps watch recording

-
Apply terraform changes to add internet gateway Refer Here

-
-
Now lets create a public route table i.e. route to internet gateway and associate this with web subnets. Refer Here for the subnet associations to the public route table and routes
-
Exercise: Create a private route table with associations to other subnets

-
Lets create a ec2 instance in the public web subnet
- To create ec2 instance we need a security group
- Then create the ec2 instance as mentioned in the architecture

-
Refer Here for the changes done
-
Till now we were able to create a basic vm in aws vpc (network), so to be effective for enterprise needs we need to explore the following
- Effective usage of variables
- using terraform functions
- To be able to delete and recreate particular resources rather than deleting the whole resources
- How to create some reusable elements out of the work which we have done
- Explore Azure also
-
But before all of this lets deep dive on what happens when we apply resources in terraform.
Deep Dive into Terraform
-
Terraform workflow as an Individual
- Write – Author Infrastructure as code
- Plan – Preview the changes before applying
- Apply – Provision reproducable infrastructure
-
Terraform with in a team
- We follow the above steps
- When we create infrastructure using apply and some other colleague also tries to apply there should be only environment created.
-
Terraform apply always gives us the same result which is the desired state described in terraform configurations/template. This property is called as Idempotance
-
Terraform apply command is actually combination of two commands
terraform plan
terraform apply
- Terraform plan command shows the changes required to meet the desired state
- Plan will crosscheck your desired state with your destination environment (aws) and tells what has to done to accomplish/meet the desired state
- Lets create a plan
terraform plan -var-file="./values.tfvars" -out="ntier.plan".
- Now to create infrastructure we can execute
terraform apply "ntier.plan" - Now terraform creates the resources as per plan and creates some extra files

- So what are these state files.
