Terraform Mastering Infra Code Code
Terraform Mastering Infra Code Code
Subhabrata Panda |1
ABOUT ME
I am Subhabrata Panda, a passionate DevOps and Cloud Enthusiast, with a strong foundation in Terraform,
AWS, and cutting-edge cloud technologies.I have consistently demonstrated expertise in deploying scalable,
secure, and efficient infrastructure solutions.
With hands-on experience implementing Infrastructure as Code (IaC) using Terraform, I have successfully
worked on projects that include building secure CI/CD pipelines, managing multi-tier applications, and
optimizing cloud deployments.
This e-book reflects my commitment to making complex infrastructure concepts accessible and actionable.
Whether you are a beginner or an experienced professional, my goal is to provide you with the tools and insights
needed to excel in modern cloud-based DevOps practices.
Subhabrata Panda |2
INDEX
1. PREREQUISITES 7
2. INTRODUCTION 7
3. IAC – INFRASTRUCTURE AS CODE 9
4. I N S TA L L T E R R A F O R M O N W I N D O W S 10
5. I N S TA L L T E R R A F O R M O N M A C / U B U N T U 12
6. CHOOSE THE PROVIDER 13
7. S E T U P AW S A C C O U N T 14
8. AWS DA S H B OA R D 16
9. AWS U S ER S E T UP 17
1 0 . D O W N L O A D AW S O N W I N D O W S 21
1 1 . A W S C L I C O N F I G U R AT I O N F O R V S C O D E 23
1 2 . AWS EC 2 W I T H T ER R A F OR M 26
11.1 AMI
11.2 terraform plan
11.3 terraform apply
11.4 terraform destroy
11.5 terraform destroy -auto—approve
11.6 terraform validate
13. RESOURCE CHANGE 33
1 4 . VA R I A B L E S I N T E R R A F O R M 34
13.1 Syntax
15. OUTPUT IN TERRAFORM 36
16. IMPLEMENT S3 BUCKET WITH THE HELP OF TERRAFORM 37
15.1 Introduction of S3 Bucket
Subhabrata Panda |3
17. RANDOM PROVIDER 40
16.1 Syntax
1 8 . T E R R A F O R M R E M O T E S TAT E M A N A G E M E N T 43
17.1 Keypoints
17.2 Syntax
1 9 . P R O J E C T 1 - D E P L O Y S TAT I C W E B S I T E O N AW S U S I N G S 3 45
BUCKET
18. 1 Reference
1 8 . 2 Wo r k i n g
2 0 . U N D E R S TA N D V P C F O R T E R R A F O R M I M P L E M E N TAT I O N 48
19.1 VPC CIDR Block
19.2 Internet Gateway
19.3 Route Tables
19.4 Security Target Groups
19.5 NACL
19.6 Subnets
19.7 NAT Gateway
19.8 AWS Peering
19.9 Route 53
21. IMPLEMENTING VPC USING TERRAFORM 54
20.1 Introduction
2 2 . D ATA R E S O U R C E 59
21.1 Real Life Scenario
2 3 . C R E AT E E C 2 U S I N G E X I S T I N G V P C 63
Subhabrata Panda |4
2 4 . T E R R A F O R M VA R I A B L E S 64
23.1 Real Life Scenario
23.2 Problem without Validation
23.3 Use of map
23.4 Use of flattern
23.5 Use of lookup
23.6 Environment Variables
23.7 terraform.tfvars
23.8 terraform.auto.tfvars
23.9 Diagram
2 5 . L O C A L VA R I A B L E S I N T E R R A F O R M 73
24.1 Feature
2 6 . T E R R A F O R M : O P E R AT I O N S & E X P R E S S I O N S 74
27. TERRAFORM: FUNCTIONS 75
2 8 . T E R R A F O R M : M U LT I P L E R E S O U R C E S 81
27.1 count
27.2 count.index
27.2 for_each
2 9 . P R O J E C T 2 – AW S I A M M A N A G E M E N T 91
28.1 Introduction
30. TERRAFORM MODULES 101
29.1 Real Life Scenario
29.2 Without the use of modules
29.3 With the use of module
29.4 Implementing VPC using Terraform Module
29.5 Implementing EC2 using Terraform Module
29.6 Building Terraform Module
3 1 . P R E PA R E M O D U L E S T O P U B L I S H 115
Subhabrata Panda |5
32. TERRAFORM DEPENDENCIES 123
33. T ERRA FORM L IFECYCL E 125
32.1 create_before_destroy
32.2 prevent_destroy
32.3 ignore_destroy
32.4 replace_triggered_by
3 4 . P R E & P O S T C O N D I T I O N R E S O U R C E S VA L I D AT I O N S 130
33.1 Syntax for precondition
33.2 Syntax for postcondition
33.3 Examples
33.4 Combined example of precondition and postcondiotn
3 5 . T E R R A F O R M S TAT E M O D I F I C AT I O N S 133
34.1 terraform state list
34.2 terraform state show
34.3 terraform state mv
34.4 terraform state rm
34.5 terraform state pull
34.6 terraform state push
34.7 terraform state
36. TERRAFORM IMPORT COMMANDS 136
3 7 . T E R R A F O R M W O R K S PA C E S 138
35.1 Uses
35.2 Working
35.3 Diagram
38. TERRAFORM CLOUD WITH GITHUB 141
Subhabrata Panda |6
PREREQUISITES
• Must have knowledge of AWS Cloud.
INTRODUCTION
In this book/pdf we will learn all the basic to advance of
the TERRAFORM tool that is mainly used in Devops with
the help of AWS cloud and VS Code editor or Cursor.
Subhabrata Panda |7
TERRAFORM
Subhabrata Panda |8
Terraform is an open-source infrastructure as a code (IAC) tool,
written in HCL (Hashicorp Config Language) format, which has State
Management feature (terraform.tfstate)where it maintained a detailed
recodes of current state of managed resources.
3. IAC
Tools allow you to manage infrastructure with configuration files rather
than through a graphical user interface.
E.g.
→ You want to host the EC2 instance in AWS cloud, normally what we
will do is to go to
→ dashboard
→setup up the instance step by step graphically
Rather than doing the graphically, write the simply configuration file
that contains the details like
→ to host the instance
→ which os is required
→ what all resources is required for the instance
Then will simply execute the file, then IAC will automatically do all the
things you asked for.
Subhabrata Panda |9
4. INSTALLATION ON TERRAFORM ON WINDOWS
Scroll Down and search for windows section and download binary of
terraform
Subhabrata Panda | 10
Click on “Environment Variables”
Subhabrata Panda | 11
INSTALLATION ON TERRAFORM ON
5. MAC/UBUNTU
MAC
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
LINUX
Ubuntu/Debian
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --
dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-
by=/usr/share/keyrings/hashicorp-archive-keyring.gpg]
CentOS/RHEL
sudo yum install -y yum-utils
Amazon Linux
sudo yum install -y yum-utils shadow-utils
Subhabrata Panda | 12
6. CHOOSE THE PROVIDER
Subhabrata Panda | 13
7. SETUP AWS ACCOUNT
Go to this account
Fill all the details that the page is asking, all the details must be legal
And at the end it will cost 1USD for verification which will be returned
automatically.
STEP-1 STEP-2
STEP-3 STEP-4
Subhabrata Panda | 14
STEP-5 STEP-6
Select the basic support If this page shows, then you are
good to go
STEP-7
And you will also get the mail
something like this
Subhabrata Panda | 15
8. A W S D A S H B O A R D
Subhabrata Panda |
16
9. A W S U S E R S E T U P
Go to search bar of AWS and type IAM you will see the dashboard
something like this
Now click on “User” → Give the User name → And Click on “Next”
Subhabrata Panda |
17
Tick on “Provide user access AWS Management console”
→Then tick on “I want to create an IAM user”
→Now Tick and Give the “Custom password”
→For now, untick “User must create a new password at next sign-in”
→ And click on “Next”
Subhabrata Panda |
18
Next this page will appear
STEP -1 STEP-2
This icon will appear →Give the 12digit account
Subhabrata Panda | 20
10. D O W N L O A D I N G A W S C L I O N W I N D O W S
Subhabrata Panda | 21
Just do next→next→ Accept the License Agreement→next→ install
If you see this screen means you have successfully installed the aws cli.
Now, we can access AWS cloud platform from a local environment.
Subhabrata Panda | 22
11. A W S C L I C O N F I G U R E I N V S C O D E
Support to check something from the VS code terminal i.e. what all
users that have created we type
Subhabrata Panda | 23
NOTE:: - It’s not an error it’s because I have deleted my user manually from
AWS IAM service
Other reasons
→ Invalid or Expired Credentials
→ Incorrect AWS Profile
→ Session Token Expiration (If using MFA)
1.Go to aws cloud and search for IAM service and left-click on tf-user
Subhabrata Panda | 24
Tick on
Fill up only “Access key & Secret Access key” and rest all skip by doing
“enter”
Finally, your AWS cloud and local machine has related to each other
with the help of vs code.
Subhabrata Panda | 25
12. A W S E C 2 W I T H T E R R A F O R M
code
Now create the Folder name “AWS” inside then create ec2-instance
folder then create main.tf file
Now decide which provider you will be working on as for me it’s “AWS”
Subhabrata Panda | 26
You will see
Now copy all the code that is present under “How to use the provider”
on “main.tf”
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.75.1"
}
}
}
provider "aws" {
# Configuration options
}
Subhabrata Panda | 27
You can change any name with aws like zxd but for readable purpose
we use aws, the only thing that is important is
source = "hashicorp/aws"
version = "5.75.1"
First, you need to specify the region where you will be working.
region= “us-east-1”
provider "aws" {
# Configuration options
region = "us-east-1"
}
Now you need to add all the necessary requirements to start the
instance like
“ami”, “instance_type”
Subhabrata Panda | 28
Ami → Amazon Machine Image (AMI) is a pre-configured template
that contains the operating system, application server, and applications
needed to launch an instance in Amazon Elastic Compute Cloud
(EC2).
Subhabrata Panda | 29
You will see this
Select the desired operating system copy the ami id that is marked with
rectangle to add it in terraform.
Steps to check which instance did you need for your project
Subhabrata Panda | 30
You will notice Instance type
Now that you have learned both about AMI ID and Instance Type
implement it on terraform in resources
tags = {
Name = "Myec2"
}
}
IMPORTANT
Subhabrata Panda | 31
Before applying terraform init After applying terraform init
if you have done yes, then it will create your based on given instances,
to check go to aws console to verify that
Subhabrata Panda | 32
13. RESOURCE CHANGE
Run terraform plan: This will show you the changes Terraform intends
to make, including the update to the EC2 instance type.
Run terraform apply: This will apply the changes and update the EC2
instance to the new instance type.
After running terraform apply, you can check the AWS EC2 Console
to verify that the instance type has been updated from t2.micro to
t3.micro.
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 33
14. VARIABLES IN TERRAFORM
Syntax:
variable "variable_name" {
type = string # Type: string, number, bool, list, map, etc.
default = "value" # Optional default value
description = "Description of the variable"
}
"variable_name" can be your any desire name
It’s the best practice to create another files name “variables.tf” to store
all the variables in one place
e.g.
Subhabrata Panda | 34
main.tf variables.tf
Subhabrata Panda | 35
15. OUTPUT IN TERRAFORM
It’s the best practice to create another files name “outputs.tf” to store
all the outputs in one place
e.g.
Outputs.tf
Subhabrata Panda | 36
16. IMPLEMENT S3 BUCKET WITH THE HELP OF
TERRAFORM
Key features:
• Stores virtually unlimited amounts of data.
• Stores data as objects that consist of key, value, metadata.
• Must have unique bucket’s name across all AWS accounts
globally.
• Store and retrieve backup data
• Region-Specific to reduce latency
• Versioning, object locking, and MFA delete enhance security.
First create one folder inside AWS name “s3-bucket” inside it create
blank files names
• main.tf
• variables.tf
• outputs.tf
• mydata.txt →to upload data in s3 bucket
variables.tf
Subhabrata Panda | 37
main.tf
outputs.tf
Subhabrata Panda | 38
Type “terraform plan” cmd in vscode terminal to check what all
configurations terraform will do.
Type “terraform plan” cmd in vscode terminal
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 39
17. RANDOM PROVIDER
For reference
https://registry.terraform.io/providers/hashicorp/random/latest/docs
Subhabrata Panda | 40
Changes in main.tf
Subhabrata Panda | 41
“byte_length” can be any number depending of your choice
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 42
18. TERRAFORM REMOTE STATE MANAGEMENT
Key Points:
→ Purpose: It helps Terraform determine what changes need to be
applied by comparing the actual state of resources with the desired
state in your configuration.
→ Format: The file is in JSON format and includes resource metadata,
attributes, and dependencies.
Syntax
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "state/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-lock-table" # For locking
encrypt = true # Encrypt state file
}
}
Subhabrata Panda | 43
Main reason to use S3 bucket is that if changes are made in the
“terraform.tfstate” it automatically makes changes in S3 bucket
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 44
19. PROJECT:DEPLOY STATIC WEBSITE ON AWS
USING S3
For reference:
- aws_s3_bucket_public_access_block --Terraform
- Setting permissions for website access --AWS
- aws_s3_bucket_policy --Terraform
- aws_s3_bucket_versioning --Terraform
- aws_s3_bucket_website_configuration --Terraform
-
block_public_acls = false
block_public_policy = false
ignore_public_acls = false
restrict_public_buckets = false
}
Subhabrata Panda | 45
To “add a bucket policy” →To make the objects in your bucket publicly
readable, you must write a bucket policy that grants everyone
s3:GetObject permission.
resource "aws_s3_bucket_policy"
"allow_access_from_another_account" {
bucket = aws_s3_bucket.S3_bucket.id
policy = jsonencode(
{
Version = "2012-10-17",
Statement = [
{
Sid = "PublicReadGetObject",
Effect = "Allow",
Principal = "*",
Action = "s3:GetObject",
Resource = "arn:aws:s3:::${aws_s3_bucket.S3_bucket.id}/*"
}
]
}
)
}
Subhabrata Panda | 46
The aws_s3_bucket_website_configuration resource in Terraform
is used to configure static website hosting for an S3 bucket. This
resource specifies the settings like the index document, error
document, and routing rules for the website.
index_document {
suffix = "index.html"
}
}
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 47
20. U N D E R S T A N D I N G V P C F O R T E R R A F O R M
IMPLEMENTATION
KEYWORDS
NAT gateway, Internet Gateway, subnets (private or public), Load
Balancer, NACL, Security group, Route table, VPC Peering
Subhabrata Panda | 48
NAT – Network Address Translation
NACL- Network Access Control List
ICMP- Internet Control Message Protocol
INTERNET GATEWAY
A gate that allows you to connect VPC to the Internet, only applicable to
the instance data present in public subnet.
LOAD BALANCER
Forward the request depending upon the load. Basically, it is connected
to the public subnet.
OR
Distributes incoming traffic across multiple targets (e.g., EC2 instances)
to improve availability and reliability.
ROUTER TABLE
A path that connects the load balancer of the public subnet to the
application or instance of the private subnet.
A set of rules that determine where network traffic is directed.
Each subnet in a VPC has its own route table that controls traffic flow
between subnets.
SECURITY GROUPS
The first layer of security of any EC2 instances i.e. attached to the
instances, which tell the instance with Ip address or port will be used to
give access to the instance.
SUBNETS
The VPC is created with Ip address range, splitting the Ip address for
sub projects.
NAT GATEWAY
- Used for private subnet.
- Helps to mask Ip address.
- Helps to download some resources from internet while doing that
it will mask or change the Ip address with the public Ip address
Subhabrata Panda | 50
either from the load balancer (SNAT) or from the router (NAT
gateway)
AWS PEERING
-Stable connection between 2 VPC either on same account or two
different accounts.
Create a VPC Peering Connection (if not already done) between the
two VPCs, as explained earlier.
- Repeat the same for the public subnets in VPC 2, adding routes to
the CIDR block of VPC 1.
Test Connectivity:
- Launch instances in the respective subnets (public/private) of both
VPCs and verify connectivity using tools like ping or curl.
Route53
- Provides DNS as a service.
- DNS – Domain Name Services
- Performs health check on web server.
- Domain Registration → hosted zones
Subhabrata Panda | 52
Subhabrata Panda | 53
21. I M P L E M E N T I N G V P C U S I N G T E R R A F O R M
For this implementation we will create new folder name “vpc” that
contains: -
• main.tf
• outputs.tf
• provider.tf
Subhabrata Panda | 54
provider.tf
main.tf
Subhabrata Panda | 55
Subhabrata Panda | 56
Subhabrata Panda | 57
Outputs.tf
Output
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 58
22. D A T A S O U R C E
Useful for obtaining dynamic data that you need for your configurations.
Real-Life Scenario:
Your company already has a production VPC and subnets set up, and
you want to deploy a new application into an existing subnet without
modifying the existing infrastructure. Instead of hardcoding VPC and
subnet IDs, you use Terraform data sources to dynamically fetch this
information.
NOTE: we are only doing “terraform plan” not “terraform apply” because it
may cost you, do it at your own risk.
Subhabrata Panda | 59
After applying “terraform plan” in the terminal, you will see this error
It explains:
• The AMI query is too broad, leading to multiple AMIs matching
the criteria.
• Terraform doesn't know which AMI to select because no specific
filtering or sorting is provided.
Subhabrata Panda | 60
If you want to check if it’s correct or not we will verify it in AWS console
then go to AWS console → Type AMI in search bar → click on “AMI
Catalog”
Subhabrata Panda | 61
To s e e t h e ava i l a b i l i t y z o n e s o f p a r t i c u l a r z o n e
Subhabrata Panda | 62
23. C R E A T E E C 2 U S I N G E X I S T I N G V P C
STEP-3 STEP-4
Output
Subhabrata Panda | 63
24. T E R R A F O R M V A R I A B L E S
main.tf
Subhabrata Panda | 64
If you hardcode these values in your main.tf file for each environment,
you will need to duplicate and edit the file multiple times, leading to
redundancy and error-prone configurations
main.tf variables.tf
Subhabrata Panda | 65
But if you try to give the wrong answer something like t2.mic which is
not part of ec2 instance type, terminal will take the output but when
you try to do “terraform apply” it will show error.
If you use validation in this case, you only option will be to choose
either “t2.nano” or “t2.micro” if you type anything except these two it
will show
Subhabrata Panda | 66
If block have multiple variables in main.tf
We can write
variables.tf main.tf
Subhabrata Panda | 67
Use of map in Terraform:
In Terraform, a map is a data structure that allows you to define and
access related data efficiently. It's particularly useful for organizing and
managing configurations when you need to group related values.
variables.tf main.tf
Subhabrata Panda | 68
Use of lookup in Terraform:
lookup retrieves a value from a map based on a key.
If the key is not found, you can provide a default value.
Subhabrata Panda | 69
ENVIROMENT VARIABLES
Syntax: -
“export TF_VAR_key=value”
Example:-
“export TF_VAR_aws_instance_type=t3.micro”
terraform.tfvars
Subhabrata Panda | 70
variables.tf terraform.tfvars
terraform.auto.tfvars
terraform.tfvars Terraform.auto.tfvars
Subhabrata Panda | 71
Output before having Output after having
“terraform.auto.tf.vars” after “terraform.auto.tf.vars” after
applying “terraform plan” applying “terraform plan”
We also write
in the
terminal
Subhabrata Panda | 72
25. L O C A L V A R I A B L E S I N T E R R A F O R M
Evaluated Dynamically:
• Local variables can be used to compute values dynamically, often
combining other inputs, resources, or expressions.
Subhabrata Panda | 73
26. T E R R A F O R M : O P E R A T I O N S & E X P R E S S I O N S
Subhabrata Panda | 74
Subhabrata Panda | 75
Subhabrata Panda | 76
27. T E R R A F O R M : F U N C T I O N S
Subhabrata Panda | 77
Subhabrata Panda | 78
Subhabrata Panda | 79
Subhabrata Panda | 80
28. T E R R A F O R M : M U L T I P L E R E S O U R C E S
For the first demo we will be creating a VPC with two subnets using
count in terraform
Int order create this demo we will create new folder name “tf-multiple-
resources” in AWS folder inside that we will be creating “main.tf” in
“main.tf” file there are subdivision
main.tf
Subhabrata Panda | 81
count
• The count parameter is set to 2, which means Terraform will
create two instances of the aws_subnet resource.
• Each instance will have unique properties based on the use of
count.index.
count.index
• The count.index is a zero-based index representing the
instance number of the resource being created.
• Since count = 2, the value of count.index will be:
o 0 for the first subnet instance.
o 1 for the second subnet instance.
Subhabrata Panda | 82
Now type “terraform init” → “terraform plan” → “terraform
apply”
For the second demo we will be creating a VPC with two subnets and
four instances using count in terraform
Subhabrata Panda | 83
Continuations of above infrastructure of the demo 1 project
Key Components:
• aws_subnet.tf_vpc_subnet[*].id:
o Retrieves the list of all subnet IDs created by the
aws_subnet.tf_vpc_subnet resource.
• length(aws_subnet.tf_vpc_subnet):
o Returns the total number of subnets (e.g., 2 subnets in the
earlier example).
• count.index % length(aws_subnet.tf_vpc_subnet):
o Distributes the instances evenly across the available subnets
using modulo operation.
Subhabrata Panda | 84
o This ensures that the subnet index cycles through the
available subnets (e.g., 0, 1, 0, 1 for 2 subnets).
• element(...):
o Retrieves the subnet ID at the calculated index.
Subhabrata Panda | 85
For the third demo we will be creating
Subhabrata Panda | 86
Now type “terraform plan” → “terraform apply”
Subhabrata Panda | 87
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Use of “for_each”.
“for_each” → only accepts “sets” and “map”
In order to learn the use of “for_each” we will have to do a slight
changes in “terraform.vars” , “terraform.tfvars” and “main.tf”
specially in resource "aws_instance" rest all will remain same.
terraform.vars
terraform.tfvars
Subhabrata Panda | 88
main.tf
Explanation of subnet_id:
aws_subnet.tf_vpc_subnet[*].id:
- This retrieves a list of all subnet IDs associated with the
aws_subnet.tf_vpc_subnet resource.
keys(var.ec2_instance_ami_map):
- Extracts all the keys from the variable ec2_instance_ami_map,
which is a map defining the AMI for each instance.
each.key:
- Refers to the current key being processed in the for_each block,
which corresponds to one EC2 instance in the
ec2_instance_ami_map.
index(keys(var.ec2_instance_ami_map), each.key):
- Determines the index of the current key (each.key) in the list of
keys extracted from the map.
length(aws_subnet.tf_vpc_subnet):
- Calculates the total number of subnets available in the
aws_subnet.tf_vpc_subnet resource.
index(...) % length(...):
- This modulus operation ensures that the index cycles through
the list of subnets. For example:
Subhabrata Panda | 89
- If there are 3 subnets and 5 instances, the instance-to-subnet
mapping would rotate (e.g., 0 -> Subnet1, 1 -> Subnet2, 2 ->
Subnet3, 3 -> Subnet1, 4 -> Subnet2).
-
element(...):
- Picks the subnet ID from the list of subnet IDs
(aws_subnet.tf_vpc_subnet[*].id) based on the calculated index.
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
Subhabrata Panda | 90
29. P R O J E C T : A W S I A M M A N A G E M E N T
Subhabrata Panda | 91
In “user.yaml”
STEP-1 STEP-2
Subhabrata Panda | 92
STEP-3
In “main.tf”
Provider
Subhabrata Panda | 93
locals
{
Subhabrata Panda | 94
…
Subhabrata Panda | 95
…
Subhabrata Panda | 96
# Configure organization-wide password policy settings
Subhabrata Panda | 97
In “output.tf”
Subhabrata Panda | 98
After the implementation of “terraform apply” we will see these
outputs in the AWS IAM console
Users console
Subhabrata Panda | 99
User group console
You can log in to any user account to verify its functionality. However,
it is the admin's responsibility to assign the account number,
username, and password.
After logging in with the password provided by the admin, AWS will
prompt you to change the password to one of your choices. If you
prefer not to change it, you can skip this step.
Note – if all work is done you should use command terraform destroy to
delete all the services you have used while doing project.
README.md:
A text file that provides documentation for the module.
Explains the module's purpose, usage, required inputs, and outputs.
variables.tf:
Specifies the inputs the module needs.
Defines variables with types, descriptions, and default values.
outputs.tf:
Declares the outputs from the module.
Shares resource information (like IDs, IPs) with the root module or other
modules.
Now click on modules you will get to see something like this:
Now type “terraform init” in termial, then you will notice something like:
n the "Inputs" section of the Terraform Registry, you’ll see all the
variables defined in the module's variables.tf file. These variables
automatically appear there for easy reference.
output
Now, we will create a new file named instance.tf inside the tf-module-
vpc directory.
In “instance.tf”
Output
NOTE: we are only doing “terraform plan” not “terraform apply” because it
may cost you, do it at your own risk.
Requirements:
• Accept cidr_block from user to create VPC
• User can create multiple subnets
→ Get CIDR block for subnets from user
→ Get AZS (availability zone)
→ User can mark a subnet as public (default is private)
If public, create IGW
Associate public subnet with Routing table
Where all the subnets i.e. public or private is attached to Route table (
) and this route table is attached to internet gateway
In tf-own-module-vpc/modules/vpc/variables.tf
In tf-own-module-vpc/ vpc-output-as-root.tf
NOTE: we are only doing “terraform plan” not “terraform apply” because it
may cost you, do it at your own risk.
It allows you to define resources once and reuse them across projects,
ensuring uniform configurations, reducing duplication, and making
collaboration easier.
• Readme.md file
• LICENSE
• Example
• Push the code in GitHub
• Terraform Registry
Add the necessary LICENSE file, which you can generate while creating
the repository on GitHub.
Then click on code and copy the like on the vs code terminal by adding
git clone before it
Subhabrata Panda | 118
Now you will see this file structure
Move all files from the modules/vpc folder (e.g., main.tf, outputs.tf,
variables.tf, versions.tf) to the root level of the repository, just outside
the modules/vpc directory.
Copy both the files and the examples folder into the terraform-aws-
subha-vpc directory.
If all the above steps are correct, then you will see this output in
terraform module
Key Uses:
1. Automatic Ordering: Terraform understands which resources
need to exist before others.
o Example: A subnet must be created before launching an EC2
instance in it.
Useful for resources that cannot have downtime, such as load balancers
or production systems.
prevent_destroy
Prevents a resource from being destroyed, even if a terraform destroy
command is run or the resource is removed from the configuration.
If you try to destroy the resource, Terraform will throw an error unless
you explicitly disable this protection.
Things to Consider
Subhabrata Panda | 126
1. Critical Resources: Use prevent_destroy for critical resources
like:
o Databases (to prevent data loss).
o VPCs or subnets (to avoid breaking the network).
o Persistent storage like S3 buckets or EBS volumes.
ignore_changes
Things to Consider
1. Dynamic Values: Use ignore_changes for attributes that are
frequently updated dynamically by external systems (e.g., tags,
user_data, or IAM policies).
2. Critical Updates: Avoid using ignore_changes for critical
attributes (e.g., instance_type, cidr_block) to ensure Terraform
manages them properly.
3. Fine-Tuning: You can ignore specific attributes rather than
ignoring all changes, making it a granular control mechanism.
replace_triggered_by
How It Works:
• Purpose: It defines specific dependencies that, when changed, will
cause the resource to be destroyed and recreated.
• Use Case: This is useful when a resource must be replaced if a
related resource or attribute changes, even if the resource itself
hasn’t directly changed in the configuration.
Syntax
preconditions
Examples
preconditions
Ensure the selected AMI starts with ami-:
postconditions
Ensure the EC2 instance has the desired state of "running":
Purpose: Deletes a resource from the state file without affecting the
actual infrastructure.
Usage: Useful for removing resources that are no longer managed by
Terraform or were manually created outside of Terraform.
Purpose: Updates the remote backend with a local state file, ensuring
consistency across environments.
Usage: Use this cautiously to avoid overwriting valid state data.
Typically used for recovery or migration.
Real-Life Scenario:
You’ve manually created resources in AWS, such as an S3 bucket or an
EC2 instance, but now you want Terraform to manage those resources
without recreating them. Terraform's import command allows you to
bring these existing resources into the Terraform state.
We will now create a new folder called tf-import-s3. Inside this folder
name “AWS”, we will add a file named main.tf, which will serve as the
entry point for defining the required Terraform configurations related to
module dependencies.
In “main.tf”
1. Environment Isolation:
Use workspaces to manage different environments (e.g., dev,
staging, prod) with the same configuration.
2. Multi-Tenant Applications:
Manage separate infrastructure for different clients or tenants.
Key Commands:
Sample of fi
STEP-1 STEP-2
Now go to any browser and type Since you have an HCP account
“app.terraform.io” then this page and are logged in, click on
will appear "Continue with HCP account"
STEP-5
Then this page will appear, then click on “Create organization”
STEP-6
Then give the “Organization name” then “Create organization”. Then
this layout will appear
STEP-8
For now go to the GitHub and create a new repo like this
Now clone the repo in local directory. Then this is the file structure by
adding “main.tf”
In main.tf
First go to AWS
➔ then IAM
➔ then go for users
➔ select “tf-user” as you are working in terraform as this users
➔ either create the access key id or reuse the id that you are using in
your local directory
➔ form their copy the “Access key” and “Secret Access key”
Workspace variables
Variables defined within a workspace always overwrite variables from
variable sets that have the same type and the same key
Or
Variable sets (0)
Allow you to reuse variables across multiple workspaces within your
organization, recommend for creating a variable set for variables used
in more than one workspace.
Now go to code that is present in local directory now just do the minor
change something like change byte_length =12 to byte_length = 13
Again, commit it now see the change iin the given layout
Click on “See details” then you will see the layout which is asking for
next information
For now click on “Confirm & apply”, then it will ask for giving the
comment and finally click on “Confirm plan”