red888
red888

Reputation: 31672

How to use null with a different value in place of default value

I know that null can be used like this to set default behavior if var not specified:

variable "override_private_ip" {
  type    = string
  default = null
}

resource "aws_instance" "example" {
  # ... (other aws_instance arguments) ...
  private_ip = var.override_private_ip
}

But I want to set my own default behavior if it's not specified.

I'm doing this:

#### if user sets an id use that but if not get id from data source
resource "aws_instance" "myserver" {
  ami = var.ami_id != null ? var.ami_id : data.aws_ami.getami.id

This seems to work but is this the correct way? I want to make sure I'm not missing a feature for this. I tried just var.ami_id ? var.ami_id : data.aws_ami.getami.id but null is not converted to a bool so did not work.

Upvotes: 3

Views: 11411

Answers (1)

Martin Atkins
Martin Atkins

Reputation: 74694

A conditional expression like the one you showed is indeed the right way to express this in Terraform. As you've seen, Terraform does not consider null to be a boolean false.


It doesn't seem like it would be necessary for this particular situation, but if you have input variables that are used in many places where all uses would need the same normalization/preparation logic then you can factor out the expression into a local value to use it many times:

variable "ami_id" {
  type    = string
  default = null
}

data "aws_ami" "example" {
  count = var.ami_id == null ? 1 : 0

  # ...
}

locals {
  ami_id = var.ami_id != null ? var.ami_id : data.aws_ami.example[0].id
}

resource "aws_instance" "example" {
  # ... (other aws_instance arguments) ...
  ami = local.ami_id
}

You could then use local.ami_id many times in the module without duplicating the logic that handles the default value lookup.

Upvotes: 2

Related Questions