是否可以访问terraform远程状态文件中的模块状态?

是否可以访问terraform远程状态文件中的模块状态?,terraform,Terraform,如果地形脚本使用具有输出的模块,则可以使用地形输出命令的-module选项访问这些模块输出: $ terraform output --help Usage: terraform output [options] [NAME] Reads an output variable from a Terraform state file and prints the value. If NAME is not specified, all outputs are printed. Opt

如果地形脚本使用具有输出的模块,则可以使用
地形输出
命令的
-module
选项访问这些模块输出:

$ terraform output --help
Usage: terraform output [options] [NAME]

  Reads an output variable from a Terraform state file and prints
  the value.  If NAME is not specified, all outputs are printed.

Options:

  -state=path      Path to the state file to read. Defaults to
                   "terraform.tfstate".

  -no-color        If specified, output won't contain any color.

  -module=name     If specified, returns the outputs for a
                   specific module

  -json            If specified, machine readable output will be
                   printed in JSON format
如果我将该状态文件存储在S3或类似文件中,那么我可以使用
terraform\u remote\u state
数据提供程序来引用主脚本的输出

data "terraform_remote_state" "base_networking" {
  backend = "s3"
  config {
    bucket = "${var.remote_state_bucket}"
    region = "${var.remote_state_region}"
    key = "${var.networking_remote_state_key}"
  }
}

resource "aws_instance" "my_instance" {
  subnets = "${data.terraform_remote_state.base_networking.vpc_id}"
}

是否可以访问状态文件中存在的模块输出?我正在寻找类似于
“${data.terraform\u remote\u state.base\u networking.module..}”
或类似的东西。

是的,您可以从自己的模块访问远程状态输出。您只需要“传播”输出

例如,假设您有这样的东西,您的
base\u网络
基础设施,其中包含用于创建专有网络的模块,并且您希望通过远程状态访问专有网络ID:

base_networking/
  main.tf
  outputs.tf
  vpc/
    main.tf
    outputs.tf
base\u networking/main.tf
中,您可以使用
base\u networking/VPC
模块创建专有网络:

module "vpc" {
  source = "./vpc"
  region = "${var.region}"
  name = "${var.vpc_name}"
  cidr = "${var.vpc_cidr}"
}
base\u networking/vpc/outputs.tf中,您的模块中有一个
id
输出:

output "id" {
  value = "${aws_vpc.vpc.id}"
}
base\u networking/outputs.tf
中,您还有一个
vpc\u id
输出,它传播
module.vpc.id

output "vpc_id" {
  value = "${module.vpc.id}"
有了它,您现在可以使用以下内容访问
vpc\u id

data "terraform_remote_state" "base_networking" {
  backend = "s3"
  config = {
    bucket = "${var.remote_state_bucket}"
    region = "${var.remote_state_region}"
    key = "${var.networking_remote_state_key}"
  }
}

[...]

vpc_id = "${data.terraform_remote_state.base_networking.vpc_id}"

我不确定我是否理解你在这里的要求。您能否提供一个Terraform文件的示例,该文件将创建您想要的输出以及您想要如何使用它?听起来你只是想从TF状态文件中访问模块的输出,但是你的问题已经解释了如何获取这些输出,所以我想我误解了一些事情。具体来说,我有多个terraform脚本,其中一个是“基础”,应用于其他所有东西之前。其他的引用它产生的状态。在这个基本脚本中,我使用模块,它们有在主脚本中引用的输出。我想在后面的依赖脚本中访问这些模块的输出。答案几乎显示了我要进行的设置。我只想在没有额外样板的情况下实现它。是的,我知道您可以设置引用模块输出的输出。我希望有一些方法不需要添加额外的样板文件。我希望能够通过
remote\u state
以与通过命令行相同的方式引用模块输出。唯一让我想到这是可能的,就是你可以在CLI中完成。很可能这是实现这一点的唯一方法。如果是这样,那么:(,但可以理解。从Terraform 0.12开始,您需要引用
输出
,例如
数据.Terraform\u remote\u state.base\u networking.outputs.vpc\u id
。我得到了这个解决方案的错误tf 12.24错误:在数据“Terraform\u remote\u state”中myfile.tf第4行不支持的块类型“base\u networking”:4:config{。它无法识别配置块应该是
config={…