且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在terraform的另一个文件中引用在一个文件中创建的资源

更新时间:2023-11-03 18:42:28

看起来你有两个模块,一个是 terraform/mod/sec 另一个是 terraform/env/资源.前者定义 aws_security_group 资源,后者使用该安全组 ID 创建 aws_elb 资源.

It looks like you have two modules, one is terraform/mod/sec and the other is terraform/env/res. The former defines an aws_security_group resource and the latter uses that security group id to create a aws_elb resource.

我假设您正在从不正确的 res 目录运行 terraform.相反,应该做的是在 res 模块中输出安全组 ID

I'm assuming you're running terraform from the res directory which is incorrect. Instead what should be done is output the security group id in the res module

output "sg_id" {
  value = aws_security_group.allow_all.id
}

然后在 sec 模块中引用 res 模块.

and then reference the res module within the sec module.

module "res" {
  source = "../../env/res"
}

resource "aws_lb" "lb" {
  name            = "lb-example"
  subnets         = [data.aws_subnet_ids.all.ids]
  security_groups = [module.res.sg_id] # uses the module output to insert SG
  internal        = false
  listener = [
    # ...
  ]
  # ...
}

然后从这个目录terraform/mod/sec,就可以运行了

Then from this directory terraform/mod/sec, this can be run

terraform init && terraform plan

并且应该在 res 模块中应用新的安全组,该模块使用 sg_id 输出安全组 id,然后由 sec 模块作为 aws_lb 资源的输入.

and that should apply the new security group in the res module which outputs the security group id using sg_id, which is then used by the sec module as an input to the aws_lb resource.