Terraform Module to create ec2 instance using aws_security_group

Root Module

Using the aws_security_group community module:
Firstly, ensure you have the aws_security_group community module in your configuration (either by cloning or referencing it). Here, I'll just outline a hypothetical usage:

module "aws_security_group" {
  source = "terraform-aws-modules/security-group/aws"

  name        = "sg_name"
  description = "Security Group description"
  vpc_id      = "your_vpc_id"

  # Example rule to allow SSH
  ingress_cidr_blocks = [""]
  ingress_rules       = ["ssh-tcp"]

The specifics of how you use this module might vary based on its actual inputs and your requirements.

Creating a Custom EC2 Module:

Now, let’s write our custom module named devopx that uses the Security Group created above.

Inside a folder named devopx, create the following files:


variable "instance_type" {
  description = "EC2 instance type"
  default     = "t2.micro"

variable "ami" {
  description = "AMI ID for the EC2 instance"

variable "security_group_id" {
  description = "Security Group ID attached to the EC2 instance"


resource "aws_instance" "devopx_instance" {
  ami           = var.ami
  instance_type = var.instance_type

  vpc_security_group_ids = [var.security_group_id]

  tags = {
    Name = "DevOpXInstance"


output "instance_id" {
  description = "ID of the EC2 instance"
  value       = aws_instance.devopx_instance.id

Using the Custom devopx Module:

Back in your main configuration, use your devopx module:

module "devopx_instance" {
  source = "./devopx" 

  ami               = "your_ami_id"
  security_group_id = module.aws_security_group.this_security_group_id

Ensure that your_ami_id is replaced with the correct AMI ID for your EC2 instance.

Apply Configuration:

Run the following commands to initialize and apply your configuration:

terraform init
terraform apply
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x