如何解决Terraform-如何在多个AWS ecs_service资源之间使用相同的负载均衡器?
我有一个关于使用Terraform在AWS ECS上创建服务的问题,希望得到所有反馈,尤其是因为我是AWS新手。
我在同一个集群中有几个服务(每个服务都是机器学习模型)。流量不是那么高,所以我希望同一个负载平衡器将请求路由到不同的服务(基于指定要使用的模型的请求标头)。
我试图使用Terraform(https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service)创建服务,但是我很难理解load_balancer的配置。没有选择特定负载均衡器的ARN或ID的选项,这让我认为为每个服务都创建了一个单独的负载均衡器-听起来很昂贵:)
有没有人对此有任何经验,谁能告诉我我的推理出了什么问题?
非常感谢您的阅读!
解决方法
弗雷德(Fred),在您发布的文档的链接中可以找到答案,让我逐步指导您。
以下是两种ECS服务如何以图形方式使用一个应用程序负载均衡器的方法:
以下场景描述了其中一项服务的配置,类似于第二项服务的配置,您唯一需要重复的就是负载均衡器声明。
您可以定义以下内容:
# First let's define the Application LB
resource "aws_lb" "unique" {
name = "unique-lb"
internal = false
load_balancer_type = "application"
... #the rest of the config goes here
}
#Now let's create the target group for the service one
resource "aws_lb_target_group" "serviceonetg" {
name = "tg-for-service-one"
port = 8080 #example value
protocol = "HTTP"
... #the rest of the config goes here
}
#Now create the link between the LB and the Target Group
# also will add a rule when to forward the traffic using HTTP path /serviceone
resource "aws_alb_listener" "alb_serviceone_listener" {
load_balancer_arn = aws_alb.unique.arn # Here is the LB ARN
port = 80
protocol = "HTTP"
default_action {
target_group_arn = "${aws_alb_target_group.serviceonetg.arn}" #Here is the TG ARN
type = "forward"
}
condition {
field = "path-pattern"
values = ["/serviceone"]
}
}
#As a last step,you need to link your service with the target group.
resource "aws_ecs_service" "service_one" {
... # prior configuration goes here
load_balancer {
target_group_arn = aws_lb_target_group.serviceonetg.arn # Here you will link the service with the TG
container_name = "myservice1"
container_port = 8080
}
... #the rest of the config goes here
}
作为旁注,我将使用数据结构以服务的重复部分为模板,以一种方式,您可以使用count
或for_each
仅描述目标组,侦听器和服务,并保留模板引擎做剩下的事。基本上,遵循DRY原则。
我希望这可以为您提供帮助。