reddy0969
reddy0969

Reputation: 109

Optional variable in Terraform is not ignored when the value is null

I have Terraform "aws_instance" resource in a module. When ami set to var.ami_id and with a with a single given string it works as expected. To use this module for a different purpose I have added var.ami_ids as list(string) and added as an optional variable.

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

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

Though "ami_ids" has no value declared(i.e null) I am getting the following error.

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

Could someone please help me here to do this in a better way.

Upvotes: 1

Views: 2244

Answers (1)

Marcin
Marcin

Reputation: 238209

Your condition var.ami_ids == [""] will always be false. This means that in any case var.ami_ids[count.index] executes.

If you really want to use such a condition it should be:

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

Alternatively change your variable to:'

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

and for condition use:

length(var.ami_ids) == 0

Upvotes: 2

Related Questions