2

我有两个计划,其中我正在创建两个不同的服务器(例如,否则它真的很复杂)。在一个计划中,我正在输出安全组的值,如下所示:

output "security_group_id" {
  value = "${aws_security_group.security_group.id}"
}

我有第二个计划,我想在其中使用该价值,如何实现它,我尝试了几件事,但对我没有任何作用。

我知道如何使用output返回值,module但不知道如何将output一个计划用于另一个计划。

4

2 回答 2

2

在配置的顶级模块(您运行的目录terraform plan)中使用输出时,其值将记录在 Terraform 状态中。

为了从另一个配置中使用这个值,必须将状态发布到另一个配置可以读取它的位置。实现这一点的常用方法是使用Remote State

为第一个配置启用远程状态后,可以使用数据源从第二个配置terraform_remote_state读取结果值。

例如,可以通过使用如下后端配置来保留 Amazon S3 中第一个配置的状态:

terraform {
  backend "s3" {
    bucket = "example-s3-bucket"
    key    = "example-bucket-key"
    region = "us-east-1"
  }
}

将此添加到第一个配置后,Terraform 将提示您运行terraform init以初始化新后端,其中包括迁移现有状态以存储在 S3 上。

然后在第二个配置中,可以通过向terraform_remote_state数据源提供相同的配置来检索它:

data "terraform_remote_state" "example" {
  backend = "s3"
  config {
    bucket = "example-s3-bucket"
    key    = "example-bucket-key"
    region = "us-east-1"
  }
}

resource "aws_instance" "foo" {
  # ...
  vpc_security_group_ids = "${data.terraform_remote_state.example.security_group_id}"
}

请注意,由于第二个配置是从第一个配置中读取状态,因此必须对terraform apply第一个配置进行配置,以便该值实际记录在状态中。每当第一次更改输出时,必须重新应用第二个配置。

于 2017-09-25T23:13:13.410 回答
1

对于local后端,过程是相同的。第一步,我们需要声明以下代码片段来发布状态。

terraform {
 backend local {
    path = "./terraform.tfstate" 
  }
}

执行terraform init and terraform apply命令时,请注意在目录中会创建包含后端信息的.terraform新文件,并告诉 terraform 使用以下文件。terraform.tfsatetfstate

现在在第二个配置中,我们需要data source使用此代码片段来导入输出

 data "terraform_remote_state" "test" {

 backend = "local"
  config {
    path = "${path.module}/../regionalvpc/terraform.tfstate"
  }
}
于 2018-10-07T06:56:30.283 回答