What is the need of terraform IAAC?
The need for Terraform Infrastructure as Code (IaAC) is driven by several key benefits:
- Consistency and Reproducibility: Terraform allows you to define your infrastructure in code, ensuring that the same configuration can be applied consistently across different environments.
- 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.
- Automation: Terraform automates the provisioning and management of infrastructure, reducing the need for manual intervention and minimizing the risk of human error.
- Scalability: Terraform can efficiently manage complex and large-scale infrastructure, supporting the scaling of resources up or down as needed.
- Declarative Language: Terraform uses a declarative language, where you describe the desired state of your infrastructure, and Terraform takes care of achieving that state.
- Multi-Cloud Support: Terraform supports multiple cloud providers and on-premises environments, allowing for a unified approach to infrastructure management across different platforms.
- 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:
- Terraform
- AWS CloudFormation
- Azure Resource Manager (ARM) Templates
- Google Cloud Deployment Manager
- Ansible
- Puppet
- Chef
- SaltStack
- Pulumi
- Kubernetes
- Juju
- CFEngine
- 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
- Providers:
- Plugins that allow Terraform to interact with APIs of various services (e.g., AWS, Azure, Google Cloud).
- Resources:
- The infrastructure components defined in Terraform configuration files (e.g., virtual machines, storage buckets).
- Modules:
- Reusable and shareable components that encapsulate a set of resources and configurations.
- State:
- The data structure that Terraform uses to map the resources defined in the configuration files to real-world resources.
- Configuration:
- The set of files written in HashiCorp Configuration Language (HCL) that describe the infrastructure.
- Plan:
- A preview of the changes Terraform will make to achieve the desired state defined in the configuration files.
- Apply:
- The command to execute the changes required to reach the desired state of the infrastructure.
- Output Values:
- Data outputs from your Terraform configuration that can be used elsewhere in the configuration or as inputs to other modules.
- Variables:
- Inputs to your Terraform configuration that allow you to parameterize and customize the infrastructure.
- Data Sources:
- Information sources that Terraform can query to get data about external resources.
- Terraform Registry:
- A public directory of modules and providers that can be used to find and share configuration components.
- Terraform Cloud/Enterprise:
- Services offered by HashiCorp for managing Terraform configurations, state, and collaboration in a centralized manner.
- Backend:
- The storage location for Terraform state, which can be local or remote (e.g., S3, Consul).
- Provisioners:
- Used to execute scripts or commands on a local or remote machine as part of resource creation or destruction.
- Workspace:
- An isolated environment for managing different versions or configurations of infrastructure, typically used for managing multiple environments like dev, staging, and production.
- Providers:
- Plugins that connect Terraform to cloud services (e.g., AWS, Azure).
- Resources:
- Individual components you create with Terraform (e.g., servers, databases).
- Modules:
- Reusable packages of Terraform code that help organize and share configurations.
- State:
- A file that keeps track of the current status of your infrastructure.
- Configuration:
- The code files where you define your infrastructure setup.
- Plan:
- A preview of what Terraform will change in your infrastructure.
- Apply:
- The command to make the changes described in your plan.
- Output Values:
- Information from your Terraform setup that can be used elsewhere.
- Variables:
- Inputs to your configuration that make it customizable.
- Data Sources:
- External information that Terraform can use to configure resources.
- Terraform Registry:
- A directory of shared modules and plugins you can use.
- Terraform Cloud/Enterprise:
- Services for managing Terraform configurations and teamwork.
- Backend:
- Where Terraform stores its state file, either locally or remotely.
- Provisioners:
- Scripts or commands run during resource setup or teardown.
- Workspace:
- Isolated environments for different versions or stages (e.g., dev, prod) of your infrastructure.
How terraform works?
- 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.
- 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.
- Run
- 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.
- Run
- Apply:
- Run
terraform apply
to execute the changes required to reach the desired state. Terraform will create, update, or delete resources as needed.
- Run
- 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.
- 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.
- Output:
- After applying changes, Terraform provides outputs that can be used for other processes or referenced in further configurations.
- 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
- Define: Write configuration files.
- Initialize: Set up Terraform with
terraform init
. - Plan: Preview changes with
terraform plan
. - Apply: Execute changes with
terraform apply
. - Manage: Maintain infrastructure state with the state file.
- Update: Modify configurations and reapply as needed.
Terraform Architecture
- Configuration Files:
- Written in HashiCorp Configuration Language (HCL) or JSON, these files define the desired state of your infrastructure.
- Core:
- The core is the heart of Terraform, responsible for reading and interpreting the configuration files, managing the state, and generating execution plans.
- 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.
- 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.
- CLI (Command Line Interface):
- The primary interface for interacting with Terraform. Commands like
init
,plan
,apply
, anddestroy
are used to manage the lifecycle of your infrastructure.
- The primary interface for interacting with Terraform. Commands like
- 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.
- Modules:
- Modules are reusable components that encapsulate a set of resources and configurations. They promote reusability and organization in large infrastructure setups.
- 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
- Initialization:
terraform init
initializes the working directory, downloads providers, and configures the backend.
- Configuration Parsing:
- Terraform Core reads the configuration files and builds a resource dependency graph.
- State Management:
- Terraform reads the current state from the state file stored in the backend.
- Planning:
terraform plan
generates an execution plan by comparing the current state with the desired state in the configuration files.
- Execution:
terraform apply
executes the plan, making the necessary changes to achieve the desired state.
- Provisioning:
- Provisioners run scripts or commands to configure resources post-creation.
- 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
- 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)
- Provider Block: Specifies the cloud provider or service.
- Resource Block: Defines infrastructure components to be created or managed.
- Variable Block: Declares variables for customization.
- Output Block: Defines outputs to display or pass information.
- Module Block: Encapsulates and reuses sets of resources and configurations.
- Data Block: Retrieves information about existing resources.
- Locals Block: Defines local values to simplify and manage configuration logic.
- 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
- local-exec: Executes a command locally on the machine running Terraform.
- remote-exec: Executes a command on a remote resource via SSH or WinRM.
- 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
- Input Variables: These are defined in a
variable
block and can be provided values via the command line, environment variables, or a.tfvars
file. - 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
- Local Backend: Stores the state file on the local disk.
- 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, thekey
parameter specifies the path within the bucket where the state file will be stored, and theregion
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 theworkspaces
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:
- main.tf: Contains the main resources to be managed.
- variables.tf: Defines input variables.
- 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 thesource
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
, andsubnets
.
List of top 20 modules in terraform
These modules are widely used for setting up various infrastructure components and services.
- terraform-aws-modules/vpc/aws
- Manages AWS VPC and associated resources.
- terraform-aws-modules/security-group/aws
- Manages AWS Security Groups and rules.
- terraform-aws-modules/eks/aws
- Manages AWS EKS (Kubernetes) clusters.
- terraform-aws-modules/s3-bucket/aws
- Manages AWS S3 buckets.
- terraform-aws-modules/rds/aws
- Manages AWS RDS (Relational Database Service) instances.
- terraform-aws-modules/terraform-aws-lambda
- Manages AWS Lambda functions.
- terraform-aws-modules/alb/aws
- Manages AWS Application Load Balancers.
- terraform-aws-modules/cloudfront/aws
- Manages AWS CloudFront distributions.
- terraform-aws-modules/autoscaling/aws
- Manages AWS Auto Scaling groups.
- terraform-google-modules/network/google
- Manages Google Cloud VPC networks.
- terraform-google-modules/kubernetes-engine/google
- Manages Google Kubernetes Engine (GKE) clusters.
- terraform-google-modules/iam/google
- Manages Google Cloud IAM (Identity and Access Management) roles and policies.
- terraform-google-modules/cloud-storage/google
- Manages Google Cloud Storage buckets.
- terraform-google-modules/sql-db/google
- Manages Google Cloud SQL databases.
- terraform-azure-modules/terraform-azurerm-vnet
- Manages Azure Virtual Network (VNet).
- terraform-azure-modules/terraform-azurerm-storage-account
- Manages Azure Storage Accounts.
- terraform-azure-modules/terraform-azurerm-aks
- Manages Azure Kubernetes Service (AKS) clusters.
- terraform-azure-modules/terraform-azurerm-key-vault
- Manages Azure Key Vault.
- terraform-azure-modules/terraform-azurerm-vm
- Manages Azure Virtual Machines.
- 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
- 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
Feature | Terraform | Ansible |
---|---|---|
Primary Use | Infrastructure as Code (IaC) | Configuration Management and Application Deployment |
Configuration Language | HashiCorp Configuration Language (HCL) or JSON | YAML (with Jinja2 templating) |
State Management | Maintains state files to track resource configurations | Stateless (does not maintain state by default) |
Provisioning | Focuses on provisioning infrastructure (cloud, VMs) | Focuses on configuration management and application deployment on existing infrastructure |
Execution Model | Declarative | Imperative |
Idempotency | Ensures resources are in the desired state | Ensures tasks are idempotent (achieves desired state) |
Parallel Execution | Built-in parallelism for resource creation | Can execute tasks in parallel using forks |
Plugins and Modules | Uses providers for different services (AWS, Azure, etc.) | Uses modules and roles for different tasks |
Dependency Management | Automatically manages dependencies between resources | Manual dependency management using task ordering |
Main Use Cases | Infrastructure setup (e.g., VPCs, subnets, instances) | Configuration management (e.g., installing software, managing services) |
Integration | Integrates with various cloud providers and services | Integrates with various services and tools (e.g., Docker, Kubernetes) |
Learning Curve | Moderate (due to HCL and state management) | Moderate (due to YAML syntax and task-based approach) |
Community and Support | Large community, extensive documentation and modules | Large community, extensive documentation and modules |
Execution Mode | Executes from the local machine where Terraform is run | Executes tasks on remote hosts via SSH or WinRM |
Orchestration | Not designed for complex orchestration tasks | Can handle complex orchestration scenarios |
Version Control | Code can be versioned, and state can be stored in VCS | Playbooks and roles can be versioned in VCS |
Agent Requirement | Agentless | Agentless |
List of command of terraform command
Command | Description |
---|---|
terraform init | Initializes a Terraform configuration directory. |
terraform validate | Validates the Terraform configuration files. |
terraform plan | Generates and shows an execution plan. |
terraform apply | Executes the actions proposed in the Terraform plan. |
terraform destroy | Destroys the Terraform-managed infrastructure. |
terraform fmt | Formats Terraform configuration files to a canonical style. |
terraform taint | Marks a resource for recreation during the next apply. |
terraform untaint | Unmarks a resource as tainted. |
terraform show | Displays the current state or a saved plan. |
terraform output | Reads an output variable from a state file. |
terraform state | Advanced state management (list, show, pull, push, etc.). |
terraform refresh | Updates local state file against real resources. |
terraform import | Imports existing infrastructure into Terraform. |
terraform workspace | Manages Terraform workspaces (new, list, select, delete). |
terraform graph | Generates a visual graph of Terraform resources. |
terraform console | Provides an interactive console for evaluating expressions. |
terraform login | Logs in to Terraform Cloud or Enterprise. |
terraform logout | Logs out of Terraform Cloud or Enterprise. |
terraform providers | Displays the providers required by the configuration. |
terraform version | Displays the Terraform version and other related info. |
terraform debug | Enables debug output for more detailed information. |
terraform get | Downloads and installs modules needed for the configuration. |
terraform apply -auto-approve | Executes a plan without requiring interactive approval. |