【问题标题】:Optional variable in Terraform is not ignored when the value is nullTerraform 中的可选变量在值为 null 时不会被忽略
【发布时间】:2021-04-13 16:48:53
【问题描述】:

我在一个模块中有 Terraform“aws_instance”资源。当 ami 设置为 var.ami_id 并使用单个给定字符串时,它按预期工作。 为了将此模块用于不同的目的,我已将 var.ami_ids 添加为列表(字符串)并添加为可选变量。

ami           = var.ami_ids == [""] ? var.ami_id : var.ami_ids[count.index]

变量.tf

variable "ami_id" {
  description = "ID of AMI to use for the instance"
  type        = string
  default     = ""
}
variable "ami_ids" {
  description = "List of IDs of AMI to use for the instance"
  type        = list(string)
  default     = [""]
}

main.tf

resource "aws_instance" "ec2" {
  count = var.number_of_ec2_instances_required

  ami           = var.ami_ids == [""] ? var.ami_id : var.ami_ids[count.index]
  instance_type = var.instance_type
  private_ip    = length(var.private_ips) > 0 ? element(var.private_ips, count.index) : var.private_ip
  subnet_id = length(var.network_interface) > 0 ? null : element(
    distinct(compact(concat([var.ec2_subnets_id], var.ec2_subnets_ids))),
    count.index,
  )
  key_name                    = var.key_name
  monitoring                  = var.monitoring
  iam_instance_profile        = var.iam_instance_profile
  vpc_security_group_ids      = var.vpc_security_group_ids
  associate_public_ip_address = var.associate_public_ip_address
  ebs_optimized               = var.ebs_optimized
  ...
}

虽然“ami_ids”没有声明值(即 null),但我收到以下错误。

Error: Invalid index

  on ../../modules/ec2/main.tf line 23, in resource "aws_instance" "ec2":
  23:   ami           = var.ami_ids == [""] ? var.ami_id : var.ami_ids[count.index]
    |----------------
    | count.index is 1
    | var.ami_ids is list of string with 1 element

The given key does not identify an element in this collection value.

Releasing state lock. This may take a few moments...

有人可以在这里帮助我以更好的方式做到这一点。

谢谢

【问题讨论】:

    标签: amazon-web-services variables amazon-ec2 terraform


    【解决方案1】:

    您的条件 var.ami_ids == [""] 将始终为false。这意味着无论如何var.ami_ids[count.index]都会执行。

    如果你真的想使用这样的条件应该是:

    var.ami_ids == tolist([""])
    

    或者将您的变量更改为:'

    variable "ami_ids" {
      description = "List of IDs of AMI to use for the instance"
      type        = list(string)
      default     = []
    }
    

    条件使用:

    length(var.ami_ids) == 0
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 2016-03-24
      • 2014-10-02
      • 2017-01-30
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多