【问题标题】:Terragrunt Multiple Instances Of Module With Varying FieldsTerragrunt 具有不同字段的模块的多个实例
【发布时间】:2021-10-22 22:03:38
【问题描述】:

我很难理解如何反映我在 Terragrunt 中习惯的原生 Terraform 模块实例化结构。采用以下 Terraform 结构,该结构创建 sns topic module 的不同实例。

module "sns_topic" {
  source  = "terraform-aws-modules/sns/aws"
  version = "~> 3.0"

  name  = "my-topic"
}

module "sns_topic_two" {
  source  = "terraform-aws-modules/sns/aws"
  version = "~> 3.0"

  name  = "my-topic-two"
  content_based_deduplication              = true
}

module "sns_topic_three" {
  source  = "terraform-aws-modules/sns/aws"
  version = "~> 3.0"

  name  = "my-topic-three"
  http_success_feedback_role_arn           = x
  http_success_feedback_sample_rate        = y
  http_failure_feedback_role_arn           = z
}
...

任何fields in the module itself 都可以填充该模块的给定实例。

对于模块的每个实例可能因字段使用而异的情况,我不明白如何在 Terragrunt via their Inputs 中完成此操作。例如,在 sns 模块中,您可以拥有使用 content_based_deduplication 的主题 A 和使用 lambda_success_feedback_role_arn 的主题 B 和使用完全不同的字段的主题 C,并且您可能在环境中有 100 个不同的主题。在本机 Terraform 中,您只需实例化每个模块,如上所示。但是如何通过 Terragrunt 做到这一点?

【问题讨论】:

    标签: terraform terragrunt


    【解决方案1】:

    (免责声明:以下内容仅代表我的理解和工作流程,可能不是确定的:))

    我的理解是,虽然您可以在顶级模块中编写本机 Terraform,但最佳做法是将其移至另一个模块,从您的 terragrunt.hcl 文件中的 terraform 块调用。该模块充当编排层。我认为这个想法是 Terragrunt 项目的顶层可能代表您在每个项目中广泛需要相同资源的事物(例如 dev、test、prod),因此使用此编排模块可以让您干燥该代码,而不是在顶级目录之间复制它。

    因此,在您的情况下,我认为您需要编写一个看起来有点像这样的模块,并从您的 terragrunt.hcl 文件中调用:

    top_level/main.tf

    variable "sns_topics" {
      type = map(map(string))
    }
    
    module "sns_topic" {
      source   = "terraform-aws-modules/sns/aws"
      version  = "~> 3.0"
      for_each = var.sns_topics
    
      name                           = each.key 
      content_based_deduplication    = lookup(each.value, "content_based_deduplication", null)
      http_success_feedback_role_arn = lookup(each.value, "http_success_feedback_role_arn", null)
    }
    
    

    然后你的terragrunt.hcl 中的inputs 可能看起来像这样:

    inputs = {
      sns_topics = {
        sns_topic = {},
        sns_topic_two = {
          content_based_deduplication = true
        },
        sns_topic_three = {
          http_success_feedback_role_arn = "x"
        }
      }
    }
    

    最后,您将在 terragrunt.hclterraform 块中调用 top_level 模块

    terraform {
      source = "git::git@github.com:<your_account>/modules.git//top_level?ref=v0.0.1"
    }
    

    注意:在lookup 函数中使用null 作为默认值,在特定主题映射不包含该特定键的情况下应导致该参数被省略。

    Terragrunt 文档中的This page 详细讨论了这种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      相关资源
      最近更新 更多