【问题标题】:terraform how to breakup environment with modulesterraform如何用模块分解环境
【发布时间】:2025-12-10 18:25:01
【问题描述】:

我对 terraform 模块有点困惑。我得到了使用模块的代码可重用性的想法。您在目录中创建的任何代码本质上都是一个模块。我正在努力解决的问题是您的模块化程度如何?每个模块是否应该包含单独的资源信息,如下所示:

/modules/security_groups/ssh/main.tf      <-- only has one aws_security_group resource
/modules/security_groups/http-80/main.tf  <-- only has one aws_security_group resource
/modules/security_groups/http-443/main.tf <-- only has one aws_security_group  resource
/modules/launch_configuration/main.tf     <-- only has one aws_launch_configuration resource 
/modules/auto_scaling_group/main.tf       <-- only has one auto_scaling_group resource
/modules/instances/main.tf                <-- only has one instance resource
....

/stage/vpc/main.tf
/stage/services/frontend-app/salon.tf   <-- source multiple /modules/... and vpc


/prod/vpc/main.tf
/prod/services/frontend-app/salon.tf    <-- source multiple /modules/... and vpc

或者每个模块是否应该包含资源信息的组合。以这个目录结构为例。

/modules/salon-app/main.tf  <-- has more than one resource aws_security_group, auto_scaling_group, launch_configuration_group ...etc
....

/stage/vpc/main.tf
/stage/services/frontend-app/salon.tf  <-- source /modules/salon-app/.. only once


/prod/vpc/main.tf
/prod/services/frontend-app/salon.tf  <-- source /modules/salon-app/.. only once

基本上,您是将 aws 资源捆绑到一个大文件中,还是将它们拆分为每个资源的单独文件,然后单独获取它们?

【问题讨论】:

  • 我有同样的问题,我最终将资源组合成一个模块(你的最后一个例子)。看我的问题。 *.com/questions/46611713/…
  • 谢谢!我在网上阅读的所有内容、博客和各种 terraform 代码示例都指向将资源合并到一个文件中。我仍然很困惑如何为不同的环境真正模块化它,这样你只需要调整一些参数而不必复制代码,但我想看看它是如何工作的。也许我试图做太多我不知道的模块化......

标签: module terraform infrastructure


【解决方案1】:

所以,我考虑这个问题的方式是这样的。对于您创建的内容,您将希望将资源组合在一起,例如创建 ECS 集群。这是一个如何做到这一点的例子: https://github.com/charles-d-burton/tf_ecs_cluster

在该示例中,它将创建一个集群、设置自动缩放、转发通知等等。然后配置输出以输出与其他资源相关的信息。在该示例中,我输出了集群名称和 arn。对于我的用例,我使用名为 terragrunt 的工具将其状态保存在 S3 中。然后我在其他模块/资源中引用该状态。基本上,细分是这样的: VPC - 模块 集群 - 模块 负载均衡器 - 模块 应用程序 - 引用这些模块的资源。

在构建地形时要记住的是,要限制在错误运行中可能造成的爆炸半径伤害。这就是为什么最好将基础设施块模块化并引用它们的远程状态,而不是采用整体方法来运行它。通过引用远程状态,您实际上是在组件之间创建 API 契约。如果他们不需要检查和重新检查每个基础设施,它还可以使您的 terraform 运行得更快。如果依赖资源尚未创建,运行也会更快失败,因为它们需要引用的数据不可用。

【讨论】: