我正在尝试重构我的IaC Terraform设置,以减少重复代码,并更快地进行更改。我正在开发一个无服务器的微服务应用程序,因此,例如,我正在运行几个AWS-ECS-autos标和aws的实例。我有开发和生产环境,在每个环境中都有一个模块文件夹,其中定义了每个微服务模块。请查看模拟文件夹结构的图像。

如您所见,有许多重复的文件夹。在dev和prod环境的main.tf中,调用每个模块并分配vars。
例:
ecs-autoscaling-microservice-A main.tf
resource "aws_appautoscaling_target" "dev_ecs_autoscaling_microservice_A_target" {
max_capacity = 2
min_capacity = 1
resource_id = "service/${var.ecs_cluster.name}/${var.ecs_service.name}"
scalable_dimension = "ecs:service:DesiredCount"
service_namespace = "ecs"
}
resource "aws_appautoscaling_policy" "dev_ecs_autoscaling_microservice_A_memory" {
name = "dev_ecs_autoscaling_microservice_A_memory"
policy_type = "TargetTrackingScaling"
resource_id = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.resource_id
scalable_dimension = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.scalable_dimension
service_namespace = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.service_namespace
target_tracking_scaling_policy_configuration {
predefined_metric_specification {
predefined_metric_type = "ECSServiceAverageMemoryUtilization"
}
target_value = 80
}
}
resource "aws_appautoscaling_policy" "dev_ecs_autoscaling_microservice_A_cpu" {
name = "dev_ecs_autoscaling_microservice_A_cpu"
policy_type = "TargetTrackingScaling"
resource_id = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.resource_id
scalable_dimension = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.scalable_dimension
service_namespace = aws_appautoscaling_target.dev_ecs_autoscaling_microservice_A_target.service_namespace
target_tracking_scaling_policy_configuration {
predefined_metric_specification {
predefined_metric_type = "ECSServiceAverageCPUUtilization"
}
target_value = 60
}
}开发main.tf
module "ecs_autoscaling_microservice_A" {
source = "./modules/ecs-autoscaling-microservice-A"
ecs_cluster = module.ecs_autoscaling_microservice_A.ecs_cluster_A
ecs_service = module.ecs_autoscaling_microservice_A.ecs_service_A
}我的问题是,删除所有模块的最佳方法是什么。因此,与其为prod和dev环境中的每个微服务提供ecs模块,我还可以为ecs提供一个模块,该模块可以在任何环境中重新用于任何微服务。有关所需文件夹结构,请参见图像。这是可能的还是我在浪费时间?我正在考虑使用某种for_each,其中每个微服务都是用自己的映射变量预先定义的。但是请给我一些指导。提前感谢!

发布于 2021-04-08 16:55:53
我建议您阅读Yevgeniy关于Terraform的一系列优秀的博客文章,这些文章澄清了我对Terraform的理解:
https://blog.gruntwork.io/a-comprehensive-guide-to-terraform-b3d32832baca
这个确切的问题似乎在这个问题中被触及:https://blog.gruntwork.io/how-to-create-reusable-infrastructure-with-terraform-modules-25526d65f73d
https://stackoverflow.com/questions/66983237
复制相似问题