Ultimate guide for terraform from basic to advance

Contents hide

What is the need of terraform IAAC?

The need for Terraform Infrastructure as Code (IaAC) is driven by several key benefits:

  1. Consistency and Reproducibility: Terraform allows you to define your infrastructure in code, ensuring that the same configuration can be applied consistently across different environments.
  2. Version Control: Infrastructure changes can be versioned and tracked in source control systems, providing a history of changes and the ability to roll back to previous configurations.
  3. Automation: Terraform automates the provisioning and management of infrastructure, reducing the need for manual intervention and minimizing the risk of human error.
  4. Scalability: Terraform can efficiently manage complex and large-scale infrastructure, supporting the scaling of resources up or down as needed.
  5. Declarative Language: Terraform uses a declarative language, where you describe the desired state of your infrastructure, and Terraform takes care of achieving that state.
  6. Multi-Cloud Support: Terraform supports multiple cloud providers and on-premises environments, allowing for a unified approach to infrastructure management across different platforms.
  7. Infrastructure as Code Best Practices: Terraform encourages best practices in infrastructure management, such as modularity, reusability, and collaboration among teams.

Summary:

  • Ensures consistent and reproducible infrastructure configurations
  • Enables version control and tracking of infrastructure changes
  • Automates provisioning and management of infrastructure
  • Supports scalability and efficient management of complex environments
  • Uses a declarative language for describing desired infrastructure states
  • Offers multi-cloud support for unified infrastructure management
  • Promotes best practices such as modularity, reusability, and team collaboration

List of IaaC tools

Here is a list of popular Infrastructure as Code (IaC) tools:

  1. Terraform
  2. AWS CloudFormation
  3. Azure Resource Manager (ARM) Templates
  4. Google Cloud Deployment Manager
  5. Ansible
  6. Puppet
  7. Chef
  8. SaltStack
  9. Pulumi
  10. Kubernetes
  11. Juju
  12. CFEngine
  13. Vagrant

What is terraform?

Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp that allows users to define and provision data center infrastructure using a high-level configuration language known as HashiCorp Configuration Language (HCL) or JSON. Here are some key aspects of Terraform:

  • Code-based Infrastructure: Set up and manage infrastructure using configuration files.
  • Multi-Provider Support: Works with various cloud providers like AWS, Azure, and Google Cloud.
  • Automation: Automatically creates, updates, and deletes resources as specified.
  • State Management: Keeps track of the current state of your infrastructure.
  • Consistency: Ensures the same setup across different environments.
  • Modularity: Allows for reusable and organized configuration code.
  • Preview Changes: Lets you see what changes will be made before applying them.

What is feature of terraform?

  • Easy Setup with Code: Define your infrastructure using simple configuration files.
  • Works with Many Providers: Supports various cloud services like AWS, Azure, and Google Cloud.
  • Automatic Dependency Management: Understands relationships between resources to set them up in the correct order.
  • Tracks Changes: Keeps a record of your infrastructure’s current state to manage updates and changes.
  • Plan Before Apply: Shows a preview of changes before they are made.
  • Reusable Modules: Allows you to create reusable pieces of infrastructure code.
  • Extendable: You can add custom plugins for more functionality.
  • Automation: Automatically creates and manages resources as specified.
  • Consistency: Ensures the same setup is applied every time.
  • Community Support: Has a large community with lots of shared modules and resources.

Terminology used in terraform

  1. Providers:
    • Plugins that allow Terraform to interact with APIs of various services (e.g., AWS, Azure, Google Cloud).
  2. Resources:
    • The infrastructure components defined in Terraform configuration files (e.g., virtual machines, storage buckets).
  3. Modules:
    • Reusable and shareable components that encapsulate a set of resources and configurations.
  4. State:
    • The data structure that Terraform uses to map the resources defined in the configuration files to real-world resources.
  5. Configuration:
    • The set of files written in HashiCorp Configuration Language (HCL) that describe the infrastructure.
  6. Plan:
    • A preview of the changes Terraform will make to achieve the desired state defined in the configuration files.
  7. Apply:
    • The command to execute the changes required to reach the desired state of the infrastructure.
  8. Output Values:
    • Data outputs from your Terraform configuration that can be used elsewhere in the configuration or as inputs to other modules.
  9. Variables:
    • Inputs to your Terraform configuration that allow you to parameterize and customize the infrastructure.
  10. Data Sources:
    • Information sources that Terraform can query to get data about external resources.
  11. Terraform Registry:
    • A public directory of modules and providers that can be used to find and share configuration components.
  12. Terraform Cloud/Enterprise:
    • Services offered by HashiCorp for managing Terraform configurations, state, and collaboration in a centralized manner.
  13. Backend:
    • The storage location for Terraform state, which can be local or remote (e.g., S3, Consul).
  14. Provisioners:
    • Used to execute scripts or commands on a local or remote machine as part of resource creation or destruction.
  15. Workspace:
    • An isolated environment for managing different versions or configurations of infrastructure, typically used for managing multiple environments like dev, staging, and production.

  1. Providers:
    • Plugins that connect Terraform to cloud services (e.g., AWS, Azure).
  2. Resources:
    • Individual components you create with Terraform (e.g., servers, databases).
  3. Modules:
    • Reusable packages of Terraform code that help organize and share configurations.
  4. State:
    • A file that keeps track of the current status of your infrastructure.
  5. Configuration:
    • The code files where you define your infrastructure setup.
  6. Plan:
    • A preview of what Terraform will change in your infrastructure.
  7. Apply:
    • The command to make the changes described in your plan.
  8. Output Values:
    • Information from your Terraform setup that can be used elsewhere.
  9. Variables:
    • Inputs to your configuration that make it customizable.
  10. Data Sources:
    • External information that Terraform can use to configure resources.
  11. Terraform Registry:
    • A directory of shared modules and plugins you can use.
  12. Terraform Cloud/Enterprise:
    • Services for managing Terraform configurations and teamwork.
  13. Backend:
    • Where Terraform stores its state file, either locally or remotely.
  14. Provisioners:
    • Scripts or commands run during resource setup or teardown.
  15. Workspace:
    • Isolated environments for different versions or stages (e.g., dev, prod) of your infrastructure.

How terraform works?

  1. Write Configuration:
    • Define your infrastructure using configuration files written in HashiCorp Configuration Language (HCL) or JSON. These files describe the desired state of your infrastructure.
  2. Initialize:
    • Run terraform init to initialize the working directory. This command downloads the necessary provider plugins and sets up the backend for storing the state.
  3. Plan:
    • Run terraform plan to create an execution plan. Terraform compares the current state with the desired state defined in the configuration files and shows what actions it will take to achieve that state.
  4. Apply:
    • Run terraform apply to execute the changes required to reach the desired state. Terraform will create, update, or delete resources as needed.
  5. State Management:
    • Terraform maintains a state file that records the current state of your infrastructure. This file helps Terraform understand what resources exist so it can manage them correctly.
  6. Provision Resources:
    • Based on the configuration, Terraform interacts with the specified providers (like AWS, Azure, Google Cloud) to create and manage resources such as virtual machines, networks, and databases.
  7. Output:
    • After applying changes, Terraform provides outputs that can be used for other processes or referenced in further configurations.
  8. Iterate:
    • As your infrastructure needs change, you can modify the configuration files and repeat the plan and apply steps to update your infrastructure accordingly.

Simple Workflow

  1. Define: Write configuration files.
  2. Initialize: Set up Terraform with terraform init.
  3. Plan: Preview changes with terraform plan.
  4. Apply: Execute changes with terraform apply.
  5. Manage: Maintain infrastructure state with the state file.
  6. Update: Modify configurations and reapply as needed.

Terraform Architecture

  1. Configuration Files:
    • Written in HashiCorp Configuration Language (HCL) or JSON, these files define the desired state of your infrastructure.
  2. Core:
    • The core is the heart of Terraform, responsible for reading and interpreting the configuration files, managing the state, and generating execution plans.
  3. Providers:
    • Plugins that interact with various APIs to manage resources. Examples include AWS, Azure, Google Cloud, and many others. Providers are downloaded during the initialization process.
  4. State:
    • Terraform maintains a state file that maps real-world resources to your configuration. This file tracks the current state of your infrastructure and helps Terraform understand changes needed to achieve the desired state.
  5. CLI (Command Line Interface):
    • The primary interface for interacting with Terraform. Commands like init, plan, apply, and destroy are used to manage the lifecycle of your infrastructure.
  6. Backend:
    • The backend is where the state file is stored. It can be local or remote (e.g., AWS S3, Terraform Cloud). The backend also handles state locking and consistency checks.
  7. Modules:
    • Modules are reusable components that encapsulate a set of resources and configurations. They promote reusability and organization in large infrastructure setups.
  8. Provisioners:
    • Scripts or commands executed on a resource during its creation or destruction. They are used for bootstrapping or configuration management tasks.

Terraform Workflow in Architecture

  1. Initialization:
    • terraform init initializes the working directory, downloads providers, and configures the backend.
  2. Configuration Parsing:
    • Terraform Core reads the configuration files and builds a resource dependency graph.
  3. State Management:
    • Terraform reads the current state from the state file stored in the backend.
  4. Planning:
    • terraform plan generates an execution plan by comparing the current state with the desired state in the configuration files.
  5. Execution:
    • terraform apply executes the plan, making the necessary changes to achieve the desired state.
  6. Provisioning:
    • Provisioners run scripts or commands to configure resources post-creation.
  7. State Update:
    • After applying changes, Terraform updates the state file to reflect the current state of the infrastructure.

Example of terraform code with list of commands to run

Example Terraform Code

Here’s an example of Terraform code to create an AWS EC2 instance.

main.tf

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"  # Amazon Linux 2 AMI ID
  instance_type = "t2.micro"

  tags = {
    Name = "ExampleInstance"
  }
}

List of Commands to Run

  1. Initialize Terraform:
    • This command sets up your working directory and downloads the necessary provider plugins.
terraform init

Validate the Configuration:

  • This command checks your configuration files for syntax errors.
terraform validate

Generate an Execution Plan:

  • This command shows what actions Terraform will take to achieve the desired state defined in your configuration files.
terraform plan

Apply the Configuration:

  • This command creates or updates the resources as defined in your configuration files.
terraform apply

Check the State:

  • This command shows the current state of the resources managed by Terraform.
terraform show

Destroy the Infrastructure:

  • This command removes all the resources defined in your configuration files.
terraform destroy

Complete Workflow

terraform init
terraform validate
terraform plan
terraform apply
terraform show
terraform destroy

What are block you find in terraform code ? Describe each block at high level?

In Terraform code, several key blocks are commonly used to define and manage infrastructure. Here are the main blocks and a high-level description of each:

1. Provider Block

  • Purpose: Specifies the provider (cloud or service) that Terraform will interact with.
  • Example:
provider "aws" {
  region = "us-west-2"
}

Description: Configures the provider settings, such as region, authentication details, and any other necessary options for connecting to the service.

2. Resource Block

  • Purpose: Defines a piece of infrastructure that Terraform will manage.
  • Example:
resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Description: Specifies the type of resource (e.g., aws_instance) and its configuration. Each resource block includes parameters and attributes needed to create and manage the resource.

3. Variable Block

  • Purpose: Declares input variables that can be used to parameterize and customize the configuration.
  • Example:
variable "instance_type" {
  default = "t2.micro"
}

Description: Defines a variable with optional type, default value, and description. Variables allow for reusability and flexibility in the Terraform code.

4.Output Block

  • Purpose: Defines output values that are returned after applying the configuration.
  • Example:
output "instance_id" {
  value = aws_instance.example.id
}

Description: Specifies what information to output after resource creation, such as resource IDs, IP addresses, or other important details. Outputs can be used for further automation or as inputs to other configurations.

5. Module Block

  • Purpose: Encapsulates reusable configuration components.
  • Example:
module "web_server" {
  source = "./modules/web_server"
  instance_type = var.instance_type
}

Description: Calls a module, which is a self-contained package of Terraform configuration that can be reused and shared. Modules promote organization and maintainability.

6. Data Block

  • Purpose: Retrieves information about existing resources for use in your configuration.
  • Example
data "aws_ami" "latest_amazon_linux" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}
  • Description: Queries and fetches data from providers without creating or managing the resource. Useful for referencing existing resources or dynamically configuring resources based on existing data.

7. Locals Block

  • Purpose: Defines local values that can be used within the configuration for simplification and readability.
  • Example
locals {
  instance_name = "example-instance"
}
  • Description: Declares local variables that are calculated from expressions, helping to avoid repetition and making configurations easier to read and maintain.

8. Terraform Block

  • Purpose: Configures settings for the Terraform project.
  • Example
terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "path/to/my/key"
    region = "us-west-2"
  }
}

Description: Specifies settings like the backend for state storage, required provider versions, and other meta-configuration settings for Terraform.

Blocks in Terraform Code (In Line)

  1. Provider Block: Specifies the cloud provider or service.
  2. Resource Block: Defines infrastructure components to be created or managed.
  3. Variable Block: Declares variables for customization.
  4. Output Block: Defines outputs to display or pass information.
  5. Module Block: Encapsulates and reuses sets of resources and configurations.
  6. Data Block: Retrieves information about existing resources.
  7. Locals Block: Defines local values to simplify and manage configuration logic.
  8. Terraform Block: Configures Terraform settings and backend for state storage.

What is Provisioner with examples for AWS

Terraform Provisioner

Provisioners in Terraform are used to execute scripts or commands on a local or remote machine as part of resource creation or destruction. They are useful for bootstrapping or configuring resources after they have been created.

Types of Provisioners

  1. local-exec: Executes a command locally on the machine running Terraform.
  2. remote-exec: Executes a command on a remote resource via SSH or WinRM.
  3. file: Transfers files from the machine running Terraform to the newly created resource.

Examples for AWS

Using remote-exec Provisioner with AWS EC2

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  key_name      = var.key_name

  provisioner "remote-exec" {
    connection {
      type        = "ssh"
      user        = "ec2-user"
      private_key = file("~/.ssh/id_rsa")
      host        = self.public_ip
    }

    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
      "sudo systemctl start nginx",
      "sudo systemctl enable nginx"
    ]
  }
}

Explanation

  • Provider Block: Configures the AWS provider.
  • Resource Block: Defines an EC2 instance resource.
  • Provisioner Block: Uses remote-exec to SSH into the instance and run commands.

Using local-exec Provisioner with AWS EC2

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  key_name      = var.key_name

  provisioner "local-exec" {
    command = "echo ${self.public_ip} >> ip_addresses.txt"
  }
}

Explanation

  • Provider Block: Configures the AWS provider.
  • Resource Block: Defines an EC2 instance resource.
  • Provisioner Block: Uses local-exec to run a command on the local machine to append the public IP of the EC2 instance to a file.

Using file Provisioner with AWS EC2

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  key_name      = var.key_name

  provisioner "file" {
    source      = "scripts/setup.sh"
    destination = "/tmp/setup.sh"

    connection {
      type        = "ssh"
      user        = "ec2-user"
      private_key = file("~/.ssh/id_rsa")
      host        = self.public_ip
    }
  }

  provisioner "remote-exec" {
    connection {
      type        = "ssh"
      user        = "ec2-user"
      private_key = file("~/.ssh/id_rsa")
      host        = self.public_ip
    }

    inline = [
      "chmod +x /tmp/setup.sh",
      "sudo /tmp/setup.sh"
    ]
  }
}

Explanation

  • Provider Block: Configures the AWS provider.
  • Resource Block: Defines an EC2 instance resource.
  • File Provisioner: Transfers a script from the local machine to the EC2 instance.
  • Remote-Exec Provisioner: Executes the transferred script on the EC2 instance.

Provisioners are powerful tools in Terraform for customizing and configuring resources during the provisioning process.

What are Variable use in terraform using AWS examples

Variables in Terraform

Variables in Terraform are used to parameterize and customize configurations, allowing you to make your configurations more flexible and reusable. Variables can be defined, assigned default values, and used within your Terraform configuration files.

Types of Variables

  1. Input Variables: These are defined in a variable block and can be provided values via the command line, environment variables, or a .tfvars file.
  2. Output Variables: These are defined in an output block and return values from your Terraform configuration.

Example: Using Variables with AWS

Step 1: Define Input Variables

Create a file called variables.tf to define input variables.

variable "region" {
  description = "The AWS region to deploy resources"
  type        = string
  default     = "us-west-2"
}

variable "instance_type" {
  description = "The type of instance to deploy"
  type        = string
  default     = "t2.micro"
}

variable "key_name" {
  description = "The name of the SSH key pair"
  type        = string
}

variable "ami_id" {
  description = "The AMI ID to use for the instance"
  type        = string
  default     = "ami-0c55b159cbfafe1f0"
}

Step 2: Use Variables in Configuration

Create a file called main.tf to use the variables in your resource definitions.

provider "aws" {
  region = var.region
}

resource "aws_instance" "example" {
  ami           = var.ami_id
  instance_type = var.instance_type
  key_name      = var.key_name

  tags = {
    Name = "ExampleInstance"
  }
}

Step 3: Create a .tfvars File (Optional)

Create a file called terraform.tfvars to assign values to the variables.

key_name = "my-ssh-key"

Step 4: Initialize and Apply

Run the following commands to initialize Terraform, validate the configuration, plan the changes, and apply the configuration.

terraform init
terraform validate
terraform plan
terraform apply

Explanation

  • Provider Block: Uses the var.region variable to set the AWS region.
  • Resource Block: Uses variables (var.ami_id, var.instance_type, var.key_name) to configure the EC2 instance.
  • Variables File (variables.tf): Defines the variables with descriptions, types, and default values.
  • Terraform Variables File (terraform.tfvars): Assigns values to the variables.

Using Variables with Different Methods

Command Line

You can also pass variable values directly via the command line:

terraform apply -var="key_name=my-ssh-key" -var="instance_type=t2.small"

Environment Variables

Set environment variables to pass values:

export TF_VAR_key_name="my-ssh-key"
export TF_VAR_instance_type="t2.small"
terraform apply

Output Variables

Define output variables to capture and display information after applying the configuration.

output "instance_id" {
  description = "The ID of the created instance"
  value       = aws_instance.example.id
}

output "public_ip" {
  description = "The public IP address of the instance"
  value       = aws_instance.example.public_ip
}

Example Usage

After running terraform apply, the output variables will display the instance ID and public IP.

Outputs:

instance_id = "i-0abcd1234efgh5678"
public_ip = "203.0.113.0"

What is terraform backend with examples?

Terraform Backend

A Terraform backend determines how and where Terraform stores its state data files. By default, Terraform uses a local backend, which stores the state file on the local disk. However, using a remote backend allows multiple team members to share the same state file and enables advanced features such as state locking and remote operations.

Types of Backends

  1. Local Backend: Stores the state file on the local disk.
  2. Remote Backend: Stores the state file in a remote location, such as AWS S3, Azure Blob Storage, Google Cloud Storage, HashiCorp Consul, or Terraform Cloud.

Benefits of Remote Backends

  • State Locking: Prevents simultaneous state modifications by multiple users.
  • Remote Operations: Run Terraform commands remotely, reducing dependencies on local environments.
  • Collaboration: Enables multiple team members to work on the same Terraform project.
  • Security: Provides better security for sensitive state data by storing it in a secure remote location.

Example: Using AWS S3 as a Terraform Backend

Step 1: Configure the S3 Backend

Create a file called main.tf and configure the S3 backend.

terraform {
  backend "s3" {
    bucket         = "my-terraform-state-bucket"
    key            = "path/to/my/key"
    region         = "us-west-2"
    dynamodb_table = "my-lock-table"  # Optional, for state locking
  }
}

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Step 2: Initialize the Backend

Run the terraform init command to initialize the backend. This command will configure Terraform to use the specified S3 bucket for storing the state file.

terraform init

Step 3: Apply the Configuration

Run the terraform apply command to create the resources and store the state file in the S3 bucket.

terraform apply

Explanation

  • Backend Block: Configures Terraform to use an S3 bucket for storing the state file. The bucket parameter specifies the name of the S3 bucket, the key parameter specifies the path within the bucket where the state file will be stored, and the region parameter specifies the AWS region.
  • Optional DynamoDB Table: The dynamodb_table parameter is optional and specifies a DynamoDB table used for state locking to prevent concurrent modifications to the state file.

Example: Using Terraform Cloud as a Backend

Terraform Cloud provides a remote backend with additional features like workspaces, VCS integration, and remote runs.

Step 1: Configure the Terraform Cloud Backend

Create a file called main.tf and configure the Terraform Cloud backend.

terraform {
  backend "remote" {
    organization = "my-organization"
    
    workspaces {
      name = "my-workspace"
    }
  }
}

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Step 2: Initialize the Backend

Run the terraform init command to initialize the backend. This command will configure Terraform to use Terraform Cloud for storing the state file.

terraform init

Step 3: Apply the Configuration

Run the terraform apply command to create the resources and store the state file in Terraform Cloud.

terraform apply

Explanation

  • Backend Block: Configures Terraform to use Terraform Cloud as the backend. The organization parameter specifies the Terraform Cloud organization, and the workspaces block specifies the workspace name.
  • Terraform Cloud Backend: Provides additional features such as state locking, remote runs, and collaboration.

What is terraform module with examples?

Terraform Module

A Terraform module is a container for multiple resources that are used together. Modules are used to create reusable, shareable, and organized configurations that promote best practices and reduce code duplication.

Benefits of Using Modules

  • Reusability: Write a module once and reuse it across multiple configurations.
  • Organization: Break down complex configurations into smaller, manageable pieces.
  • Consistency: Ensure consistent configurations across different environments.
  • Maintainability: Simplify updates and maintenance by managing common resources in one place.

Basic Structure of a Module

A module typically consists of the following files:

  1. main.tf: Contains the main resources to be managed.
  2. variables.tf: Defines input variables.
  3. outputs.tf: Defines output values.

Example: Creating and Using a Terraform Module

Step 1: Create the Module

Create a directory called modules/web_server and add the following files.

modules/web_server/main.tf

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = var.instance_name
  }
}

modules/web_server/variables.tf

variable "ami_id" {
  description = "The AMI ID to use for the instance"
  type        = string
}

variable "instance_type" {
  description = "The type of instance to use"
  type        = string
  default     = "t2.micro"
}

variable "instance_name" {
  description = "The name of the instance"
  type        = string
}

modules/web_server/outputs.tf

output "instance_id" {
  description = "The ID of the instance"
  value       = aws_instance.web.id
}

output "public_ip" {
  description = "The public IP of the instance"
  value       = aws_instance.web.public_ip
}

Step 2: Use the Module

Create a file called main.tf in the root directory and use the module.

main.tf

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

module "web_server" {
  source        = "./modules/web_server"
  ami_id        = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  instance_name = "ExampleInstance"
}

Step 3: Initialize and Apply

Run the following commands to initialize and apply the configuration.

terraform init
terraform apply

Explanation

  • Module Directory: The modules/web_server directory contains the module’s configuration files.
    • main.tf: Defines the resources managed by the module.
    • variables.tf: Defines input variables used by the module.
    • outputs.tf: Defines output values produced by the module.
  • Root Configuration: The main.tf file in the root directory uses the module by specifying the source attribute, which points to the module’s directory. It also provides values for the module’s input variables.

Using Public Modules

Terraform has a public registry of modules that can be used to quickly deploy common infrastructure patterns.

Example: Using a Module from the Terraform Registry

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

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

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-west-2a", "us-west-2b"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.3.0/24", "10.0.4.0/24"]

  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Terraform = "true"
    Environment = "dev"
  }
}

Explanation

  • Provider Block: Configures the AWS provider.
  • Module Block: Uses a module from the Terraform Registry (terraform-aws-modules/vpc/aws) to create a VPC.
    • source: Specifies the module’s source.
    • version: Specifies the version of the module.
    • Input Variables: Provides values for the module’s input variables, such as name, cidr, azs, and subnets.

List of top 20 modules in terraform

These modules are widely used for setting up various infrastructure components and services.

  1. terraform-aws-modules/vpc/aws
    • Manages AWS VPC and associated resources.
  2. terraform-aws-modules/security-group/aws
    • Manages AWS Security Groups and rules.
  3. terraform-aws-modules/eks/aws
    • Manages AWS EKS (Kubernetes) clusters.
  4. terraform-aws-modules/s3-bucket/aws
    • Manages AWS S3 buckets.
  5. terraform-aws-modules/rds/aws
    • Manages AWS RDS (Relational Database Service) instances.
  6. terraform-aws-modules/terraform-aws-lambda
    • Manages AWS Lambda functions.
  7. terraform-aws-modules/alb/aws
    • Manages AWS Application Load Balancers.
  8. terraform-aws-modules/cloudfront/aws
    • Manages AWS CloudFront distributions.
  9. terraform-aws-modules/autoscaling/aws
    • Manages AWS Auto Scaling groups.
  10. terraform-google-modules/network/google
    • Manages Google Cloud VPC networks.
  11. terraform-google-modules/kubernetes-engine/google
    • Manages Google Kubernetes Engine (GKE) clusters.
  12. terraform-google-modules/iam/google
    • Manages Google Cloud IAM (Identity and Access Management) roles and policies.
  13. terraform-google-modules/cloud-storage/google
    • Manages Google Cloud Storage buckets.
  14. terraform-google-modules/sql-db/google
    • Manages Google Cloud SQL databases.
  15. terraform-azure-modules/terraform-azurerm-vnet
    • Manages Azure Virtual Network (VNet).
  16. terraform-azure-modules/terraform-azurerm-storage-account
    • Manages Azure Storage Accounts.
  17. terraform-azure-modules/terraform-azurerm-aks
    • Manages Azure Kubernetes Service (AKS) clusters.
  18. terraform-azure-modules/terraform-azurerm-key-vault
    • Manages Azure Key Vault.
  19. terraform-azure-modules/terraform-azurerm-vm
    • Manages Azure Virtual Machines.
  20. cloudposse/terraform-aws-ecs-web-app
    • Manages ECS (Elastic Container Service) web applications on AWS.

What is terraform workspace with commands?

Terraform Workspace

Terraform workspaces allow you to manage multiple states within a single Terraform configuration. This feature is useful for managing different environments (e.g., development, staging, production) without having to create separate configurations for each.

Key Concepts

  • Default Workspace: The initial workspace created by Terraform, typically used for the main environment.
  • Custom Workspaces: Additional workspaces created to manage separate states for different environments or purposes.

Commands for Managing Workspaces

Create a New Workspace

To create a new workspace, use the terraform workspace new command:

terraform workspace new <workspace_name>

Example:
terraform workspace new development

List Workspaces

To list all available workspaces, use the terraform workspace list command:

terraform workspace list

Example Output:
* default
  development
  staging
  production

The * indicates the currently selected workspace.

Select a Workspace

To switch to a different workspace, use the terraform workspace select command:

terraform workspace select <workspace_name>

Example:

terraform workspace select staging

Show Current Workspace

To display the name of the current workspace, use the terraform workspace show command:

terraform workspace show

Example Output:

development

Delete a Workspace

To delete a workspace, use the terraform workspace delete command. Note that you cannot delete the currently selected workspace:

terraform workspace delete <workspace_name>

Example:

terraform workspace delete staging

Using Workspaces in Configuration

You can reference the current workspace in your Terraform configuration using the terraform.workspace built-in variable. This can be useful for managing environment-specific settings.

Example

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

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "example-${terraform.workspace}"
  }
}

Example Workflow

  1. Create Workspaces:
terraform workspace new development
terraform workspace new staging
terraform workspace new production

2.Select a Workspace:

terraform workspace select development

3.Initialize and Apply:

terraform init
terraform apply

Repeat the selection and apply steps for other workspaces as needed.

Summary

  • Workspaces allow for managing multiple states within a single configuration, useful for different environments.
  • Commands:
    • terraform workspace new <name>: Create a new workspace.
    • terraform workspace list: List all workspaces.
    • terraform workspace select <name>: Select a workspace.
    • terraform workspace show: Show the current workspace.
    • terraform workspace delete <name>: Delete a workspace.

By using workspaces, you can efficiently manage separate environments while maintaining a single set of configuration files.

What is difference between terraform and ansible in tabular form

FeatureTerraformAnsible
Primary UseInfrastructure as Code (IaC)Configuration Management and Application Deployment
Configuration LanguageHashiCorp Configuration Language (HCL) or JSONYAML (with Jinja2 templating)
State ManagementMaintains state files to track resource configurationsStateless (does not maintain state by default)
ProvisioningFocuses on provisioning infrastructure (cloud, VMs)Focuses on configuration management and application deployment on existing infrastructure
Execution ModelDeclarativeImperative
IdempotencyEnsures resources are in the desired stateEnsures tasks are idempotent (achieves desired state)
Parallel ExecutionBuilt-in parallelism for resource creationCan execute tasks in parallel using forks
Plugins and ModulesUses providers for different services (AWS, Azure, etc.)Uses modules and roles for different tasks
Dependency ManagementAutomatically manages dependencies between resourcesManual dependency management using task ordering
Main Use CasesInfrastructure setup (e.g., VPCs, subnets, instances)Configuration management (e.g., installing software, managing services)
IntegrationIntegrates with various cloud providers and servicesIntegrates with various services and tools (e.g., Docker, Kubernetes)
Learning CurveModerate (due to HCL and state management)Moderate (due to YAML syntax and task-based approach)
Community and SupportLarge community, extensive documentation and modulesLarge community, extensive documentation and modules
Execution ModeExecutes from the local machine where Terraform is runExecutes tasks on remote hosts via SSH or WinRM
OrchestrationNot designed for complex orchestration tasksCan handle complex orchestration scenarios
Version ControlCode can be versioned, and state can be stored in VCSPlaybooks and roles can be versioned in VCS
Agent RequirementAgentlessAgentless

List of command of terraform command

CommandDescription
terraform initInitializes a Terraform configuration directory.
terraform validateValidates the Terraform configuration files.
terraform planGenerates and shows an execution plan.
terraform applyExecutes the actions proposed in the Terraform plan.
terraform destroyDestroys the Terraform-managed infrastructure.
terraform fmtFormats Terraform configuration files to a canonical style.
terraform taintMarks a resource for recreation during the next apply.
terraform untaintUnmarks a resource as tainted.
terraform showDisplays the current state or a saved plan.
terraform outputReads an output variable from a state file.
terraform stateAdvanced state management (list, show, pull, push, etc.).
terraform refreshUpdates local state file against real resources.
terraform importImports existing infrastructure into Terraform.
terraform workspaceManages Terraform workspaces (new, list, select, delete).
terraform graphGenerates a visual graph of Terraform resources.
terraform consoleProvides an interactive console for evaluating expressions.
terraform loginLogs in to Terraform Cloud or Enterprise.
terraform logoutLogs out of Terraform Cloud or Enterprise.
terraform providersDisplays the providers required by the configuration.
terraform versionDisplays the Terraform version and other related info.
terraform debugEnables debug output for more detailed information.
terraform getDownloads and installs modules needed for the configuration.
terraform apply -auto-approveExecutes a plan without requiring interactive approval.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments