引用在不同文件夹中创建的 Terraform 资源 [英] Referencing Terraform resource created in a different folder

查看:21
本文介绍了引用在不同文件夹中创建的 Terraform 资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件夹结构:

infrastructure
└───security-groups
│   │   main.tf
│   │   config.tf
│   │.  security_groups.tf
│   
└───instances
    │   main.tf
    │   config.tf
    │   instances.tf

我想通过引用来引用在 security-groups 文件夹中实例化的安全组 ID.我试图在 security_groups.tf 文件中输出所需的 ID

I would like to reference the security group id instantiated in security-groups folder by reference. I have tried to output the required ids in the security_groups.tf file with

output "sg_id" {
  value = "${aws_security_group.server_sg.id}"
}

然后在实例文件中将其添加为模块:

And then in the instances file add it as a module:

module "res" {
  source = "../security-groups"
}

这种方法的问题在于,当我在实例文件夹中执行 terraform apply 时,它也会尝试创建安全组(我已经通过在 security-groups 文件夹中执行 terraform apply 创建了该安全组)并且它失败了,因为SG 是存在的.

The problem with this approach is that when I do terraform apply in the instances folder, it tries to create the security groups as well (which I have already created by doing terraform apply in the security-groups folder) and it fails because the SGs are existing.

在不更改代码结构的情况下,引用在不同文件夹中创建的资源的最简单方法是什么?

What would be the easiest way to reference the resources created in a different folder, without changing the structure of the code?

谢谢.

推荐答案

要引用现有资源,您需要使用 data 块.您不会直接引用其他文件夹中的资源块,而是指定名称或 ID 或它具有的任何其他唯一标识符.因此,对于 安全组,您需要添加像

To refer to an existing resource you need to use a data block. You won't refer directly to the resource block in the other folder, but instead specify a name or ID or whatever other unique identifier it has. So for a security group, you would add something like

data "aws_security_group" "sg" {
  name = "the-security-group-name"
}

到您的实例文件夹,并引用该实体以将您的实例与该安全组相关联.

to your instances folder, and refer to that entity to associate your instances with that security group.

您还应该考虑是否真的只想将 terraform 应用到整个树,而不是单独应用每个文件夹.然后,您可以像尝试那样直接在所有托管资源之间进行引用,而不必多次调用 terraform apply.

You should also consider whether you actually want to be just applying terraform to the whole tree, instead of each folder separately. Then you can refer between all your managed resources directly like you are trying to do, and you don't have to call terraform apply as many times.

这篇关于引用在不同文件夹中创建的 Terraform 资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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