terraform - 资源产出值从一个计划转移到另一计划

标签 terraform terraform-template-file

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

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

我有第二个计划,我想在其中使用该值,如何实现它,我尝试了一些方法,但没有任何效果。

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

最佳答案

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

为了使用其他配置中的该值,必须将状态发布到其他配置可以读取的位置。实现此目的的常用方法是使用 Remote State .

第一个配置启用远程状态后,可以使用the terraform_remote_state data source第二配置读取结果值。 .

例如,可以通过使用如下所示的后端配置来保留 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 第一个配置,以便该值实际上记录在状态中。每当第一个配置中的输出发生更改时,都必须重新应用第二个配置。

关于terraform - 资源产出值从一个计划转移到另一计划,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46410906/

相关文章:

Terraform - 如何修改 Terraform 中的 map 对象?

azure - 使用现有资源在 Azure 中的 terraform 中创建资源并创建新资源

terraform - user_data 中的命令不在 terraform 中执行

Terraform:如何将文件资源与实例和 RDS 解耦

amazon-web-services - Terraform 导入 aws_cloudwatch_log_stream

lambda - 使用 Terraform/CloudFormation/其他东西有效部署 lambda(仅部署已更改的)

azure - 尝试使用azure terraform在应用程序网关上附加SSL证书

terraform - 在 terraform 中使用 count.index ?

amazon-web-services - 如何在同一个 VPC 中使用 terraform 配置两个 ECS 集群?

azure - 托管资源 "azurerm_network_interface" "myterraformnic"尚未在 module.vm 中声明。 azure