Launch EC2 Instance With Terraform — Steps to provision
What is Terraform?
Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. Configuration files describe to Terraform the components needed to run a single application or your entire datacenter.
Reference: https://www.terraform.io/intro/index.html
- Connect EC2 Instance with AMI as Linux.
$ sudo su
$ ls - No files can be seen.
- Now copy the terraform file from https://www.terraform.io/downloads.html for Linux.
$ wget https://releases.hashicorp.com/terraform/0.14.4/terraform_0.14.4_linux_amd64.zip
$ yum install unzip -y
$ unzip terraform_0.14.4_linux_amd64.zip - Set the path for getting terraform cmd available
$ echo $”export PATH=\$PATH:$(pwd)” >> ~/.bash_profile
$ source ~/.bash_profile - Now run the terraform cmd to check weather its working or not?
$ terraform
$ mkdir terraform-lab
$ cd terraform-lab/
$ vi ec2.tf
provider “aws” {
access_key = “AKIA5W3VEU6TCNAY2FXA”
secret_key = “RNEJ+ZKurXWqBQ8DC18UZVGk+TZveU6fIqlME/Q/”
region = “ap-south-1”
}
resource “aws_instance” “test” {
ami = “ami-0cda377a1b884a1bc”
instance_type = “t2.micro”
key_name = “imran_keypair”
}
- Now initialize the working directory for terraform.
$ terraform init - Now Provision the ec2 with this command, you can create (apply) or delete (destroy) the server.
$ terraform apply - If it fails check for permission on IAM -> users -> “resource group” provide EC2FullAccess for the user.
- From your terminal/command prompt/ shell, destroy the resources
$ terraform destroy
That’s it! you installed Terraform and used it to provision an EC2 instance.