How To Use Terraform

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14
At a glance
Powered by AI
Terraform is an infrastructure as code tool used to provision, change, and version infrastructure resources safely and efficiently across multiple cloud providers.

Terraform is used to build, change, and version infrastructure safely and efficiently. It is a free and open-source tool written by HashiCorp that uses configuration files to manage resources across public cloud providers like AWS, Azure, GCP and more.

The main Terraform commands are terraform init, terraform plan, terraform apply, terraform destroy and terraform refresh. Terraform init downloads plugins, terraform plan generates an execution plan, terraform apply provisions infrastructure and terraform destroy tears down resources.

TERRAFORM

V1:- What is Terraform?


 Tool for building changing and versioning infrastructure
saftly and efficiently.
 Free and opensource IAC tool build by Hashicorp
 Written by hashicorp configuration language(HCL)
Why Terraform?
Cloudformation ansible terraform
only AWS mainly config mainly IAAC with 100+ providers

Nill mutable(fast) immutable(slow)


Nill procedural declarative
(order/nostate/notreuseable) (Noorder/aware-state/reusable)

https://registry.terraform.io/browse/providers

Terraform Architecture?
Core—config.tf state
We save the configuration file extension in .tf and state file is created to save all
the configuration. These two files are mingle know as core.
Providers – aws , azure , GCP .. 100+

V2:- create EC2 Instance from terraform


Terraform installationon linux .
https://www.terraform.io/docs/cli/install/yum.html
to check the version after installation # terraform - -version

now let see the hashicorp configuration language structure.


Resource “aws_instance” “myec2” {
Ami = “ami-084xxxxxxxxx”
Instance_type = “t2.micro”
}
Resource is mean by block name
Aws_instance is mean by provider_resources block we can change the resources
type like S3 ..
Creating first EC2 instance with Terraform
Terraform init
Terraform plan
Terraform apply
Terraform show

Provider “aws” {
Region = “us-east-1”
Access_key = ”PUT-YOUR-ACCESS-KEY-HEAR”
Secret_key = “PUT-SECRET-KEY-HEAR”
}
Terraform commands:-
https://www.youtube.com/redirect?
event=video_description&redir_token=QUFFLUhqbnBsdlp1ZkFzTC1xMDRDYkJZS
WdoODdYcGx4QXxBQ3Jtc0ttYzRuMUZHNngxUXNMR2NlSFppRk90RlhaMUpaRGIt
NXBYUGlqYlhfOWcyd3N2bHl4UEZ3WEtLeGZhZzl2V2xnbGpQZ19jVTJjeDhQYWQ5a
29XbllOSG8tcnNUeERvaFF3bC1ZSFNqSklma2ptZ2g0NA&q=https%3A%2F
%2Fwww.terraform.io%2Fdocs%2Fcli%2Fcommands%2Fapply.html
to create a instance
create a empty directory and create ec2.tf file in the mention below
Resource “aws_instance” “myec2” {
Ami = “ami-084xxxxxxxxx”
Instance_type = “t2.micro”
}
Again create provider.tf file
Provider “aws” {
Region = “us-east-1”
Access_key = ”PUT-YOUR-ACCESS-KEY-HEAR”
Secret_key = “PUT-SECRET-KEY-HEAR”
}
Now execute using cmd
#terraform init
This cmd will download the package
To check the code in the file .tf
#terraform plan
Now apply the code.
#terraform apply
It will create a instance in aws in localmachine one more folder is created is
terraform.tfstate is file in future we can modify in the file only it will reflect.
To view the history of instance details.
#terraform show

V3:- how to change instance type and delete the resources.


Now change the ec2.tf file
Micro to large instance. As same command
#terraform plan
#terraform apply
To delete instance just execute
#terraform delete

V4: terraform providers vs Resources


Terraform providers:
Official
Verified
Community
V5:- Terraform Refersh | Desired vs current state
Understand of terraform state:-
Terraform must store state about your managed infrastructure and configuration.
This satate is used by terraform to map real world resources to your
configuration.
If we changed the instance manually it wont update in the state file so we refresh
the terraform #terraform refresh
Update the state with the real infrastructure.

Desired state and Current state


Desired state = current state

V6:- Terraform Variables usage & demo


Configuration Directory
Main.tf
Provider.tf
Variables.tf
Output.tf

Variables:-
Repeated Static value easily handle
Replace the hardcore value
Ex:-
Resource “aws_security_group” “demo_var” {
Name = “demo_var”
Ingress {
Description = “TLS from vpc”
From_port =443
To_port = 443
Proctol = “tcp”
Cidr_block =[10.20.30.40/32]
}
}
How to create variable :-
Variable.tf
Variable “client_ip” {
Default = “10.60.60.60/32”
}
Now change in the conf file in Cidr_block =[10.20.30.40/32]
cidr_block = [var.client_ip]
to check the file
#terraform valid
To execute
#terraform plan
#terraform apply

V7:- Terraform Attributes & Output


Attributes:-
Every resource have arguments and attributes
TF use this for output
TF input this to other resources being created.

Output:-
After created resource fetch the value from resource attribute
Now create a elastic ip in aws
Eip.tf
Resource “aws_eip” “myeip”{
Vpc = true
}
To view the output of the eip
Output.tf
Resource “Demo_outputeip”{
Value = aws_eip. Myeip.public_ip
}
V8:- attributes value to other resources
As as above combined and execute

V9:Yerraform formate vs validate


To alignment the proper formate use
#terraform fmt
Then to view the difference the formate and change it.
# terraform fmt –diff output.tf
If no need to chamge add
# terraform fmt – write=false –diff output.tf

V10: multiple approaches – variables assignments


Multiple Approaches to variable
1.enviroments variables
2.CLI Flag
3.from a file
4.Variables Default

Terraform variables extension # terraform.tfvars

To create and execute the custom vaars


#terraform plan –var-file=”custom.tfvars”
To set default environment vars
#export TF_VAR_instancetype=”r5.large”
And check # env

V11: Data types in variables


 String
 Number
 List
 Bool
 Map
How to get output in cmd

Variable “username”{

type = number

https://registry.terraform.io/modules/terraform-aws-modules/elb/aws/latest

for reference.

V12:- terraform output command

#terraform output

V13:- Terraform state command

There is 7 sub commands in state

#terraform state list


to view how many state file in the terraform

# terraform state mv
to change the State file without destroy
#terraform state pull > backup
this cmd to take a backup the state file

#terraform state rm
to remove the state file

V14: terraform import

Terraform is able to import existing infrastructure.

Currently state only

The current implementation of terraform import can only import resources.


into the state. It does not generate configuration.

A future version of terraform will also generate configuration.

We have to write the code for manual creation iin aws console same
comnfiguration. Below import cmd

# terraform import aws_instance.devec2 <instance- id>

V15:-terraaform graph

The terraform graph  command is used to generate a visual


representation of either a configuration or execution plan. The
output is in the DOT format, which can be used by GraphViz to
generate charts.
To view the grapf download the graphViz
Usage:- Outputs the visual execution graph of Terraform
resources according to either the current configuration or an
execution plan.

#terraform graph | dot -Tsvg > graph.svg

It will download the .svg formate

V16: Terraform Lifecycle Rules


https://www.terraform.io/docs/language/meta-arguments/lifecycle.html

lifecycle  is a nested block that can appear within a resource


block. The lifecycle block and its contents are meta-arguments,
available for all resource blocks regardless of type.

The following arguments can be used within a lifecycle block.


- create_before_destroy

- prevent_destroy  
- ignore_changes

V17: terraform resource behaviour

In summary, applying a Terraform configuration will:

 Create resources that exist in the configuration but are not


associated with a real infrastructure object in the state.
 Destroy resources that exist in the state but no longer exist in
the configuration.

 Update in-place resources whose arguments have changed.

 Destroy and re-create resources whose arguments have changed


but which cannot be updated in-place due to remote API
limitations.

V19:-Remote state and advantages of remote state


V21:- debugging terraform:-

# export TF_LOG=TRACE

We can set the variables TF_LOG= TRACE most of them are use Trace and
Debug.we can easily find out the checkpoints step by step.

How to store the log file in different location?

#export TF_LOG_PATH=/tmp/tfdebug.log

We can see the log file in seprate directory


V21: Load order and semantics

You might also like