问题描述
我正在尝试使用同级目录中的特定代码,但在这样做时遇到了一些麻烦.例如,请参阅下面的文件结构:
I am trying to use specific code from sibling directories and I am having some trouble doing so. As an example, please see below for how my files are structured:
parents/
brother/
main.tf
outputs.tf
variables.tf
sister/
main.tf
outputs.tf
variables.tf
我想在 sister/main.tf
中使用我在 brother/main.tf
中创建的定义,但我似乎无法找出正确的方法这样做.我尝试过使用模块:
I want to use a definition that I created in brother/main.tf
in sister/main.tf
and I can't seem to figure out the right way to do so. I have tried to use modules:
module "brother" {
source = "../brother"
}
这样做行得通,但行不通.我能够导入和使用代码,但由于某种原因,terraform 正在使用新的模块名称(如果这有意义的话)创建一堆具有新资源名称的其他资源.从本质上讲,它创建了所需的资源,但也创建了 100 多个其他不需要的资源.
Doing this works, but it doesn't. I am able to import and use the code, but for some reason terraform is creating a bunch of other resources with a new resource name, using the new module name (if that makes any sense). Essentially, it creates the desired resource, but also created 100+ other unwanted.
通过将我想要使用的定义放在同一个 sister
目录中,我可以轻松地完成这项工作,但这不是我想要构建文件的方式.这样做的正确方法是什么?如果我有一个在 brother
中定义的 IAM 角色,并且我想在 sister
中引用它,我该怎么做?提前致谢!
I can easily get this to work by putting the definition I want to use in the same sister
directory, but that is not how I want to structure my files. What is the right way to do this? If I have an IAM role that is defined in brother
, and I want to reference it in sister
, how can I do that? Thanks in advance!
当前代码:
姐妹/main.tf
resource "aws_config_config_rule" "test-rule" {
name = "test-rule"
source {
owner = "AWS"
source_identifier = "TEST"
}
depends_on = ["aws_config_configuration_recorder.config_configuration_recorder"]
}
resource "aws_config_configuration_recorder" "config_configuration_recorder" {
name = "config_configuration_recorder"
role_arn = "${var.test_assume_role_arn}"
}
兄弟/main.tf
resource "aws_iam_role" "test_assume_role" {
name = "${var.test_assume_role_name}"
path = "/"
assume_role_policy = <<POLICY
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": "config.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
POLICY
}
所以基本上,我希望能够使用 sister/main.tf
中的 test_assume_role
arn.
So basically, I want to be able to use the test_assume_role
arn in the sister/main.tf
.
推荐答案
当您需要另一个模块时,它将重新创建这些资源.听起来您想引用已创建资源的状态.您可以使用远程状态数据源来做到这一点.
When you require another module it will recreate those resources.It sounds like you want to reference the state of the already created resources. You can do this using remote state data source.
这允许您读取另一个状态的输出,但不会创建额外的资源
This allows you to read outputs of another state but doesn't create additional resources
data "terraform_remote_state" "brother" {
backend = "..."
}
resource "aws_instance" "sister" {
# ...
subnet_id = "${data.terraform_remote_state.brother.my_output}"
}
这篇关于如何使用来自 terraform 同级目录的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!