跨微服务环境模块化 Terraform IaC

时间:2021-04-07 09:29:42

标签: amazon-web-services terraform microservices terraform-provider-aws infrastructure-as-code

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

enter image description here

如您所见,有许多重复的文件夹。在 dev 和 prod 环境的 main.tf 中,每个模块都被调用并分配了变量。

EG:

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 使用 1 个模块,它可以重新用于任何环境中的任何微服务。有关所需的文件夹结构,请参阅图像。这是可能的还是我在浪费时间?我正在考虑使用某种 for_each ,其中每个微服务都是事先用其拥有的映射变量定义的。但希望得到一些指导。提前致谢!

enter image description here

1 个答案:

答案 0 :(得分:0)

我建议您阅读 Yevgeniy Brikman 撰写的关于 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

相关问题