Terraform模块结构

Terraform module structure

我的所有 .tf 文件都有一个平面结构,我想迁移到基于文件夹(即 module)的设置,以便我的代码更清晰。

例如,我已将我的实例和弹性 IP (eip) 定义移动到单独的文件夹中

/terraform
 ../instance
   ../instance.tf
 ../eip
    ../eip.tf

在我的 instance.tf:

resource "aws_instance" "rancher-node-production" {}

在我的 eip.tf:

module "instance" {
  source = "../instance"
}


resource "aws_eip" "rancher-node-production-eip" {
  instance = "${module.instance.rancher-node-production.id}"

然而当运行 terraform plan:

Error: resource 'aws_eip.rancher-node-production-eip' config: "rancher-node-production.id" is not a valid output for module "instance"

将模块视为您无法 "reach" 进入的黑盒子。要从模块中获取数据,该模块需要使用 output 导出该数据。因此,在您的情况下,您需要将 rancher-node-production id 声明为 instance 模块的输出。

如果您查看所收到的错误,它的意思就是这样:rancher-node-production.id 不是模块的有效输出(因为您从未将其定义为输出)。

无论如何,这就是它的样子。

# instance.tf
resource "aws_instance" "rancher-node-production" {}

output "rancher-node-production" {
    value = {
        id = "${aws_instance.rancher-node-production.id}"
    }
}

希望能为您解决问题。