0% found this document useful (0 votes)
75 views9 pages

IaC Terraform-1

Na

Uploaded by

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

IaC Terraform-1

Na

Uploaded by

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

Created By: Dhruv Singhal | LinkedIn

Terraform
Terraform is an open-source infrastructure-as-code (IaC) tool developed by HashiCorp.
It allows you to define, provision, and manage infrastructure resources in a
consistent and version-controlled way across multiple cloud platforms, on-premises
environments, and even custom providers. It uses a declarative configuration
language, HashiCorp Configuration Language (HCL), to define resources and manage
their lifecycle.

Page 1|9
Created By: Dhruv Singhal | LinkedIn

Here's an overview of everything you need to know about Terraform:

Key Concepts in Terraform

1. Infrastructure as Code (IaC): Terraform allows you to define infrastructure in


a code format, which you can save in version control. This makes your
infrastructure reproducible, shareable, and manageable over time.

2. Declarative Language (HCL): With HCL, you describe the desired state of your
infrastructure, and Terraform calculates the necessary steps to achieve it.
This is different from imperative programming, where you would define each step
manually.

3. Providers: Providers are plugins that allow Terraform to interact with various
cloud platforms (like AWS, Azure, and Google Cloud) or on-premises
environments. Providers define the specific resources that can be managed (like
aws_instance for EC2 instances in AWS or azurerm_storage_account for storage
accounts in Azure).

4. State Management: Terraform maintains a state file (terraform.tfstate) that


keeps track of resources it manages. The state file represents the current
status of the infrastructure and helps Terraform understand what it needs to
change, add, or remove to achieve the desired state.

5. Execution Plans: When you run a Terraform plan, Terraform generates an


execution plan that shows what actions it will take to bring the infrastructure
in line with the configuration. This is a crucial step in the workflow, as it
lets you review changes before applying them.

6. Modules: Modules are reusable, logical groupings of resources that make


configurations modular and more manageable. You can define a module once and
use it multiple times, reducing redundancy and improving maintainability.

7. Terraform Registry: The Terraform Registry is an online repository where users


can share and discover modules. It includes official and community-contributed
modules, covering a wide range of use cases.

8. Workspaces: Workspaces in Terraform allow you to manage multiple instances of


the same infrastructure. This is useful for handling different environments,
like development, staging, and production.

9. Terraform Cloud/Enterprise: Terraform Cloud (and Enterprise) is a managed


service that provides a centralized place for teams to collaborate on Terraform
projects. It offers features like remote state management, secure variables,
and integration with CI/CD pipelines.

Terraform Workflow

The Terraform workflow typically includes four main steps:

1. Write: Define your infrastructure in HCL. This can be done by writing


configurations that define resources, providers, and variables.

2. Initialize: Run terraform init to initialize the configuration. This step


installs the necessary provider plugins and prepares the backend for storing
state files.

Page 2|9
Created By: Dhruv Singhal | LinkedIn

3. Plan: Use terraform plan to generate and review an execution plan. The plan
shows a preview of what actions Terraform will take to make the infrastructure
match the configuration.

4. Apply: Apply the changes with terraform apply, which executes the plan and
makes the necessary changes to the infrastructure. After applying, Terraform
updates the state file to reflect the new state.

Terraform CLI Commands

• terraform init: Initializes the working directory by downloading the required


provider plugins and preparing the backend.

• terraform plan: Generates an execution plan, showing changes to make the


infrastructure match the configuration.

• terraform apply: Applies the changes to infrastructure to match the


configuration.

• terraform destroy: Deletes all resources managed by the Terraform


configuration.

• terraform import: Imports existing infrastructure into Terraform.

• terraform state: Manages the state file, allowing you to inspect and modify
state as needed.

• terraform validate: Checks whether a configuration is syntactically valid.

• terraform fmt: Formats configuration files to a standard style.

• terraform workspace: Manages multiple workspaces.

Terraform Configuration Structure

A basic Terraform configuration is divided into several blocks:

1. Provider Block: Specifies the provider and authentication details.

provider "aws" {
region = "us-west-2"
}

2. Resource Block: Defines the resources to be created.

resource "aws_instance" "example" {


ami = "ami-123456"
instance_type = "t2.micro"
}

3. Variable Block: Defines input variables for the configuration, making it


reusable.

Page 3|9
Created By: Dhruv Singhal | LinkedIn

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

4. Output Block: Defines output values, useful for referencing information from
the configuration.

output "instance_ip" {
value = aws_instance.example.public_ip
}

State Management and Backends

• State Storage: Terraform stores state locally by default, but it can be


configured to use remote storage (like AWS S3, Azure Blob Storage, or Terraform
Cloud) for better collaboration and security.

• Locking: Remote backends support state locking, preventing multiple Terraform


executions from altering the state simultaneously.

• Remote Backends: Examples include AWS S3, Azure Blob, GCP Storage, and
HashiCorp's Terraform Cloud. Remote backends are essential for collaborative
work and team projects.

Terraform Modules
Modules in Terraform allow you to organize and reuse code effectively. You can break
down complex configurations into smaller modules, which can be maintained and
versioned separately.

Example Structure of a Module:

module/

├── main.tf # Defines resources

├── variables.tf # Defines input variables

├── outputs.tf # Defines outputs for the module

Using a module:

module "my_vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
}

Page 4|9
Created By: Dhruv Singhal | LinkedIn

Terraform Cloud and Terraform Enterprise offer additional features:

• Remote State Management: Secure storage for state files, accessible to multiple
users.

• Workspaces and Variables Management: Allows management of multiple environments


and variable configurations.

• VCS Integration: Integrates with version control systems like GitHub, GitLab,
and Bitbucket for automated plan and apply steps.

• Sentinel Policies: Allows defining policies as code to enforce governance on


infrastructure provisioning.

Advantages of Terraform

• Multi-Cloud Support: Supports various cloud providers and on-prem


infrastructure.
• Declarative Language: Simplifies infrastructure management by focusing on the
desired state.
• Modularity and Reusability: Encourages the use of modules for reusable and
manageable configurations.
• Open-Source and Community-Driven: Large community support and wide range of
plugins.

Best Practices

1. Use remote state for collaboration and backups.


2. Follow the DRY (Don't Repeat Yourself) principle by leveraging modules.
3. Use terraform plan to review changes before applying.
4. Version-control all configuration files.
5. Limit direct use of sensitive values in configuration files (use Terraform
Cloud or Vault to manage secrets).

Modules in Terraform:
Terraform modules are a way to organize and reuse code in Terraform configurations. A
module is essentially a collection of .tf files in a directory, which allows you to
group related resources together and manage them as a single entity. Modules are
powerful because they enable you to write once and reuse in multiple configurations,
making your infrastructure code modular, consistent, and easier to maintain.

Why Use Terraform Modules?

• Reusability: Modules let you define infrastructure once and use it in multiple
places.
• Consistency: Modules enforce best practices and ensure consistency across
environments.
• Abstraction: Modules abstract away details, exposing only the variables and
outputs needed by other parts of your infrastructure.

Page 5|9
Created By: Dhruv Singhal | LinkedIn

Structure of a Module

A Terraform module typically has three main components:

1. Input Variables (variables.tf): Define parameters that customize the module's


behavior.
2. Resources (main.tf): Define the infrastructure resources the module will
manage.
3. Outputs (outputs.tf): Define outputs that expose values to other parts of the
infrastructure.

Example: Creating an AWS EC2 Instance Module

Let’s create a simple module that provisions an EC2 instance in AWS.

Step 1: Create the Module Directory

First, create a directory for the module:

mkdir ec2-instance-module

cd ec2-instance-module

Inside this directory, create the following files:

1. variables.tf - Define Input Variables

variable "instance_type" {

description = "The type of EC2 instance to create"

type = string

default = "t2.micro"

variable "ami_id" {

description = "AMI ID of the EC2 instance"

type = string

variable "key_pair_name" {

description = "Name of the key pair for SSH access"

type = string

Page 6|9
Created By: Dhruv Singhal | LinkedIn

2. main.tf - Define Resources

resource "aws_instance" "example" {

ami = var.ami_id

instance_type = var.instance_type

key_name = var.key_pair_name

tags = {

Name = "Example EC2 Instance"

3. outputs.tf - Define Output Values

output "instance_id" {

description = "The ID of the EC2 instance"

value = aws_instance.example.id

output "public_ip" {

description = "The public IP of the EC2 instance"

value = aws_instance.example.public_ip

This completes the module structure. The module ec2-instance-module is now ready to
be used in other Terraform configurations.

Step 2: Use the Module in a Root Module

Now, create a new directory (e.g., project-root) to serve as the root module, which
will call the ec2-instance-module:

mkdir project-root

cd project-root

Page 7|9
Created By: Dhruv Singhal | LinkedIn

Inside this root module, create a main.tf file to call the EC2 instance module:

provider "aws" {
region = "us-west-2"
}

module "ec2_instance" {
source = "../ec2-instance-module" # Path to the module
instance_type = "t2.micro"
ami_id = "ami-0abcdef1234567890" # Replace with a valid AMI ID in your
region
key_pair_name = "my-key-pair"
}

output "ec2_instance_id" {
value = module.ec2_instance.instance_id
}

output "ec2_public_ip" {
value = module.ec2_instance.public_ip
}

In this example:

• module "ec2_instance" is used to call ec2-instance-module, passing variables to


customize the instance.
• source specifies the path of the module (relative or remote).
• Outputs from the module (instance_id and public_ip) are then accessible in the
root module as module.ec2_instance.instance_id and
module.ec2_instance.public_ip.

Step 3: Run Terraform Commands

In the project-root directory, initialize and apply the configuration:

terraform init
terraform apply

Terraform also supports modules from the Terraform Registry, allowing you to use
community-maintained modules. For example, to use a public VPC module from the
registry:

module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "3.14.2"

name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-west-2a", "us-west-2b"]
public_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
enable_nat_gateway = true
single_nat_gateway = true

Page 8|9
Created By: Dhruv Singhal | LinkedIn

enable_dns_support = true
enable_dns_hostnames = true
}

Note:

This VPC module provisions a fully configured VPC in AWS, including subnets, internet
gateway, NAT gateway, and route tables. Just customize the variables as needed!

Summary
Terraform modules are essential for organizing and reusing infrastructure code. They
can be local, shared across projects, or downloaded from the Terraform Registry. By
encapsulating reusable code, modules make infrastructure more modular, maintainable,
and scalable.

For more information, see following:


https://developer.hashicorp.com/terraform/docs

https://developer.hashicorp.com/terraform/language/modules

Page 9|9

You might also like