Terraform VPC and EC2 example

Terraform basic VPC and EC2 example:

main.tf

provider "aws" {
  region = var.region
}


resource "aws_instance" "Server" {
  instance_type = var.inst_type
  ami           = var.ami
  key_name      = var.key_name

  subnet_id = module.vpc.public_subnets[0]

  vpc_security_group_ids = [aws_security_group.EC2_security.id]

  tags = {
    "Name" = "EC2 Server"
  }

  depends_on = [
    module.vpc.my_vpc
  ]

}

vpc.tf

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.11.5"

  name = "my_vpc"
  cidr = "10.0.0.0/16"

  azs             = [var.azs]
  private_subnets = ["10.0.11.0/24"]
  public_subnets  = ["10.0.12.0/24"]

  #enable_nat_gateway = true


  tags = {
    Name        = "My_VPC"
    Description = "VPC"
  }
}

sg.tf

# Security Group for EC2 Instance

resource "aws_security_group" "EC2_security" {
  name = "EC2_security"

  vpc_id = module.vpc.vpc_id
  ingress {
    description = "SSH"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = [var.Allowed_SSH_IP]
  }


  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]

  }

  tags = {
    Name = "EC2_security Group"
  }

  depends_on = [module.vpc.my_vpc]
}

variables.tf

variable "region" {
  default = "us-west-2"
}

variable "azs" {
  default = "us-west-2a"
}

variable "ami" {
  default = "ami-0ca05c6eaa4ac40e0"
}

variable "key_name" {
  default = "dev"
}


variable "Allowed_SSH_IP" {
  default = "0.0.0.0/0"
}

variable "inst_type" {
  default = "t2.micro"
}

output.tf

output "EC2_Public_IP" {
  value = aws_instance.Server.public_ip
}

This Terraform basic VPC and EC2 example you can clone from GitGub.

Discuss article in ArsTech Forum

   

If you like what you are reading, please:

Buy me a coffeeBuy me a coffee

arstech

Start the discussion at forum.arstech.net