djsmiley2kStaysInside
djsmiley2kStaysInside

Reputation: 286

Terraform: Optional fields in Resource

In terraform I'm trying to create some firewall rules, which normally don't have logging enabled - to accomplish this, I must not have the log_config field created. However, I have a variable firewall_logging, which if true, should add this field and the options I wish it to contain.

I don't think using a dynamic here is quite the right thing to do but it's possible it is and I've misunderstood how to generate it, instead I came up with the following:

resource "google_compute_firewall" "this" {
  name          = var.name
  project       = var.project
  network       = var.network
  source_ranges = var.source_ranges
  source_tags   = var.source_tags
  target_tags   = var.target_tags
  priority      = var.priority
  direction     = var.direction

  allow {
    protocol = lower(var.protocol)
    ports    = var.ports
  }

  ##  If log_config is defined, this enables logging. By not defining it, we are disabling logging.
  var.firewall_logging == true ? log_config { metadata = var.log_metadata } : null

I was hoping that the variable would be evaluated, and if true, the log_config section is added to the resource but I get an error that a argument or block definition is required.

Upvotes: 2

Views: 736

Answers (1)

aherve
aherve

Reputation: 4070

It should work using dynamic blocks. For instance:

dynamic "log_config" {
  for_each = var.firewall_logging == true ? [true] : []
  content {
    metadata = var.log_metadata
  }
}

Upvotes: 3

Related Questions