在根模块中使用 aws_vpc 数据源的 Terraform 鸡/蛋问题 [英] Terraform chicken/egg problem using aws_vpc data source in root module

查看:23
本文介绍了在根模块中使用 aws_vpc 数据源的 Terraform 鸡/蛋问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个根 Terraform 模块,它声明了一个 VPC 模块和其他模块,例如要在 VPC 中启动的 EC2 实例.

I have a root Terraform module that declares a VPC module and other modules such as an EC2 instance that is to launch in the VPC.

在 EC2 模块中,我使用 aws_vpc 类型读取 VPC:

In the EC2 module, I read the VPC using the aws_vpc type:

data "aws_vpc" "vpc" {
  filter {
    name  = "tag:Name"
    values = [var.name_tag]
  }
}

现在,如果我独立声明模块,这可以正常工作.

Now this works fine if I declare the modules independently.

但是当声明一个单独声明这些其他模块的根模块时,我得到了这个失败:

But when declaring a root module that declares these other modules separately, I get this failure:

▶ terraform apply
module.cloudwatch.data.aws_ami.ami: Refreshing state...
module.backend.data.aws_vpc.vpc: Refreshing state...
module.backend.data.aws_ami.ami: Refreshing state...

Error: no matching VPC found

  on .terraform/modules/backend/main.tf line 1, in data "aws_vpc" "vpc":
   1: data "aws_vpc" "vpc" {

所以这里有一个鸡/蛋的问题.

So there is a chicken/egg problem here.

我很困惑.这怎么可能奏效?如果一个根模块不能同时声明一个 VPC,然后使用 aws_vpc 数据源将其读入其他模块,那么这些数据源有什么用?我会很感激关于这里的最佳实践的建议.我是否应该不使用 aws_vpc 而是在其他地方读取 VPC ID 作为输出?

I am confused. How can this ever work? If a root module cannot both declare a VPC and then use the aws_vpc data source later to read it into other modules, what is the use of these data sources? I would appreciate advice on the best practice here. Should I simply not use aws_vpc and instead read in the VPC ID as an output elsewhere?

推荐答案

对我来说,这听起来就像你在声明两个资源一样

To me this sounds like you are declaring both a resource like

resource "aws_vpc" "example" {}

与数据提供者类似

data "aws_vpc" "example" {}

为了从 data.aws_vpc.example.arn 之类的数据中访问某些内容.这不是必需的,实际上是导致您的错误.如果两者都处于相同的 terraform 状态,您可以简单地删除 data "aws_vpc" "example" {} 并通过例如引用资源resource.aws_vpc.example.arn.

in order to access something from the data like data.aws_vpc.example.arn. This is not needed and in fact is causing your error. If both is in the same terraform state, you can simply drop the data "aws_vpc" "example" {} and refer to the resource by e.g. resource.aws_vpc.example.arn.

数据提供者实际上仅在您指的是在其他地方创建的资源时才需要,例如手动创建的资源,由不同的供应引擎(或也由 terraform,但在不同的层).

The data provider is actually only needed in cases in which you are referring to a resource that is created somewhere else like something created manually, by a different provisioning engine (or also by terraform, but in a different layer).

这篇关于在根模块中使用 aws_vpc 数据源的 Terraform 鸡/蛋问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆