📁Terraform Configuration File:
Create a Terraform configuration file to define a resource of AWS EC2 instance.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "5.43.0"
}
}
}
provider "aws" {
region = "us-east-2"
}
resource "aws_instance" "my_instance"{
ami = "ami-5f4884535656"
instance_type = "t2.micro"
}
📁Check state files
Check state files before running plan and apply commands & Use validate command to validate your tf file for errors and provide the Output generated by each commands.
terraform init
terraform validate
📁Adding Provisioner to Configuration file
You can add a provisioner to your configuration file to configure the resource after it is created. For example, to run a shell script on the EC2 instance after creation, you can use the remote-exec
provisioner:
resource "aws_instance" "new-instance" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
provisioner "remote-exec" {
inline = [
"echo 'Hello, World' > hello.txt",
]
}
In this example:
We're provisioning an AWS EC2 instance with the
aws_instance
resource block.Inside the
aws_instance
resource block, we're using theprovisioner
block to specify aremote-exec
provisioner. This provisioner executes commands on the created instance remotely via SSH.The
inline
block contains the commands we want to execute on the remote instance after it's created. In this case, it's just creating ahello.txt
file with the text "Hello, World".
📜To apply changes
terraform init
terraform apply
📜To destroy resources
terraform destroy
⚙Add lifecycle management configurations
To control the creation, modification, and deletion of the resource and use Terraform commands to apply the changes.These configurations allow you to specify behaviors such as preventing resource deletion or updating in-place.
resource "aws_instance" "new-instance" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
lifecycle {
create_before_destroy = true
prevent_destroy = true
}
}
In this example:
We've added a
lifecycle
block inside theaws_instance
resource block.create_before_destroy
is set to true, which means Terraform will create a new instance before destroying the old one during updates.prevent_destroy
is set to true, which means Terraform will prevent the instance from being destroyed.
Happy Learning :)