How to create an EC2 instance through Terraform

Sandeep - Sep 18 - - Dev Community

In this post, we will create an EC2 instance on AWS in two methods:

1. Using the Amazon CLI.
Prerequisite: A laptop or machine with terraform installed and AWS cli configured

1: Create main.tf and variables.tf inside a folder
main.tf

provider "aws" {
  region = var.aws_region
}

resource "aws_instance" "example" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = "Terraform-EC2"
  }
}
Enter fullscreen mode Exit fullscreen mode

variables.tf

provider "aws" {
  region = var.aws_region
}

resource "aws_instance" "example" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = "Terraform-EC2"
  }
}
Enter fullscreen mode Exit fullscreen mode

2 : Initialize the directory with $ terraform init command
3 : Run $ terraform plan command to print out the execution plan
4 : Apply the configuration now with the $ terraform apply command.
5 : Inspect the current state using $ terraform show and check AWS console whether a instance is created.
6 : Run $ terraform destroy command to destroy the created instance.

2. By adding an Access Key & Secret key in code as Variables (deploying publicly is not recommended)

1: Create main.tf and variables.tf inside a folder
main.tf

provider "aws" {
  region     = var.aws_region
  access_key = var.aws_access_key
  secret_key = var.aws_secret_key
}

resource "aws_instance" "example" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = "Terraform-EC2"
  }
}
Enter fullscreen mode Exit fullscreen mode

variables.tf

2 : Initialize the directory with terraform init command
3 : Run terraform plan command to print out the execution plan
4 : Apply the configuration now with the terraform apply command.
5 : Inspect the current state using terraform show and check AWS console whether a instance is created.
6 : Run terraform destroy command to destroy the created instance.

variable "aws_access_key" {
  description = "Your AWS Access Key"
  type        = string
}

variable "aws_secret_key" {
  description = "Your AWS Secret Key"
  type        = string
}

variable "aws_region" {
  description = "The AWS region to create EC2 instance"
  default     = "us-west-2" # Change as needed
}

variable "ami_id" {
  description = "The AMI ID to use for the instance"
  default     = "ami-0c55b159cbfafe1f0" # Example for Amazon Linux 2 in us-west-2, replace with your preferred AMI
}

variable "instance_type" {
  description = "The type of instance to launch"
  default     = "t2.micro" # Change the instance type if needed
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player