1

在 AWS 中使用 Terraform (TF) 并在尝试使用 terraform_remote_state 调用 vpc_id 时遇到错误。我们分割了网络的不同部分以减轻状态滑移。但是,它还需要与基础设施的每个单独部分的状态文件(即 vpc、sgs、角色等的状态文件)进行交互。当我尝试从 S3 存储桶中保存的状态文件中获取 vpc_id 时,我收到以下错误:


  on main.tf line 78, in module "vpc_sg":
  78:   vpc_id = data.terraform_remote_state.vpc.vpc_id

This object has no argument, nested block, or exported attribute named
"vpc_id".

这是我在 main.tf 文件中的 terraform_remote_state 调用:

  backend = "s3"
  workspace = var.workspace
  config = {
    bucket = "terraform-east"
    key = "terraform-vpc.tfstate"
    region ="us-east-1" 
  }
}

这是同一个 main.tf 中的调用

  // output "sg_id"
  source = "git::https://url_to_sg.git/reference?
  vpc_cidr = data.terraform_remote_state.vpc.vpc_cidr -- This line also doesn't work.. but same issue.
  *vpc_id = data.terraform_remote_state.vpc.vpc_id* -- Here's the troublesome line.
  deployment_name = "*redacted*"
  workspace = var.workspace
  tags = merge(
    local.common_tags,
    map(
      "Name", "vpc_sg-${var.workspace}",
      "module", "vpc_sg"
    )
  )
}

这是 vpc 目录中的 outputs.tf 文件:

output "vpc_id" {
  value       = module.vpc.vpc_id
  description = "The VPC ID"
}

output "vpc_cidr" {
  value       = var.vpc_cidr
  description = "The VPC CIDR block"
}

这是 tf_remote_state 声明:

data "terraform_remote_state" "vpc" {
    backend = "s3"
    workspace = var.workspace
    config = {
         bucket = "correct bucket (trust me)
         key = "correct key"
         region = us-east-1
    }
}

最后,这是来自 vpc 目录的 backend.tf 信息:

terraform {
    backend "s3" {
        bucket = "terraform-east"
        key = "terraform-vpc.tfstate"
        region ="us-east-1" 
        }
}

我尝试过使用 output.vpc_id (如上),没有输出(在 tf 0.12 更新后需要输出),使用 outputs.vpc_id.value (因为 statefile 使它看起来像这样的结构),以及使用输出 [1] .value.. 它给出了不同的错误,但它们都失败了。帮助将不胜感激。

4

3 回答 3

4

数据源在terraform_remote_state名为 的属性下从远程状态导出输出,该属性outputs本身是一个对象值,每个输出值包含一个属性。

因此,要特别引用vpc输出值,您需要编写:

data.terraform_remote_state.outputs.vpc

...然后vpc_id从该嵌套vpc对象中获取属性:

data.terraform_remote_state.outputs.vpc.vpc_id
于 2020-12-19T00:40:40.340 回答
1

terraform v 0.12 中引用状态值的方式发生了变化。请参阅此处的参考:

https://www.terraform.io/upgrade-guides/0-12.html#remote-state-references

从指南:

在以前的版本中,对远程状态数据源导出的 vpc_id 输出的引用可能如下所示:

data.terraform_remote_state.vpc.vpc_id

现在必须通过新的输出属性访问此值:

data.terraform_remote_state.vpc.outputs.vpc_id

于 2021-09-15T06:01:05.063 回答
0

原来这很简单。需要确保已建立 VPN 连接。-_- 感谢您的观看!

于 2020-12-21T18:56:03.773 回答