hashicorp / terraform

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.
https://www.terraform.io/
Other
42.71k stars 9.55k forks source link

import block bug #35968

Closed andreibodi22 closed 18 hours ago

andreibodi22 commented 1 day ago

Terraform Version

terraform -v
Terraform v1.9.8
on darwin_arm64
+ provider registry.terraform.io/ibm-cloud/ibm v1.71.0
+ provider registry.terraform.io/sysdiglabs/sysdig v1.38.0

Terraform Configuration Files

locals{
  alerts = {
    "197178" = "ibm_usage_tier_changed"
    "197372" = "kubernetes_failed_to_pull_image"
    "197389" = "kubernetes_liveness_probe_failed"
    "197392" = "kubernetes_readiness_probe_failed"
    "242679" = "epa__readiness_probe_failed"
    "242683" = "epa__liveness_probe_failed_container_restarted"
    "242686" = "epa__failed_to_pull_image"
    "536236" = "epa__pc_pods_readiness_probe_failed"
  }
}

import {
  for_each = local.alerts
  to = sysdig_monitor_alert_v2_event.this[each.value]
  id = each.key
}

Debug Output

terraform plan -generate-config-out=prometheus_alerts.tf
╷
│ Error: Cannot generate configuration
│
│   on main.tf line 16, in import:
│   16:   to = sysdig_monitor_alert_v2_event.this[each.value]
│
│ The given import block is not compatible with config generation. The -generate-config-out option cannot be used with import blocks
│ which use for_each, or resources which use for_each or count.

Expected Behavior

I wanted to ask if this is a bug in my Terraform version or if it’s really not possible to do this. I wouldn’t want to just import them and then copy the configuration from the state file; I’d like to use the import block.

Actual Behavior

I can't import multiple resources at once with for_each and use terraform terraformplan -generate-config-out=prometheus_alerts.tf.

Steps to Reproduce

terraform init terraform plan -generate-config-out=prometheus_alerts.tf

Additional Context

No response

References

No response

liamcervante commented 18 hours ago

Hi @andreibodi22, generating configuration from an import block with a for_each is unfortunately not currently supported. Including the for_each increases the complexity of the config generation a great deal, as Terraform must work out a data structure to share the referenced data for each instance of the target resource.

However, you can still use the import block alongside a for_each if you wrote the resource block yourself, or split the alerts into separate import blocks.