Spinning Up An EC2 Instance

In this section we will examine the steps required to spin up a new EC2 instance in AWS.

First step is to create a new file with the name instance.tf like below,

provider "aws" {
  access_key = "ACCESS_KEY_HERE"
  secret_key = "SECRET_KEY_HERE"
  region     = "us-east-2"
}

resource "aws_instance" "example" {
  ami           = "ami-046cfe1f8332fd5f2"
  instance_type = "t2.micro"
}

Spinning up a new EC2 instance involves using the Terraform AWS provider and we have to specify the access_key and secret_key along with the region for our resources on AWS. Once the provider is configured, we have to defaine our resource, which is of an aws_instance type. The name we have given to the instance in example and in addition to that we have specified the ami ID and the instance type.

Execute the below command to setup the required Terraform providers,

$ terraform init

You'll see an output similar to below,

Initializing the backend...

Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v3.37.0

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

This indicate that the AWS Terraform provider has been fetched and it is ready to use.

Next we can inspect what is going to be deployed,

We can save this plan to a separate file and use it to deploy the instances in AWS to make sure about what's being deployed.

Or we can simply initiate the deployment like below,

This will spin up a new EC2 instance.

To delete the instance,

Last updated

Was this helpful?