@@ -208,6 +208,9 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
208
208
// The label is what "terraform graph" uses to reference nodes.
209
209
tfResourcesByLabel := map [string ]map [string ]* tfjson.StateResource {}
210
210
211
+ // Map resource IDs to labels for efficient lookup when processing metadata
212
+ labelByResourceID := map [string ]string {}
213
+
211
214
// Extra array to preserve the order of rich parameters.
212
215
tfResourcesRichParameters := make ([]* tfjson.StateResource , 0 )
213
216
tfResourcesPresets := make ([]* tfjson.StateResource , 0 )
@@ -233,6 +236,13 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
233
236
tfResourcesByLabel [label ] = map [string ]* tfjson.StateResource {}
234
237
}
235
238
tfResourcesByLabel [label ][resource.Address ] = resource
239
+
240
+ // Build the ID to label map
241
+ if idAttr , hasID := resource .AttributeValues ["id" ]; hasID {
242
+ if idStr , ok := idAttr .(string ); ok && idStr != "" {
243
+ labelByResourceID [idStr ] = label
244
+ }
245
+ }
236
246
}
237
247
}
238
248
for _ , module := range modules {
@@ -690,27 +700,11 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
690
700
// First, check if ResourceID is provided and try to find the resource by ID
691
701
if attrs .ResourceID != "" {
692
702
// Look for a resource with matching ID
693
- foundByID := false
694
- for label , tfResources := range tfResourcesByLabel {
695
- for _ , tfResource := range tfResources {
696
- // Check if this resource's ID matches the ResourceID
697
- idAttr , hasID := tfResource .AttributeValues ["id" ]
698
- if hasID {
699
- idStr , ok := idAttr .(string )
700
- if ok && idStr == attrs .ResourceID {
701
- targetLabel = label
702
- foundByID = true
703
- break
704
- }
705
- }
706
- }
707
- if foundByID {
708
- break
709
- }
710
- }
711
-
712
- // If we couldn't find by ID, fall back to graph traversal
713
- if ! foundByID {
703
+ foundLabel , foundByID := labelByResourceID [attrs .ResourceID ]
704
+ if foundByID {
705
+ targetLabel = foundLabel
706
+ } else {
707
+ // If we couldn't find by ID, fall back to graph traversal
714
708
logger .Warn (ctx , "coder_metadata resource_id not found, falling back to graph traversal" ,
715
709
slog .F ("resource_id" , attrs .ResourceID ),
716
710
slog .F ("metadata_address" , resource .Address ))
0 commit comments