1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- provider "aws" {
- region = var.region
- }
- data "aws_vpc" "default" {
- id = var.vpc_id
- }
- resource "aws_security_group" "instance_sg" {
- name = "instance_sg"
- description = "Security group for instances"
- ingress {
- from_port = 22
- to_port = 22
- protocol = "tcp"
- cidr_blocks = [data.aws_vpc.default.cidr_block] # restrict SSH access
- }
- }
- resource "aws_security_group" "alb_sg" {
- name = "alb_sg"
- description = "Security group for ALB"
- ingress {
- from_port = 80
- to_port = 80
- protocol = "tcp"
- cidr_blocks = [data.aws_vpc.default.cidr_block] # example
- }
- ingress {
- from_port = 443
- to_port = 443
- protocol = "tcp"
- cidr_blocks = [data.aws_vpc.default.cidr_block] # example
- }
- }
- resource "aws_launch_configuration" "example" {
- name_prefix = "example-"
- image_id = var.ami_id
- instance_type = "t2.micro"
-
- security_groups = [aws_security_group.instance_sg.id]
- user_data = <<-EOF
- #!/bin/bash
- apt update
- apt upgrade -y
- EOF
- lifecycle {
- create_before_destroy = true
- }
- }
- resource "aws_autoscaling_group" "my-asg" {
- name = "my-asg"
- launch_configuration = aws_launch_configuration.example.name
- min_size = 2
- max_size = 5
- desired_capacity = 2
- vpc_zone_identifier = var.subnet_ids
- instance_refresh {
- strategy = "rolling"
- }
- }
- resource "aws_lb" "my-lb" {
- name = "my-lb"
- internal = false
- load_balancer_type = "application"
- subnets = var.subnet_ids
- security_groups = var.alb_security_group_ids
- }
- resource "aws_lb_target_group" "my-tg" {
- name = "my-tg"
- port = 80
- protocol = "HTTP"
- vpc_id = var.vpc_id
- }
|