如何使用0.12 for_each在模块内部使用条件资源

时间:2020-02-07 17:37:15

标签: terraform

我向模块传递了一个列表,它将创建ec2实例和eips并附加

我正在使用for_each,因此用户可以重新排序列表,并且Terraform不会尝试销毁任何内容

但是我现在如何使用条件资源?我仍然使用计数吗?如果是这样,那是因为您不能在for_each中使用count。

这是我的模块:

"scripts": {
    "start": "node node_modules/.bin/react-scripts start",
    "build": "node node_modules/.bin/react-scripts build",
    "test": "node node_modules/.bin/react-scripts test",
    "eject": "node node_modules/.bin/react-scripts eject"
  }

我还需要获取myip的mylist项目的值,因为我使用它来标记eip。因此,我认为我需要以某种方式索引到foreach循环中,并且还能够使用count或另一个列表来确定其是否已创建?

1 个答案:

答案 0 :(得分:0)

认为我明白了,但是我不愿意接受,直到它证实这不是错误的方式(不是出于意见,而是使用不当会导致实际问题)

variable "mylist" {
  type            = set(string)
  description     = "Name used for tagging, AD, and chef"
}

variable "createip" {
  type            = bool
  default         = true
}

locals {
  // set will-create-public-ip to empty array if false
  // otherwise use same mylist which module uses for creating instances
  will-create-public-ip = var.createip ? var.mylist : []
}

resource "aws_instance" "sdfsdfsdfsdf" {
  for_each    = var.mylist
  user_data   = data.template_file.user_data[each.key].rendered
  tags        = each.value
  ...

resource "aws_eip" "public-ip" {
  // will-create-public-ip set to mylist or empty to skip this resource creatation
  for_each    = will-create-public-ip
  instance = aws_instance.aws-vm[each.key].id
  vpc      = true
  tags     = each.value
}