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

spi*_*n p 9 terraform

terraform/env/res/main.tf:

resource "aws_security_group" "allow_all" {
  name        = "allow_all"
  description = "Allow all inbound traffic"
  vpc_id      = "${aws_vpc.main.id}"

  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
} 
Run Code Online (Sandbox Code Playgroud)

terraform/mod/sec/main.tf:

resource aws_elb " elb" { 
  name = "elb-example"
  subnets         = ["${data.aws_subnet_ids.all.ids}"]
  security_groups = ["${aws_security_group.allow_all.id}"] // SG 
  internal        = false
  listener = [
    {
      instance_port     = "80"
      instance_protocol = "HTTP"
      lb_port           = "80"
      lb_protocol       = "HTTP"
    },
    {
      instance_port     = "8080"
      instance_protocol = "HTTP"
      lb_port           = "8080"
      lb_protocol       = "HTTP"
    },
  ]

  health_check = [
    {
      target              = "HTTP:80/"
      interval            = 30
      healthy_threshold   = 2
      unhealthy_threshold = 2
      timeout             = 5
    },
  ]
  access_logs = [
    {
      bucket = "my-access-logs-bucket"
    },
  ]
  lifecycle {
    prevent_destroy = true
  }
}
Run Code Online (Sandbox Code Playgroud)

在变量 aws_security_group.allow_all_id 中遇到错误未定义变量 aws_security_group.allow_all。此外,是否可以验证字符串并添加额外的安全组。三元条件是我能想到的。你能建议任何其他选择吗?

Som*_*ter 11

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

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

output "sg_id" {
  value = aws_security_group.allow_all.id
}
Run Code Online (Sandbox Code Playgroud)

然后在res模块内引用sec模块。

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 = [
    # ...
  ]
  # ...
}
Run Code Online (Sandbox Code Playgroud)

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

terraform init && terraform plan
Run Code Online (Sandbox Code Playgroud)

并且应该在res模块中应用新的安全组,该模块使用 输出安全组 ID sg_id,然后sec模块将其用作aws_lb资源的输入。