Terraform资源作为模块输入变量

问题描述

在开发terraform模块时,有时我发现自己需要为相同的资源定义不同的输入变量。例如,现在我需要为模块使用同一AWS / ECS集群的NAME和ARN,因此,我在模块中定义了两个变量:ecs_cluster_arnecs_cluster_name

出于DRY的考虑,如果我只定义类型ecs_cluster的输入变量aws_ecs_cluster并在模块内部使用我需要的任何东西,那将是非常好的。

我似乎找不到解决办法。有人知道这是否可能吗?

解决方法

您可以定义一个输入变量,其type constraintaws_ecs_cluster资源类型的架构兼容。通常,您会编写一个子集类型约束,其中仅包含模块实际需要的属性。例如:

variable "ecs_cluster" {
  type = object({
    name = string
    arn  = string
  })
}

在模块的其他位置,您可以使用var.ecs_cluster.namevar.ecs_cluster.arn来引用那些属性。模块的调用者可以传入与该类型约束兼容的任何内容,其中包括aws_ecs_cluster资源类型的整个实例,但还包括仅包含这两个属性的文字对象:

module "example" {
  # ...

  ecs_cluster = aws_ecs_cluster.example
}
module "example" {
  # ...

  ecs_cluster = {
    name = "blah"
    arn  = "arn:aws:yada-yada:blah"
  }
}

在许多情况下,这还将允许传递the corresponding data source的结果而不是托管资源类型。不幸的是,对于这种配对,由于某种原因,数据源使用了不同的属性名称cluster_name,因此不兼容。不幸的是,这不是同名托管资源类型和数据源对的典型设计约定。我认为这是设计疏忽。

module "example" {
  # ...

  # This doesn't actually work for the aws_ecs_cluster
  # data source because of a design quirk,but this would
  # be possible for most other pairings such as
  # the aws_subnet managed resource type and data source.
  ecs_cluster = data.aws_ecs_cluster.example
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...