Sunday, April 10, 2022

Create Multiple EC2 instance with Nginx Role using Terraform

Description: Here I have explained, How to create multiple EC2 instance with Nginx Role using Terraform.

Prerequisites:

  • SSH Key in AWS
  • IAM user with EC2 Full access
  • Default VPC in EC2 instance
First creating provider file provider.tf for region access and secret keys

provider "aws" { region = "us-east-1" access_key = "XXXXXXXXXXXXXXXXXXX" secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXX" }

Define Variables like port, image_id and instance_type in variable file variable.tf  

variable ports { type = list(number) } variable image_id { type = string } variable "instance_type" { type = string }

Variable define in terraform.tfvars

ports=[22,80,443] image_id="ami-04505e74c0741db8d" instance_type="t2.micro"

Define Security group rule in Securitygroup.tf. For inbound port, I have used dynamic block for multiple port numbers define in terraform.tfvars file  "ports=[22,80,443]"
### Creating Security Group ### resource "aws_security_group" "terrainstance" { name = "Web_SG" description = "Security Group for Web" egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } dynamic "ingress" { for_each = var.ports iterator = port content { description = "Port for SG" from_port = port.value to_port = port.value protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] } } }


Shell script to install Nginx and start the service

#!/bin/bash apt update apt-get install nginx -y echo "this is techserverglobal" > /var/www/html/index.nginx-debian.html systemctl start nginx systemctl enable nginx

Instance.tf file for launch instance by using all the above variable. Here I define 3 count for 3 instance and name of the instance will be like "NginxWeb-0, NginxWeb-1 and NginxWeb-2"

resource "aws_instance" "terrainstance" { ami = "${var.image_id}" instance_type = "${var.instance_type}" count = 3 key_name = "terraform-key" security_groups = ["${aws_security_group.terrainstance.name}"] tags = { Name = "NginxWeb-${count.index}" } user_data = "${file("nginx.sh")}" }

Plan and Apply terraform project



























Verify in AWS console














No comments:

Post a Comment