title: Terraform - don't create resource if data source does not exist
body: <p>I'm using the following set up to iterate through my locals. Certain parameters should only be filled in if terraform can grab the data resource. If the data resource DOES NOT EXIST, then it is noted in the parameter and then the resource creation is skipped.</p>
  <pre><code>#Only get the data resource if it exists#################################
  data &quot;aws_ssm_parameter&quot; &quot;example_parameter&quot; {
    count        = &quot;${var.does_ssm_parameter_exist == true ? 1 : 0}&quot;
    name         = &quot;ssm_parameter&quot;
  }
  
  #List of parameters for all config rules
  locals {   
    config_rule_params = {
        &quot;access_keys_rotated&quot; = {
            &quot;input_parameters&quot; = &quot;example&quot;
        },
        &quot;acm_certificate_expiration_check&quot; = {
            #ERROR! Get input parameters from data source if it exists#################################
            &quot;input_parameters&quot; = &quot;${var.does_ssm_parameter_exist == &quot;true&quot; ? &quot;${data.aws_ssm_parameter.example_parameter[count.index].value}&quot; : &quot;DOES_NOT_EXIST&quot;}&quot;
        }
    }
  
  #Only create config rule if input parameters exist
  resource &quot;aws_config_config_rule&quot; &quot;parameterised_config_rules&quot; {
    for_each = {
      for rule, params in local.config_rule_params : rule =&gt; params
      if params.input_parameters != &quot;DOES_NOT_EXIST&quot;
    }
    input_parameters            = each.value.input_parameters
  }
  </code></pre>
  <p>Unfortunately, it seems like I cannot use count.index in this way:</p>
  <pre><code>Error: Reference to &quot;count&quot; in non-counted context
  &quot;input_parameters&quot; = &quot;${var.does_ssm_parameter_exist == &quot;true&quot; ? &quot;${data.aws_ssm_parameter.example_parameter[count.index].value}&quot; : &quot;DOES_NOT_EXIST&quot;}&quot;
  The &quot;count&quot; object can be used only in &quot;resource&quot; and &quot;data&quot; blocks, and only when the &quot;count&quot; argument is set.
  </code></pre>