Is there any way to prevent a block from executing if a condition is not satisfied

Hi ,

Is there any way to prevent a block from executing in a resource if a condition is not satisfied .
I am facing This object does not have an attribute named when it fails to find the element in the list of variables.
I am trying to create the newrelic_one_dashboard with dynamic blocks but at some cases the page will not have certain attributes and is throwing error .So I want to make it in such a way that this block should execute only if a condition is met or an argument is present in the variables
A code in terraform something like below code

if(locals.page.value. widget_area ! = null ){
widget_area{
// This is a block

 }

}

Can you post a more detailed example of what you’re trying to achieve? Please use code blocks (clicking the <> button in the editor) to make it easier to read.

Hi,

You might want to try try (https://www.terraform.io/docs/language/functions/try.html) or filter a map or list when looping over them on a resource / block creation.
I have recently provided an example to filter a map that could be useful.
See https://discuss.hashicorp.com/t/conditionally-create-resources-when-a-for-each-loop-is-involved/20841/3

Cheers,

I have updated the question

I think in this case the best option is to use dynamic blocks for your dashboard widgets. To do this, you’ll want to construct a list of objects representing each widget, then use for_each inside a dynamic block to iterate over them.

Here’s an example of what I mean:

terraform {
  required_providers {
    newrelic = {
      source = "newrelic/newrelic"
    }
  }
}

locals {
  widget_areas = tolist([
    {
      title = "Transactions"
      row   = 1
      column = 1
      query = "FROM Transaction SELECT count(*) FACET name"
    }
  ])
}

resource "newrelic_one_dashboard" "db" {
  name = "Example"

  page {
    name = "Example"

    dynamic "widget_area" {
      for_each = local.widget_areas
      iterator = widget

      content {
        title  = widget.value.title
        row    = widget.value.row
        column = widget.value.column

        nrql_query {
          query = widget.value.query
        }
      }
    }
  }
}
1 Like