0% found this document useful (0 votes)
45 views7 pages

Terraform Instructor Day3 1

Uploaded by

d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views7 pages

Terraform Instructor Day3 1

Uploaded by

d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Structure of Terraform Projects

Terraform configurations are typically organized into files and directories. Here's a common
structure:

Example Directory Structure:

my-terraform-project/
├── main.tf # Core resources
├── variables.tf # Input variable definitions
├── outputs.tf # Output values
├── provider.tf # Provider configurations
├── terraform.tfvars # Input variable values
├── backend.tf # Remote backend configuration (optional)
├── modules/ # Reusable modules
│ ├── vpc/
│ │ ├── main.tf # VPC-specific resources
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ └── ec2/
│ ├── main.tf # EC2-specific resources
│ ├── variables.tf
│ ├── outputs.tf
└── .terraform/ # Terraform cache and state (auto-generated)

Key Files:

 main.tf: The main configuration file where resources are defined (you’re already using
this).
 variables.tf: Defines input variables for your Terraform configuration (e.g., region,
instance types).
 outputs.tf: Declares the outputs that Terraform will print after applying (e.g., VPC IDs,
instance IPs).
 terraform.tfvars: Specifies values for variables. This file is used to override defaults
defined in variables.tf.
 provider.tf: Contains the provider block(s) to configure the cloud platform (e.g., AWS,
Azure).
 backend.tf: Configures the Terraform backend (e.g., S3 for remote state storage).

Modular Directory Structure:

 modules/: Used to define reusable infrastructure components (e.g., a module for VPCs,
EC2 instances, RDS, etc.).

2. Organizing Code

a. Split Your Code


Instead of putting everything into main.tf, split the code into logical files:

 main.tf: High-level orchestration or references to modules.


 provider.tf: Provider-specific configuration.
 variables.tf: Variable definitions.
 outputs.tf: Outputs for important resources.
 backend.tf: Backend configuration (if needed for remote state).

b. Use Modules

Modules are reusable pieces of Terraform code that encapsulate resources for a specific purpose
(e.g., a VPC module, an EC2 module). For example:

 Directory Structure for a Module:

bash
Copy code
modules/
└── vpc/
├── main.tf # VPC-related resources
├── variables.tf # Input variables for the module
├── outputs.tf # Output values (e.g., VPC ID)

How to Use a Module:

hcl
Copy code
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
environment = "dev"
}

c. Use Workspaces

Workspaces allow you to manage multiple environments (e.g., dev, staging, prod) in the same
configuration:

 Commands:
o Create a workspace:

bash
Copy code
terraform workspace new dev

o Switch workspaces:

bash
Copy code
terraform workspace select prod
3. Advanced Terraform Features

a. Remote State Management

 Use a remote backend (e.g., AWS S3, Terraform Cloud) to store state files securely and
enable team collaboration.
 Example: backend.tf

hcl
Copy code
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "state-file/terraform.tfstate"
region = "ap-southeast-2"
dynamodb_table = "terraform-locks" # Optional for state locking
}
}

b. Data Sources

 Data sources allow you to query existing resources in your cloud environment.
 Example: Get an existing VPC by name:

hcl
Copy code
data "aws_vpc" "default" {
filter {
name = "tag:Name"
values = ["default-vpc"]
}
}

output "default_vpc_id" {
value = data.aws_vpc.default.id
}

c. Dependency Graph

 Terraform automatically builds a dependency graph between resources. You can view it
using:

bash
Copy code
terraform graph | dot -Tsvg > graph.svg

This generates a visual representation of your resource dependencies.


4. Debugging and Logging

 Enable Detailed Logs:

bash
Copy code
TF_LOG=DEBUG terraform apply

 Use terraform plan Effectively:


o Always run terraform plan before apply to understand what changes will be
made.

5. Working with Variables

Defining Variables (variables.tf):

hcl
Copy code
variable "region" {
description = "AWS region"
default = "ap-southeast-2"
}

variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}

Using Variables (main.tf):

hcl
Copy code
provider "aws" {
region = var.region
}

resource "aws_instance" "example" {


instance_type = var.instance_type
ami = "ami-0d6560f3176dc9ec0"
}

Providing Variable Values (terraform.tfvars):

hcl
Copy code
region = "us-east-1"
instance_type = "t2.medium"
6. Outputs

 Outputs make it easier to get values of resources post-deployment.


 Example: Add an output in outputs.tf:

hcl
Copy code
output "vpc_id" {
value = aws_vpc.my_vpc.id
}

output "public_subnet_id" {
value = aws_subnet.public_subnet.id
}

 After applying, Terraform will display the output values:

bash
Copy code
Outputs:

vpc_id = "vpc-123abc"
public_subnet_id = "subnet-456def"

7. Playing Around and Experimenting

Here are some fun tasks you can try to get comfortable with Terraform:

a. Multi-Region Deployment

Deploy resources in multiple AWS regions using provider aliases:

hcl
Copy code
provider "aws" {
region = "us-east-1"
alias = "us"
}

provider "aws" {
region = "us-west-1"
alias = "west"
}

resource "aws_instance" "east_instance" {


provider = aws.us
instance_type = "t2.micro"
ami = "ami-12345"
}

resource "aws_instance" "west_instance" {


provider = aws.west
instance_type = "t2.micro"
ami = "ami-67890"
}

b. Dynamic Blocks

Use dynamic blocks to handle repetitive configurations:

hcl
Copy code
resource "aws_security_group" "example" {
name = "example-sg"
description = "Example security group"
vpc_id = aws_vpc.my_vpc.id

dynamic "ingress" {
for_each = ["22", "80", "443"] # Ports to allow
content {
from_port = ingress.value
to_port = ingress.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
}

c. Use Count and For-Each

Create multiple resources dynamically:

hcl
Copy code
resource "aws_subnet" "subnets" {
count = 3
vpc_id = aws_vpc.my_vpc.id
cidr_block = "10.0.${count.index + 1}.0/24"
availability_zone = "ap-southeast-2a"

tags = {
Name = "Subnet-${count.index + 1}"
}
}

Next Steps

1. Practice with Modules: Build and use reusable modules.


2. Explore Remote State: Learn how to collaborate with remote backends (e.g., S3,
Terraform Cloud).
3. Automation: Integrate Terraform into CI/CD pipelines.
4. Policy as Code: Use terraform validate or Sentinel (in Terraform Enterprise) to
enforce rules.

With these tips, you can take Terraform beyond the basics and build robust, reusable
infrastructure configurations.

You might also like