简体   繁体   中英

Terraform: How to add a filter to a data source conditionally

Given the data source definition:

data "aws_ami" "my_ami" {
  filter {
    name   = "name"
    values = ["my_ami_name"]
  }
}

How does one add a second filter only if a condition is true?

Example pseudo code of what I want:

data "aws_ami" "my_ami" {
  filter {
    name   = "name"
    values = ["my_ami_name"]
  }
  var.state ? filter {
    name   = "state"
    values = [var.state]
  } : pass
}

The second filter would only be used if the state variable has content.

Note that I don't want to use a 'N/A' value to always use the second filter, regardless if it's needed or not.

You can use dynamic blocks . The condition depends exactly on what is your condition ( var.state is not shown, so I don't know what it is), but in general you can do:

data "aws_ami" "my_ami" {

  filter {
    name   = "name"
    values = ["my_ami_name"]
  }

  dynamic "filter" {
    for_each = var.state ? [1] : []
    content {
      name   = "state"
      values = [var.state]    
    }
  } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM