2016-09-27 39 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

相關問題