【问题标题】:How to reference a resource created in one file in another file in terraform如何在terraform的另一个文件中引用在一个文件中创建的资源
【发布时间】:2019-06-15 15:51:35
【问题描述】:

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"]
  }
} 

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
  }
}

遇到错误未定义变量 aws_security_group.allow_all 在变量 aws_security_group.allow_all_id 中。此外,是否可以验证字符串并添加额外的安全组。三元条件是我能想到的。您能否提出其他替代方案?

【问题讨论】:

  • 您的文件在您使用数据源的地方是什么样的?
  • 我正在创建一个 aws_elb 资源并在其中访问此安全组。资源 "aws_elb" "myelb" { security_groups_1 = [ "${aws_security_group.allow_all.id}" ] @yd
  • 编辑问题以显示整个第二个文件并显示每个文件的文件路径。如果这是很多代码,那么您应该考虑尝试将其剥离为 minimal reproducible example
  • 你能在你的代码上运行terraform fmt吗?

标签: terraform


【解决方案1】:

看起来你有两个模块,一个是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
}

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

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,就可以运行了

terraform init && terraform plan

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

【讨论】:

  • 如何在多个文件中引用同一个模块?它说模块名称必须是唯一的
  • @SouradeepNanda 您可以拥有多个具有相同源但名称不同的模块。例如,我回答中的上述模块显示module "sec" 的源为env/res,您可以使用module "sec2" 创建另一个具有相同源的模块引用,现在您有两个不同名称的相同模块引用。
猜你喜欢
  • 2020-12-17
  • 2021-12-11
  • 2021-11-10
  • 2021-12-14
  • 2022-07-01
  • 2021-01-13
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多