首页 > 解决方案 > 跨微服务环境模块化 Terraform IaC

问题描述

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

在此处输入图像描述

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

例如:

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 ,其中每个微服务都预先定义了其拥有的映射变量。但希望得到一些指导。提前致谢!

在此处输入图像描述

标签: amazon-web-servicesterraformmicroservicesterraform-provider-awsinfrastructure-as-code

解决方案


我建议您阅读 Yevgeniy Brikman 撰写的关于 Terraform 的一系列优秀博客文章,这些文章清除了我对 Terraform 的理解:

https://blog.gruntwork.io/a-comprehensive-guide-to-terraform-b​​3d32832baca

这个确切的问题似乎在这个问题中被触及:https ://blog.gruntwork.io/how-to-create-reusable-infrastructure-with-terraform-modules-25526d65f73d


推荐阅读