【问题标题】:resource output value from one plan into another plan从一个计划到另一个计划的资源输出值
【发布时间】:2018-03-06 18:13:48
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: terraform terraform-template-file


    【解决方案1】:

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

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

    first 配置启用远程状态后,可以使用 the terraform_remote_state data sourcesecond 配置中读取结果值。

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

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

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

    然后在 second 配置中,可以通过向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 第一个配置,以便该值实际记录在状态中。每次更改第一个配置时,都必须重新应用第二个配置。

    【讨论】:

    • 如果我有本地state 文件怎么办?
    • 避免本地状态文件
    【解决方案2】:

    对于local 后端,过程相同。第一步,我们需要声明如下代码sn-p来发布状态。

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

    当你执行terraform init and terraform apply命令时,请注意在.terraform目录下会创建一个新的terraform.tfsate文件,其中包含后端信息,并告诉terraform使用下面的tfstate文件。

    现在在第二个配置中,我们需要使用data source 通过使用此代码 sn-p 导入输出

     data "terraform_remote_state" "test" {
    
     backend = "local"
      config {
        path = "${path.module}/../regionalvpc/terraform.tfstate"
      }
    }
    

    【讨论】:

    • 你不想在本地做。
    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多