【问题标题】:How to have conditional resources inside a module with 0.12 for_each如何在具有 0.12 for_each 的模块内拥有条件资源
【发布时间】:2020-05-23 21:16:04
【问题描述】:

我正在向我的模块传递一个列表,它将创建 EC2 实例和 eips 并附加。

我正在使用 for_each,因此用户可以重新排序列表,Terraform 不会尝试破坏任何内容。

但是我现在如何使用条件资源呢?我还用计数吗?如果是这样怎么办,因为你不能用 for_each 使用 count?

这是我现在的模块:

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

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

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

#conditional for EIP
resource "aws_eip" "public-ip" {
  for_each    = var.mylist
  // I can't use this anymore!
  // how can I say if true create else don't create
  #count       = var.createip ? 0 : length(tolist(var.mylist))
  instance = aws_instance.aws-vm[each.key].id
  vpc      = true
  tags     = each.value
}

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

【问题讨论】:

    标签: terraform


    【解决方案1】:

    我认为我明白了,但在确认这不是错误的方式之前我不想接受(不是意见问题,而是使用不当会导致实际问题)。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2021-07-21
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2020-08-08
      • 2021-09-24
      相关资源
      最近更新 更多