Terraform is an infrastructure as code tool that lets you build, change, and version cloud and on-prem resources safely and efficiently.
HashiCorp Terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all of your infrastructure throughout its lifecycle. Terraform can manage low-level components like compute, storage, and networking resources, as well as high-level components like DNS entries and SaaS features.
Terraform is an open-source Infrastructure as Code (IaC) software tool created by HashiCorp. It enables developers to define and provide data center infrastructure using a declarative configuration language. Terraform plans and creates infrastructure resources on cloud providers such as Amazon Web Services (AWS), Microsoft Azure, Google Cloud Platform, and many others.
Terraform allows developers to define and manage infrastructure resources in a safe and efficient way. It uses a unique approach of abstracting resources into modules, which enables reusability and modularity. These modules can be shared, versioned, and distributed, promoting collaboration and consistency in infrastructure management.
Terraform vs Ansible
Terraform and Ansible are both popular tools for managing infrastructure, but they serve different purposes.
Terraform is an Infrastructure as Code (IaC) tool that is primarily used for creating, managing, and provisioning infrastructure on various cloud providers such as AWS, Azure, and Google Cloud Platform. It enables developers to define infrastructure resources declaratively using a high-level language. Terraform uses a state file to keep track of the current state of infrastructure resources, ensuring that resources are created and managed consistently and efficiently.
Ansible, on the other hand, is a Configuration Management (CM) tool that is primarily used for managing the configuration of servers and other infrastructure resources. It enables developers to define configuration tasks using a simple and human-readable language called YAML. Ansible uses an agentless approach, which means that it does not require any software to be installed on the target machines. Ansible uses SSH to connect to target machines and run tasks.
While Terraform and Ansible can both be used for managing infrastructure, they serve different use cases.
Terraform is best suited for managing infrastructure resources such as virtual machines, storage, and networking.
Ansible is best suited for managing the configuration of servers and other infrastructure resources such as software installation, security hardening, and user management
Terraform and Ansible can be complementary tools for managing infrastructure. Terraform can be used to provision infrastructure resources, and Ansible can be used to manage and configure those resources. Together, they enable developers to build, deploy, and manage infrastructure in a consistent, efficient, and secure way.
Terraform installation
For Windows:
Go to the official Terraform website (https://www.terraform.io/downloads.html) and download the appropriate package for Windows.
Extract the downloaded package to a location of your choice. For example, you can extract the package to
C:\terraform
.Add the
terraform.exe
binary to your system'sPATH
environment variable. You can do this by following these steps:Right-click on "Computer" or "This PC" and select "Properties".
Click on "Advanced system settings" on the left-hand side.
Click on "Environment Variables".
Under "System variables", find the "Path" variable and click on "Edit".
Click on "New" and add the path to the directory where you extracted Terraform (e.g.
C:\terraform
).Click "OK" on all dialog boxes to save the changes.
Verify the installation by opening a command prompt and running the following command:
> terraform --v
ersion
This should output the version number of Terraform that you installed.
Go to the official Terraform website (https://www.terraform.io/downloads.html) and download the appropriate package for Linux.
Extract the downloaded package to a location of your choice. For example, you can extract the package to
/usr/local/terraform
.Add the
terraform
binary to your system'sPATH
environment variable. You can do this by running the following command:
$ export PATH=$PATH:/usr/local/terraform
- Verify the installation by running the following command:
$ terraform --version
This should output the version number of Terraform that you installed.
That's it! You have successfully installed Terraform on your Windows or Linux system. You can now start using it to manage your infrastructure resources.
Note: If you're using a package manager like Homebrew on macOS or apt on Linux, you can use it to install Terraform as well. The installation instructions for other operating systems and package managers can be found on the official Terraform website.
Terraform Archicture
Terraform uses a client-server architecture where the client is responsible for managing the infrastructure resources and the server maintains the state of the managed resources. Here is a high-level overview of the Terraform architecture:
Terraform Configuration Files: Terraform uses configuration files written in HashiCorp Configuration Language (HCL) to define the desired infrastructure resources. These files specify what resources to create, how to configure them, and any dependencies between them.
Terraform CLI: The Terraform Command Line Interface (CLI) is the primary tool used to interact with Terraform. It provides a set of commands for initializing, planning, applying, and destroying infrastructure resources.
Terraform Providers: Terraform providers are plugins that implement the API for managing specific infrastructure resources. Providers are written in Go and can be distributed as shared libraries or packaged with Terraform.
Terraform State: Terraform uses a state file to track the current state of the managed infrastructure resources. The state file is a JSON file that stores the current configuration and attributes of each resource. The state file can be stored locally, remotely in a backend such as S3, or in a version control system.
Terraform Backend: The Terraform backend is a pluggable component responsible for storing and retrieving the Terraform state. The backend can be configured to use local storage, remote storage, or a combination of both.
Remote APIs: Terraform can interact with remote APIs to manage infrastructure resources. Remote APIs can be cloud providers such as AWS, Azure, or Google Cloud, or custom APIs for managing on-premises resources.
Overall, Terraform's architecture is designed to be modular, scalable, and customizable, allowing developers to manage their infrastructure resources in a flexible and efficient way. The use of a declarative configuration language and a centralized state file ensures that infrastructure resources are managed consistently and reliably. The ability to use plugins for managing resources and integrating with remote APIs makes Terraform a powerful and versatile tool for managing infrastructure.
Terraform Scripts
Terraform scripts define the desired infrastructure as code using the HashiCorp Configuration Language (HCL). These scripts specify the resources to create, configure, and manage on cloud providers or on-premises infrastructure.
A Terraform script consists of one or more resource blocks, each of which defines a specific infrastructure resource. Resource blocks have a type specifying the type of resource to create, and one or more attributes specifying how to configure the resource.
Here's an example Terraform script that creates a single AWS EC2 instance:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "example-instance"
}
}
infrasture Creation
Infrastructure creation refers to the process of building and configuring infrastructure resources using Terraform. Here are the general steps for creating infrastructure with Terraform:
Define the desired infrastructure in a Terraform script: This step involves writing a Terraform script that defines the desired infrastructure resources, such as virtual machines, storage, networking, and databases. The script specifies the resource types, attributes, and dependencies.
Initialize the Terraform environment: This step involves running the
terraform init
command, which initializes the Terraform environment and downloads any necessary plugins for managing the specified infrastructure resources.Generate an execution plan: This step involves running the
terraform plan
command, which generates an execution plan that shows what resources will be created, updated, or destroyed. The execution plan includes a cost estimate for the infrastructure resources and any changes that will be made.Execute the execution plan: This step involves running the
terraform apply
command, which creates or updates the specified infrastructure resources based on the execution plan. This step may take several minutes or hours, depending on the complexity and size of the infrastructure being created.Verify the infrastructure: This step involves verifying that the infrastructure was created correctly and is functioning as expected. This may involve logging into the infrastructure, running tests, or verifying that the desired services are available.
Throughout the infrastructure creation process, Terraform maintains a centralized state file that tracks the current state of the infrastructure resources. The state file can be stored locally or remotely, and can be used to manage and update the infrastructure resources in the future.
Creditenal management
Terraform supports credential management through different methods, depending on the cloud provider or infrastructure resource being managed. Here are some of the common credential management methods used with Terraform:
Environment variables: Terraform can use environment variables to authenticate with cloud providers and infrastructure resources. For example, the
AWS_ACCESS_KEY_ID
andAWS_SECRET_ACCESS_KEY
environment variables can be set to authenticate with AWS. This method is convenient but may expose sensitive information in the environment.Shared credentials file: Terraform can use a shared credentials file to authenticate with cloud providers and infrastructure resources. The shared credentials file can be stored in a centralized location and shared among team members. The shared credentials file can be encrypted for added security.
Provider-specific authentication plugins: Terraform providers can implement their own authentication plugins for managing credentials. For example, the AWS provider supports the AWS CLI configuration file, AWS CLI credentials file, and AWS IAM role-based authentication.
Terraform Cloud: Terraform Cloud is a managed service that provides secure credential management for Terraform. Terraform Cloud uses secure Vault instances to store secrets and credentials, and supports multiple authentication methods, such as SSO, OAuth, and SSH keys.
To use credential management with Terraform, you need to configure the credential management method for the specific cloud provider or infrastructure resource being managed. The configuration may involve setting environment variables, creating a shared credentials file, or configuring a provider-specific authentication plugin.
Terraform also supports using multiple providers and credentials within a single Terraform script. This enables managing multiple cloud providers or infrastructure resources with different credentials and authentication methods.
Terraform commands
Here are some of the most commonly used Terraform commands:
terraform init: Initializes the Terraform working directory and downloads the necessary provider plugins.
terraform plan: Generates an execution plan for the Terraform script, showing what resources will be created, updated, or destroyed.
terraform apply: Executes the Terraform execution plan and applies the changes to the infrastructure resources.
terraform destroy: Destroys the infrastructure resources managed by the Terraform script.
terraform state: Manages the Terraform state file, which tracks the current state of the infrastructure resources.
terraform output: Retrieves the output values of the Terraform script.
terraform console: Opens an interactive console for running Terraform expressions.
terraform providers: Lists the available Terraform provider plugins and their versions.
terraform version: Shows the installed version of Terraform and the provider plugins.
Terraform Scripts
main.tf
provider "aws" {
access_key = "${var.access_key}"
secret_key = "${var.secret_key}"
region = "ap-south-1"
}
resource "aws_instance" "ec2_instance" {
ami = "${var.ami_id}"
count = "${var.number_of_instances}"
subnet_id = "${var.subnet_id}"
instance_type = "${var.instance_type}"
key_name = "${var.ami_key_pair_name}"
}
terraform.tfvars
access_key = "AKIAWekekekekekeH4ZK"
secret_key = "vBjWguekeejnfenienvievninwnwinwnqFo2/"
variables.tf
variable "access_key" {
description = "Access key to AWS console"
}
variable "secret_key" {
description = "Secret key to AWS console"
}
variable "instance_name" {
description = "Name of the instance to be created"
default = "DEMO-instance"
}
variable "instance_type" {
default = "t2.micro"
}
variable "subnet_id" {
description = "The VPC subnet the instance(s) will be created in"
default = "subnet-XXXXXXXXXXXXXXXX"
}
variable "ami_id" {
description = "The AMI to use"
default = "ami-08e5424edfe926b43"
}
variable "number_of_instances" {
description = "number of instances to be created"
default = 1
}
variable "ami_key_pair_name" {
default = "Aditya"
}
###