Create AWS ec2, alb with terraform – userdata

– Download terraform from https://www.terraform.io/downloads.html

unzip terraform_0.13.4_linux_amd64.zip
mv terraform /usr/bin/

– Setup and configure aws cli

– Create a file ec2.tf

provider "aws" {
  region = "ap-south-1"
}

resource "aws_key_pair" "ap-web-01" {
  key_name   = "ap-web-01"
  public_key = "YOUR_SSH_PUB_KEY"
}

resource "aws_instance" "ap-web-01" {
  ami = "ami-086c142842468ba9d"
  instance_type = "t4g.micro"
  key_name = "ap-web-01"
  security_groups = ["ap-web-01"]
  user_data = "${file("userdata.sh")}"

  tags = {
    Name = "ap-web-01"
    env = "prod"
    owner = "admin"
  }

}

resource "aws_security_group" "ap-web-01" {
  name        = "ap-web-01"
  description = "ap-web-01 inbound traffic"

  ingress {
    description = "all"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

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

  tags = {
    Name = "ap-web-01"
  }
}

alb.tf

#target group
resource "aws_lb_target_group" "web1-tg" {
  name     = "web1-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = "vpc-01cf98f5afb156c90"
  target_type = "instance"
}

#target group attachment
resource "aws_lb_target_group_attachment" "web1-tg-attach" {
  target_group_arn = aws_lb_target_group.web1-tg.arn
  target_id        = aws_instance.ap-web-01.id
  port             = 80
}

#alb
resource "aws_lb" "web1-alb" {
  name               = "web1-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.ap-web-01.id]
  subnets            = ["subnet-093a2ddfcb7bc30b1", "subnet-0475d9e26dfdc9d00", "subnet-0274975b4af3513ee"]

  tags = {
    Environment = "web1-alb"
  }
}

#alb-listner
resource "aws_lb_listener" "web1-alb-listner" {
  load_balancer_arn = aws_lb.web1-alb.arn
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.web1-tg.arn
  }
}

userdata.sh

#! /bin/bash
sudo apt-get update
sudo apt-get install -y nginx
sudo systemctl start nginx
sudo systemctl enable nginx
echo "<h1>hola Terraform</h1>" | sudo tee /var/www/html/index.html
terraform init
terraform plan
terraform apply -auto-approve

terraform destory

More : https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance