-- 1. tfファイル作成
vim main.tf
provider "aws" {
region = "ap-northeast-1"
}
variable "server_port" {
description = "The port the server will use for HTTP requests"
type = number
}
data "aws_vpc" "vpc01" {
default = true
}
data "aws_subnets" "subnet01" {
filter {
name = "vpc-id"
values = [data.aws_vpc.vpc01.id]
}
}
resource "aws_security_group" "sg01" {
name ="sg01"
ingress {
from_port = var.server_port
to_port = var.server_port
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_launch_configuration" "lc01" {
image_id = "ami-0ed99df77a82560e6"
instance_type = "t2.micro"
security_groups = [ aws_security_group.sg01.id ]
user_data = <<-EOF
#!/bin/bash
echo "Hello ,World!" > index.html
nohup busybox httpd -f -p ${var.server_port} &
EOF
lifecycle {
create_before_destroy = true
}
}
resource "aws_lb_target_group" "tg01" {
name = "tg01"
port = var.server_port
protocol = "HTTP"
vpc_id = data.aws_vpc.vpc01.id
health_check {
path = "/"
protocol = "HTTP"
matcher = "200"
interval = 15
timeout = 3
healthy_threshold = 2
unhealthy_threshold = 2
}
}
resource "aws_autoscaling_group" "asg01" {
launch_configuration = aws_launch_configuration.lc01.name
vpc_zone_identifier = data.aws_subnets.subnet01.ids
target_group_arns = [aws_lb_target_group.tg01.arn]
health_check_type = "ELB"
min_size = 2
max_size = 3
tag {
key = "Name"
value = "asg01"
propagate_at_launch = true
}
}
resource "aws_security_group" "sg02" {
name = "sg02"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_lb" "alb01" {
name = "alb01"
load_balancer_type = "application"
subnets = data.aws_subnets.subnet01.ids
security_groups = [aws_security_group.sg02.id]
}
resource "aws_lb_listener" "listener01" {
load_balancer_arn = aws_lb.alb01.arn
port = 80
protocol = "HTTP"
default_action {
type ="fixed-response"
fixed_response {
content_type ="text/plain"
message_body = "404: page not found"
status_code = 404
}
}
}
resource "aws_lb_listener_rule" "listener_rule01" {
listener_arn = aws_lb_listener.listener01.arn
priority = 100
condition {
path_pattern {
values = ["*"]
}
}
action {
type = "forward"
target_group_arn = aws_lb_target_group.tg01.arn
}
}
output "alb_dns_name" {
value = aws_lb.alb01.dns_name
description = "The domain name of the load balancer"
}
-- 2. terraform 実行
terraform init -upgrade
terraform plan
terraform apply -auto-approve
terraform output
terraform state list
-- 3. クリーンアップ
terraform destroy -auto-approve