【问题标题】:'Not a valid output for module' when using output variable with terraform将输出变量与 terraform 一起使用时,“不是模块的有效输出”
【发布时间】:2018-06-13 13:06:09
【问题描述】:

我正在尝试为在 AWS 上使用 Hashicorp Terraform 的新项目设置一些 IaC。我使用模块是因为我希望能够在多个环境(staging、prod、dev 等)中重用东西

我很难理解我必须在模块中的何处设置输出变量,以及如何在另一个模块中使用它。任何指向此的指针将不胜感激!

在创建 EC2 机器时,我需要使用在我的 VPC 模块中创建的一些东西(子网 ID)。我的理解是,您不能在另一个模块中引用某个模块的内容,因此我尝试使用 VPC 模块中的输出变量。

我的网站中有以下内容main.tf

module "myapp-vpc" {
  source     = "dev/vpc"
  aws_region = "${var.aws_region}"
}

module "myapp-ec2" {
 source     = "dev/ec2"
 aws_region = "${var.aws_region}"
 subnet_id  = "${module.vpc.subnetid"}
}

dev/vpc 只是设置一些值并使用我的 vpc 模块:

module "vpc" {
  source = "../../modules/vpc"

  aws_region = "${var.aws_region}"

  vpc-cidr            = "10.1.0.0/16"
  public-subnet-cidr  = "10.1.1.0/24"
  private-subnet-cidr = "10.1.2.0/24"
}

在我的 vpc main.tf 中,在 aws_vpc 和 aws_subnet 资源(显示子网资源)之后,我在最后有以下内容:

resource "aws_subnet" "public" {
  vpc_id                  = "${aws_vpc.main.id}"
  map_public_ip_on_launch = true
  availability_zone       = "${var.aws_region}a"
  cidr_block              = "${var.public-subnet-cidr}"
}

output "subnetid" {
  value = "${aws_subnet.public.id}"
}

当我运行 terraform plan 时,我收到以下错误消息:

错误:模块“vpc”:“subnetid”不是模块“vpc”的有效输出

【问题讨论】:

  • 在为您的问题添加语法高亮显示后,我注意到最后一个代码块中的subnetid 输出中缺少双引号 ("),这可能导致了您的初始错误。跨度>

标签: amazon-web-services terraform infrastructure


【解决方案1】:

每次都需要明确地通过每个模块传递输出。

例如,如果您想从嵌套在另一个模块下方的模块中将变量输出到屏幕上,您需要这样的东西:

子模块.tf

output "child_foo" {
  value = "foobar"
}

父模块.tf

module "child" {
  source = "path/to/child"
}

output "parent_foo" {
  value = "${module.child.child_foo}"
}

main.tf

module "parent" {
  source = "path/to/parent"
}

output "main_foo" {
  value = "${module.parent.parent_foo}"
}

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 2021-01-11
    • 2021-05-06
    • 2021-04-09
    • 1970-01-01
    • 2020-12-22
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多