Please find the below code for reference to create an ec2 instance in AWS using terraform variables and data sets.
provider "aws" {
region = var.aws_region
access_key = ""
secret_key = ""
}
Declare variables
variable "aws_region" {
description = "The AWS region to deploy the EC2 instance"
type = string
default = "ap-south-1"
}
variable "instance_type" {
description = "The type of EC2 instance"
type = string
default = "t2.micro"
}
variable "instance_count" {
description = "Number of EC2 instances to create"
type = number
default = 1
}
variable "allowed_ips" {
description = "List of allowed IP addresses for the security group"
type = list(string)
default = ["0.0.0.0/0"]
}
variable "tags" {
description = "Map of tags to assign to the EC2 instance"
type = map(string)
default = {
Name = "Terraform-EC2-Instance"
Environment = "dev"
}
}
variable "enable_monitoring" {
description = "Enable detailed monitoring for the instance"
type = bool
default = false
}
Create a security group
resource "aws_security_group" "ec2_sg" {
name_prefix = "${var.tags["Name"]}-sg-"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = var.allowed_ips
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = var.tags
}
Create the EC2 instance
resource "aws_instance" "ec2_instance" {
count = var.instance_count
ami = data.aws_ami.amazon_linux.id
instance_type = var.instance_type
key_name = "test02"
vpc_security_group_ids = [aws_security_group.ec2_sg.id]
monitoring = var.enable_monitoring
tags = var.tags
}
Data source to fetch the latest Amazon Linux AMI
data "aws_ami" "amazon_linux" {
most_recent = true
owners = ["137112412989"] # Amazon's official account ID for Amazon Linux
filter {
name = "name"
values = ["amzn2-ami-hvm-*-x86_64-gp2"]
}
}