terraform.tf 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. provider "aws" {
  2. region = var.region
  3. }
  4. data "aws_vpc" "default" {
  5. id = var.vpc_id
  6. }
  7. resource "aws_security_group" "instance_sg" {
  8. name = "instance_sg"
  9. description = "Security group for instances"
  10. ingress {
  11. from_port = 22
  12. to_port = 22
  13. protocol = "tcp"
  14. cidr_blocks = [data.aws_vpc.default.cidr_block] # restrict SSH access
  15. }
  16. }
  17. resource "aws_security_group" "alb_sg" {
  18. name = "alb_sg"
  19. description = "Security group for ALB"
  20. ingress {
  21. from_port = 80
  22. to_port = 80
  23. protocol = "tcp"
  24. cidr_blocks = [data.aws_vpc.default.cidr_block] # example
  25. }
  26. ingress {
  27. from_port = 443
  28. to_port = 443
  29. protocol = "tcp"
  30. cidr_blocks = [data.aws_vpc.default.cidr_block] # example
  31. }
  32. }
  33. resource "aws_launch_configuration" "example" {
  34. name_prefix = "example-"
  35. image_id = var.ami_id
  36. instance_type = "t2.micro"
  37. security_groups = [aws_security_group.instance_sg.id]
  38. user_data = <<-EOF
  39. #!/bin/bash
  40. apt update
  41. apt upgrade -y
  42. EOF
  43. lifecycle {
  44. create_before_destroy = true
  45. }
  46. }
  47. resource "aws_autoscaling_group" "my-asg" {
  48. name = "my-asg"
  49. launch_configuration = aws_launch_configuration.example.name
  50. min_size = 2
  51. max_size = 5
  52. desired_capacity = 2
  53. vpc_zone_identifier = var.subnet_ids
  54. instance_refresh {
  55. strategy = "rolling"
  56. }
  57. }
  58. resource "aws_lb" "my-lb" {
  59. name = "my-lb"
  60. internal = false
  61. load_balancer_type = "application"
  62. subnets = var.subnet_ids
  63. security_groups = var.alb_security_group_ids
  64. }
  65. resource "aws_lb_target_group" "my-tg" {
  66. name = "my-tg"
  67. port = 80
  68. protocol = "HTTP"
  69. vpc_id = var.vpc_id
  70. }