How to create AWS EC2 instance using Terraform
create directory ec2 and navigate to the directory
$ mkdir ec2 && cd ec2
create main.tf file
$ vim main.tf
provider "aws" {
region = "ap-south-1"
}
resource "aws_instance" "app_server" {
ami = "ami-03f4878755434977f"
instance_type = "t2.nano"
subnet_id = "subnet-0ccba3b8cfd0645e2"
key_name = "awskey"
associate_public_ip_address = "true"
tags = {
Name = "demo-server"
}
}
output "public_ip" {
description = "public ip of the instance"
value = aws_instance.app_server.public_ip
}
save and exit
initialize the terraform
$ terraform init
$ terraform plan
$ terraform apply -auto-approve
it will create the AWS EC2 instance with output the public ip of the instance
To destroy the instance
$ terraform destroy -auto-approve