'Terraform for_each issue with data type
i have the next code to attach snapshot policy to existing disks for particular instance:
data "alicloud_ecs_disks" "db_disks" {
instance_id = alicloud_instance.db.id
}
resource "alicloud_ecs_auto_snapshot_policy" "common" {
...
}
resource "alicloud_ecs_auto_snapshot_policy_attachment" "db" {
for_each = { for disk in data.alicloud_ecs_disks.db_disks.disks : disk.disk_id => disk }
auto_snapshot_policy_id = alicloud_ecs_auto_snapshot_policy.common.id
disk_id = each.key
}
When i run plan it works well, but after applying the next plan fails with error:
data.alicloud_ecs_disks.db_disks.disks is a list of object, known only after apply
│
│ The "for_each" value depends on resource attributes that cannot be
│ determined until apply, so Terraform cannot predict how many instances will
│ be created. To work around this, use the -target argument to first apply
│ only the resources that the for_each depends on.
What the best option to workaround this? it works using plan on some machines and sometimes not. Thanks
Solution 1:[1]
The reason for your error is that your alicloud_ecs_disks.db_disks references alicloud_instance.db which is probably created in the same configuration. As the error msg says, you can't use dynamic data in for_each.
The solution is to use -target option first to deploy your alicloud_instance.db first, and then when it has been deployed you can proceed with the rest of your infrastructure.
If you don't want to split your deployment, then you have to re-architect your TF so that there is no dependency on any dynamic content.
Solution 2:[2]
The problem is that during first apply snapshot policy has been attached to the system disk. It forces the whole instance re-creation on next plan and instance.id is not know until apply.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin |
| Solution 2 | BigBoss |
