Create AWS ec2 instance using terraform

Madeesha’s Tech Space
2 min readJul 2, 2018

--

Terraform is widely used for managing remote resources in cloud providers such as AWS. Terraform is designed to be able to manage extremely large infrastructures that span multiple cloud providers. Lets see how we can use terraform to create a simple ec2 instance in AWS as the first step.

Before running the terraform script, you need to install it in your machine and you should have a aws account to test your code.

Then create a folder with following structure :

sample_terraform
|____________ main.tf
|____________ secret.tfvars

include following terraform code inside main.tf

# Configure the AWS Provider
provider "aws" {
region = "ap-southeast-2"
}
# Create an EC2 instance
resource "aws_instance" "example" {
ami = "ami-4c5b8b2e"
instance_type = "m3.medium"
tags {
Name = "example"
}
}

note: You need to specify the exact region that you are going to create the instance in AWS as well as a AMI id for the instance. As an example if you need to create an ubuntu 16.04 instance, you need to give an ubuntu 16.04 AMI id for the particular region. (to select ami id, first go to AWS dashboard. then click on “Launch a virtual machine”. Then select “Community AMIs”. There you can see the AMI ids for different operating systems.)

include your AWS access key and secret key as follows inside the secret.tfvars

access_key   = ""
secret_key = ""

Then run following commands to create the remote instance using terraform :

cd sample_terraformterraform initterraform plan -var-file=secret.tfvars -var-file=main.tfterraform apply -var-file=secret.tfvars -var-file=main.tf

Then go to AWS console, you can see the created instance there.

If you need to destroy the created instance run following command :

terraform destroy -var-file=secret.tfvars -var-file=main.tf

--

--

No responses yet