Terraform + AWS
Learn while Doing it
Learn AWS Concepts
Programming Concepts
Projects + Task EC2
Terraform Cloud VPC
Terraform Module S3
Workspaces IAM
State Mangement
What is Terraform?
Terraform is an open-source
infrastructure as code (IaC) tool.
What is IaC?
Tools allow you to manage infrastructure with
configuration files rather than through a graphical user
interface.
What is IaC?
IaC allows you to build, change, and manage your
infrastructure in a safe, consistent, and repeatable way by
defining resource configurations that you can version,
reuse, and share.
Why Terraform?
Automate Setup: Quickly create and configure resources like servers,
databases, and networks.
Consistency: Ensure every environment is set up the same way,
reducing errors.
Scalability: Easily replicate and scale infrastructure for different
environments.
Version Control: Track and manage infrastructure changes just like
software code.
Flexibility: Works with multiple cloud providers and on-premises
setups.
EC2
Manual Terraform
Terraform Config
It uses .tf extension
Format is HCL (Hashicorp Config Language)
Declarative Language
State Management
Terraform supports JSON
format also
State Management
The state file (terraform.tfstate) maintains a detailed
record of the current state of managed resources
This state file can be stored locally or remotely, with
remote storage options enabling collaboration by
sharing the state across teams and environments.
Variables
Outputs
S3
AWS S3 (Amazon Simple Storage Service) is a scalable,
high-speed, web-based cloud storage service designed for
online backup and archiving of data and applications.
Exercise:
Create a S3 bucket using TF config
Upload a File
Output the bucket name
Terraform Remote State Management
Create S3 bucket
Backend block for remote state management
Project:
Deploy Static website
on AWS using S3
Provider Configuration: Specifies AWS and random providers.
Bucket Creation: Creates an S3 bucket with a unique name.
Public Access: Configures public access to the bucket.
Website Configuration: Sets up the bucket for static website hosting.
File Uploads: Uploads the index.html and error.html files to the bucket.
Website Endpoint: Outputs the URL of the static website.
Summary
resource "aws_s3_bucket" "mywebapp-bucket"
resource "aws_s3_bucket_public_access_block" "example"
resource "aws_s3_bucket_policy" "mywebapp"
resource "aws_s3_bucket_website_configuration" "mywebapp"
resource "aws_s3_object" "index_html"
resource "aws_s3_object" "styles_css"
output "name"
Virtual Private Cloud (VPC)
Virtual Private Cloud (VPC)
A private, isolated network within the AWS cloud
where you can launch and manage your resources
securely.
Website is ready
Where to deploy?
Website is ready
Where to deploy?
US
Asia
Website is ready
Where to deploy?
Europe
North
Asia East
Website is ready
Where to deploy? South
REGION
North
Singapore
Mumbai
Asia East
Hyderabad
Website is ready Tokyo
Where to deploy? South
Availability Zones
a b c
Mumbai
What is Subnets?
A subnet is a smaller, segmented part of a larger
network that isolates and organizes devices within a
specific IP address range.
c
a b
CIDR (Classless Inter-Domain Routing) is a method for allocating IP
addresses and routing Internet Protocol (IP) packets.
What happens when creating subnet?
CIDR Block Allocation:
You specify a range of IP addresses (CIDR block) within the VPC's IP
address range for the subnet.
This determines the pool of IP addresses available for instances in
the subnet.
Explanation of 10.0.1.0/24
The /24 indicates that the first 24 bits are the network portion of the address.
The remaining 8 bits are available for host addresses within the network.
10.0.1.0 to 10.0.1.255 is the full range.
Route Table
Internet Gateway
An Internet Gateway is a component that allows
communication between instances in your VPC and the
internet.
Security Groups: Network firewall rules that
control inbound and outbound traffic for
instances.
Network ACLs (Access Control Lists): Optional
layer of security for your VPC that acts as a
firewall for controlling traffic in and out of one
or more subnets.
NAT (Network Address Translation) Gateway:
Enables instances in a private subnet to connect
to the internet or other AWS services, but
prevents the internet from initiating connections
to those instances.
VPC Peering: A networking connection between
two VPCs that enables you to route traffic
between them privately.
VPC Endpoints: Allows you to privately connect
your VPC to supported AWS services and VPC
endpoint services powered by AWS PrivateLink.
Bastion Host: A special-purpose instance that
provides secure access to your instances in
private subnets.
Elastic IP Addresses: Static IP addresses
designed for dynamic cloud computing.
VPC Flow Logs: Capture information about the IP
traffic going to and from network interfaces in
your VPC.
Direct Connect: Establishes a dedicated network
connection from your premises to AWS.
Transit Gateway: A network transit hub that you
can use to interconnect your VPCs and on-
premises networks.
Create VPC.
Create Public Subnet.
Create Private Subnet.
Create Internet Gateway.
Attach Internet Gateway to VPC.
Create Route Table for Public Subnet.
Add Route to Internet Gateway in Public Route Table.
Associate Public Subnet with Public Route Table.
Create Route Table for Private Subnet (if using NAT,
otherwise optional).
Associate Private Subnet with Private Route Table.
Exercise on VPC:
A VPC with a CIDR block of 10.0.0.0/16.
One public subnet with a CIDR block of 10.0.1.0/24.
One private subnet with a CIDR block of 10.0.2.0/24.
One Internet Gateway.
One public route table with a route to the Internet Gateway,
and the correct association between the public subnet and
the public route table.
Project: VPC + EC2 + NGINX + HTTP Access:
A VPC with pubic and private subnet
A EC2 instance using public subnet we created.
Setup nginx webserver
Create security group rule to enable HTTP access
Output the webserver URL on terminal
Data Source in Terraform?
It allows you to fetch and use information from
external sources or
existing resources within your cloud infrastructure.
Useful for obtaining dynamic data that you need for your
configurations.
Data Source TASK?
Create an EC2 instance using existing
VPC
private-subnet
security-group
Terraform Variables
Terraform Variables
environment var
terraform.tfvars
*.auto.tfvars
-var & -var-file
export TF_VAR_key=value
Terraform Functions
Terraform Functions
Built-in functions that you can call from within
expressions to transform and combine values.
max(5, 12, 9)
Terraform Functions
#value = lower(local.name)
#value = startswith(local.name, "Hello")
#value = join("-", var.list)
#value = split("-", var.string)
#value = trimspace(var.string)
#value = length(var.list)
#value = merge(var.map1, var.map2)
#value = contains(var.list, "d")
#value = max(1, 2, 3) and min(1, 2, 3)
#value = abs(var.number)
#value = toset(var.list) #to convert list into set (will remove the duplicates)
#value = tolist(var.set)
Multiple Resources using
Count
for_each
Create 2 subnets
Using count
subnet-1 subnet-2
10.0.0.0/24 10.0.1.0/24
Create 2 subnets
Create 4 ec2 instance, 2 in each subnet
ec2-1 ec2-3
subnet-1 subnet-2 ec2-4
ec2-2
Create 2 subnets
Create 2 ec2 instance, 1 in each subnet
subnet-1 ec2-1 (ubuntu)
subnet-2 ec2-2 (amazon-linux)
Project: IAM
Task: AWS IAM Management
Provide user and roles info via YAML file
Read the YAML file and process data
Create IAM users
Generate Passwords for the users
Attach policy/roles to each users
[
{
roles = ["AmazonEC2FullAccess"]
username = "raju"
index 0
},
{
roles = ["AmazonS3ReadOnlyAccess"]
username = "sham"
index 1
},
{
roles = ["AmazonS3ReadOnlyAccess", "AmazonEC2FullAccess"] index 2
username = "baburao"
},
]
The flatten function in Terraform is used to
transform a list of lists into a single, flat list.
{
roles = ["AmazonS3ReadOnlyAccess", "AmazonEC2FullAccess"]
username = "baburao"
}
Terraform Modules
Terraform Modules:
Modules are containers for multiple resources that are
used together.
A module consists of a collection of .tf and/or .tf.json
files kept together in a directory.
Modules are the main way to package and reuse
resource configurations with Terraform.
Building our own Module
Requirements
Accept cidr_block from user to create VPC
User can create multiple subnets
Get CIDR block for subnet 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
Prepare Module For Publish
README.md file
LICENSE
Examples
Push code in GitHub
Terraform Registry
Terraform Dependency
Terraform Dependencies
Resource Lifecycle
Terraform Lifecycle Block
prevent_destroy
ignore_changes
replace_triggered_by
ignore_changes
replace_triggered_by
Validations
Terraform Validations
preconditions postconditions
Allow you to define checks that must be true before a resource
is created (precondition) and after a resource is created
(postcondition).
preconditions
postconditions
Conditions Task
Create EC2 instance
Implement preconditions:
Inside the resource block, add a lifecycle block.
Add precondition blocks to ensure that the security_group
id is created
Implement postcondition:
Add another lifecycle block within the resource.
Add a postcondition block to ensure that the instance has
a public IP address after creation.
assert
check "ec2_instance_validation" {
description = "Ensure EC2 instance is using an approved AMI and instance type."
assert {
condition = var.ami_id != ""
error_message = "AMI ID must not be empty."
}
assert {
condition = contains(var.production_instance_type, var.instance_type)
error_message = "Instance type must be one of the approved types for production:
${join(", ", var.production_instance_type)}."
}
}
State Manipulation
List all resources in the state:
terraform state list
Show details of a specific resource:
terraform state show <resource_address>
Move a resource to a different address:
terraform state mv <source_address> <destination_address>
Remove a resource from the state:
terraform state rm <resource_address>
Pull the current state:
terraform state pull
Push a local state file to the remote backend:
terraform state push <state_file>
List all state commands:
terraform state
Terraform Import
terraform import is a command in Terraform
that allows you to import existing
infrastructure resources into your Terraform
state.
Use-Case
Assuming you have already created an EC2 instance.
Create a resource block in tf config (initially you can
keep it empty)
Use terraform import command
terraform import aws_instance.main ec2_id
Terraform show to inspect the imported resource.
Update the resource block accordingly.
Workspaces
Allows you to manage multiple sets of
infrastructure configurations within a single
configuration directory.
Each workspace has its own state file
tfstate tfstate tfstate
workspace-dev workspace-test workspace-prod
tf config
Listing Workspaces
terraform workspace list
Creating a Workspace
terraform workspace new <workspace_name>
Selecting a Workspace
terraform workspace select <workspace_name>
Showing the Current Workspace
terraform workspace show
Deleting a Workspace
terraform workspace select default
terraform workspace delete <workspace_name>
Terraform Cloud
Terraform Cloud is a managed service provided by
HashiCorp that facilitates collaboration on
Terraform configurations.
Providing features like
remote state management,
version control system (VCS) integration,
automated runs, and
secure variable management.