将输出变量与 terraform 一起使用时,“不是模块的有效输出" [英] 'Not a valid output for module' when using output variable with terraform

查看:22
本文介绍了将输出变量与 terraform 一起使用时,“不是模块的有效输出"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 AWS 上使用 Hashicorp Terraform 为新项目设置一些 IaC.我使用模块是因为我希望能够在多个环境(暂存、生产、开发等)中重用东西

I'm trying to setup some IaC for a new project using Hashicorp Terraform on AWS. I'm using modules because I want to be able to reuse stuff across multiple environments (staging, prod, dev, etc.)

我正在努力理解我必须在模块中的何处设置输出变量,以及如何在另一个模块中使用它.对此的任何指示将不胜感激!

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

I need to use some things created in my VPC module (subnet IDs) when creating EC2 machines. My understanding is that you can't reference something from one module in another, so I am trying to use an output variable from the VPC module.

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

I have the following in my site 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 模块:

dev/vpc simply sets some values and uses my vpc module:

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_vpcaws_subnet 资源(显示子网资源)之后,我在最后有以下内容:

In my vpc main.tf, I have the following at the very end, after the aws_vpc and aws_subnet resources (showing subnet resource):

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 时,我收到以下错误消息:

When I run terraform plan I get the following error message:

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

Error: module 'vpc': "subnetid" is not a valid output for module "vpc"

推荐答案

输出每次都需要明确地向上传递到每个模块.

Outputs need to be passed up through each module explicitly each time.

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

For example if you wanted to output a variable to the screen from a module nested below another module you would need something like this:

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}"
}

这篇关于将输出变量与 terraform 一起使用时,“不是模块的有效输出"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆