Terraform

Q: What is Terraform?

Ans:

Terraform is an infrastructure as code (IaC) tool that lets you build, edit, and version infrastructure in a secure and efficient manner. 

This covers both low-level and high-level components, such as compute instances, memory, and networking, as well as DNS records, SaaS services, and so on. 

Terraform is capable of managing both third-party services and unique in-house solutions. 

Terraform uses configuration files to tell it which components are needed to run a single application or a whole datacenter. Amazon Web Services, 

IBM Cloud, Google Cloud, Platform, DigitalOcean, Linode, Microsoft Azure, Oracle Cloud Infrastructure, OVH, VMware, vSphere, OpenNebula, and OpenStack all use Terraform.

Q: What are the key features of Terraform?

Ans:

  • Following are the key features of Terraform:
  • Infrastructure as Code: Terraform's high-level configuration language is used to describe your infrastructure in declarative configuration files that are human-readable. You may now generate a blueprint that you can edit, share, and reuse.
  • Execution Strategies: Before making any infrastructure modifications, Terraform develops an execution plan that describes what it will do and asks for your agreement. Before Terraform produces, upgrades, or destroys infrastructure, you can evaluate the changes.
  • Graph of Resources: Terraform develops or alters non-dependent resources while simultaneously building a resource graph. This allows Terraform to construct resources as quickly as possible while also providing you with more information about your infrastructure.
  • Automation of Change: Terraform can automate the application of complex changesets to your infrastructure with little to no human intervention. Terraform identifies what happened when you update configuration files and provides incremental execution plans that take dependencies into account.

Q:What do you mean by terraform init in the context of Terraform?

Ans:

The terraform init command creates a working directory in which Terraform configuration files can be found. After creating a new Terraform configuration or cloning an old one from version control, run this command first. It is safe to use this command more than once. Despite the fact that successive runs may result in errors, this command will never overwrite your current settings or state.

Syntax:

terraform init [options]

The following options can be used in conjunction with the init command :

-input=true: This option is set to true if the user input is mandatory. If no user input is provided, an error will be thrown.

-lock=false: This option is used to disable the locking of state files during state-related actions.

-lock-timeout=<duration>: This option is used to override the time it takes Terraform to get a state lock. If the lock is already held by another process, the default is 0s (zero seconds), which results in an immediate failure.

-no-color: This option disables the color codes in the command output.

-upgrade: This option can be chosen to upgrade modules and plugins throughout the installation process.

Q: What are the different terraform Commands?

Ans:

  • terraform init: Initializes remote backends; downloads providers and remote modules defined in your configuration.
  • terraform init -upgrade: used to upgrade the existing downloaded providers.
  • terraform plan: generates the execution plan for the infrastructure creation or updation.
  • terraform apply: creates or updates the infrastructure after requesting confirmation from user.
  • terraform apply –auto-approve: creates or updates the infrastructure; user approval stage is skipped.
  • terraform destroy: deletes the infrastructure after requesting confirmation from user.
  • terraform destroy –auto-approve: deletes the infrastructure; user approval stage is skipped.
  • terraform fmt: scans the current directory for configuration files and formats them according to the HCP canonical style and format.
  • terraform fmt –recursive: scans the current directory as well as the sub directories for configuration files and formats them according to the HCP canonical style and format.
  • terraform show: provides a human-readable output from a state or plan file.

Q: How can you use the same provider in Terraform with different configurations?

Ans: By using alias argument in the provider block.

Q: You have a Terraform configuration file with no resources. What happens when you run the terraform apply command?

Ans: Terraform will destroy all the resources. Starting an empty run with terraform apply command is exactly the same as starting the terraform destroy run.

Q: What happens if a resource was created successfully in terraform but failed during provisioning?

Ans: This is an unlikely scenario, but when this happens, the resource is marked as tainted and can be recreated by restarting the terraform run.

Q: How can you import existing resources under Terraform Management?

Ans: By using the terraform import command.

Q: Which command can be used to preview the terraform execution plan?

Ans: The terraform plan command generates the execution plan of the changes Terraform will do to the infrastructure.

Q: Which command can be used to reconcile the Terraform state with the actual real-world infrastructure?

Ans: The terraform apply -refresh-only command is used to reconcile Terraform state with the actual real-world infrastructure. It is the new alternative to the terraform refresh command, which is now deprecated.

Q: Which command can be used to switch between workspaces when using Terraform Cloud?

Ans: The terraform workspace select <workspace-name> command is used to choose a different workspace.

Q: Which command is used to perform syntax validation on terraform configuration files?

Ans: The terraform validate command is used to verify whether a configuration is syntactically valid and internally consistent.

Q: Which command is used to create new workspaces in the Terraform cloud?

Ans: The terraform workspace new <workspace-name> command is used to create a new workspace.

Q: Write a terraform script to launch an EC2 instance in AWS?

Ans:
provider "aws" {
  region     = "us-west-2"
}
resource "aws_instance" "Dheeraj" {
  ami           = "ami-00970f57473724c10"
  instance_type = "t2.micro"

}
Note: you can provide your access key and secret key with aws configure command in terminal

Q: How import command is used in Terraform?

Ans:
Use Case
Explanation
Import old resources
Organizations can import resources created with alternative tools or methods 
Import resources created outside Terraform.
When Terraform was deployed, it may not have been universally adopted. As such, there may have been infrastructure additions/amendments made outside of Terraform
Loss of Terraform state file.
The state file can be deleted or become irreversibly corrupt
Re-factoring / Amending Terraform code structure
As an environment scales, there may be a need to re-factor or re-structure Terraform modules and other constructs
terraform import <resource_type>.<resource_name> <id_of_resource> 
<resource_type>  =>the type of the resource being imported i.e. aws_instance
<resource_name>  =>the name you are assigning to this resource in Terraform i.e. web02
<id_of_resource> =>The ID that your cloud provider allocated to the resource i.e. i-0704591175edb7b20


Q: what is module in Terraform ?

Ans:
In Terraform, a module is a container for a set of related resources that are used together to perform a specific task. Modules allow users to organize and reuse their infrastructure code, making it easier to manage complex infrastructure deployments.
Modules are defined using the ‘module ‘block in Terraform configuration. A module block takes the following arguments:
  • source: The source location of the module. This can be a local path or a URL.
  • name: The name of the module. This is used to reference the module in other parts of the configuration.
  • version: The version of the module to use. This is optional and can be used to specify a specific version of the module.
module "vpc" {
  source ="../VPC_network"
}
Modules can be nested, allowing users to create complex infrastructure architectures using a hierarchical structure. Modules can also be published and shared on the Terraform Registry, enabling users to reuse and extend the infrastructure code of others.

Q: what is state file in Terraform?

Ans:
This file stores the current state of the infrastructure resources managed by Terraform. The state file is used to track the resources that have been created, modified, or destroyed, and it is used to ensure that the infrastructure resources match the desired state defined in the configuration files.

Q: What is terraform provisioner?

Ans:
Terraform Provisioners are used to performing certain custom actions and tasks either on the local machine or on the remote machine.
The custom actions can vary in nature, and it can be -
  • Running custom shell script on the local machine
  • Running custom shell script on the remote machine
  • Copy file to the remote machine
Also, there are two types of provisioners -
  • Generic Provisioners (file, local-exec, and remote-exec)
  • Vendor Provisioners (chef, habitat, puppet, salt-masterless)

1. file provisioner
As the name suggests file provisioner can be used for transferring and copying the files from one machine to another machine.
Not only file but it can also be used for transferring/uploading the directories.
resource "aws_instance" "ec2_example" {

    ami = "ami-0767046d1677be5a0"  
    instance_type = "t2.micro"
    key_name= "aws_key"
    vpc_security_group_ids = [aws_security_group.main.id]

  provisioner "file" {
    source      = "/home/rahul/abc/keys/aws/test-file.txt"
    destination = "/home/ubuntu/test-file.txt"
  }
  connection {
      type        = "ssh"
      host        = self.public_ip
      user        = "ubuntu"
      private_key = file("/home/rahul/abc/keys/aws/aws_key")
      timeout     = "4m"
   }
}
So when we talk about copying files or directories from one machine to another machine then it has to be secured and file provisioner supports for ssh and winrm type of connections which can help you to achieve secure file transfer between the source machine and destination machine.

2. local-exec provisioner
The next provisioner we are going to talk about is local-exec provisioner. Basically, this provisioner is used when you want to perform some tasks onto your local machine where you have installed the terraform.
resource "aws_instance" "ec2_example" {
 9
10    ami = "ami-0767046d1677be5a0"  
11    instance_type = "t2.micro"
12    tags = {
13        Name = "Terraform EC2"
14    }
15
16  provisioner "local-exec" {
17    command = "touch hello-dj.txt"
18  }
19}
So local-exec provisioner is never used to perform any kind task on the remote machine. It will always be used to perform local operations onto your local machine.

3. remote-exec provisioner
As the name suggests remote-exec it is always going to work on the remote machine. With the help of the remote-exec you can specify the commands of shell scripts that want to execute on the remote machine.
resource "aws_instance" "ec2_example" {
 9
10    ami = "ami-0767046d1677be5a0"  
11    instance_type = "t2.micro"
12    key_name= "aws_key"
13    vpc_security_group_ids = [aws_security_group.main.id]
14
15  provisioner "remote-exec" {
16    inline = [
17      "touch hello.txt",
18      "echo helloworld remote provisioner >> hello.txt",
19    ]
20  }
21  connection {
22      type        = "ssh"
23      host        = self.public_ip
24      user        = "ubuntu"
25      private_key = file("/home/rahul/abc/keys/aws/aws_key")
26      timeout     = "4m"
27   }
28}
As we discussed ssh and winrm for secure data transfer in local-exec, here also all the communication and file transfer is done securely.

Comments