2016-09-27 40 views
2

如果terraform脚本使用具有输出模块,它可以访问使用-module选项为terraform output命令这些模块输出:是否可以在terraform远程状态文件中访问模块状态?

$ 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_remote_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_remote_state.base_networking.module.<module_name>.<output>}"或类似的东西。

+0

我不知道我明白了什么你在这里要求。你能否提供一个Terraform文件的例子来创建你想要的输出,以及你想如何使用它?这听起来像你只是想从TF状态文件访问模块的输出,但你的问题已经解释了如何得到这些,所以我想我误解了一些东西。 – ydaetskcoR

+0

具体来说,我有多个terraform脚本,其中一个是在所有其他应用程序之前应用的“基础”。其他人参考它产生的状态。在该基本脚本中,我使用模块模块,并在主脚本中引用了输出。我想在后面的依赖脚本中访问这些模块的输出。 – dustyburwell

+0

答案[这里](http://stackoverflow.com/a/39785310/77040)显示了我要做的设置。我只想在没有额外样板的情况下实现它。 – dustyburwell

回答

4

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

例如,假设你有这样的事情,你base_networking基础设施,其中包含用于创建您的VPC一个模块,你想要的VPC ID是通过远程状态访问:

base_networking/ 
    main.tf 
    outputs.tf 
    vpc/ 
    main.tf 
    outputs.tf 

base_networking/main.tf

module "vpc" { 
    source = "./vpc" 
    region = "${var.region}" 
    name = "${var.vpc_name}" 
    cidr = "${var.vpc_cidr}" 
} 

在你的模块中base_networking/vpc/outputs.tf你有一个id输出:使用base_networking/vpc模块中创建您的VPC

output "id" { 
    value = "${aws_vpc.vpc.id}" 
} 

base_networking/outputs.tf你也有一个vpc_id模块传播module.vpc.id

output "vpc_id" { 
    value = "${module.vpc.id}" 

有了,你现在可以用的东西访问vpc_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}" 
+0

是的,我知道你可以设置引用模块输出的输出。我希望有一些方法不需要添加额外的样板。我希望能够通过'remote_state'特定地引用模块输出,就像你可以通过命令行一样。唯一指向我思考的事情是,你可以在CLI中做到这一点。 – dustyburwell

+0

这是很有可能的,这是实现这一目标的唯一方法。如果是这样,那么:(但可以理解。 – dustyburwell

相关问题