Create an EC2 instance | Terraform

This post helps you to create a basic EC2 instance (free tier) through Terraform AWS provisioning DSL scripting language
  • Download Terraform CLI
https://www.terraform.io/downloads.html
  • Extract and move terraform inside bin folder
mv ~/Downloads/terraform /usr/local/bin/

terraform version
  • Create a new project and a file with extension .tf
  • Copy and paste the below script
provider "aws" {
version = "~> 2.0"
region = "us-west-2"
shared_credentials_file = "~/.aws/credentials"
profile = "prashanth"
}
data "aws_ami" "amazon-linux-2" {
most_recent = true
owners = ["amazon"]
filter {
name = "name"
values = ["amzn2-ami-hvm*"]
}
filter {
name = "architecture"
values = ["x86_64"]
}
}
resource "aws_instance" "test" {
ami = "${data.aws_ami.amazon-linux-2.id}"
associate_public_ip_address = true
instance_type = "t2.micro"
}
  • Now, initialize terraform
terraform init
  • Compile the terraform file for any issues
terraform plan
  • Finally apply terraform
terraform apply -auto-approve

Leave a comment