Skip to content

Commit 1232eaa

Browse files
sreyaThomasK33
authored andcommitted
cache id
1 parent 9d60f47 commit 1232eaa

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

provisioner/terraform/resources.go

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,9 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
208208
// The label is what "terraform graph" uses to reference nodes.
209209
tfResourcesByLabel := map[string]map[string]*tfjson.StateResource{}
210210

211+
// Map resource IDs to labels for efficient lookup when processing metadata
212+
labelByResourceID := map[string]string{}
213+
211214
// Extra array to preserve the order of rich parameters.
212215
tfResourcesRichParameters := make([]*tfjson.StateResource, 0)
213216
tfResourcesPresets := make([]*tfjson.StateResource, 0)
@@ -233,6 +236,13 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
233236
tfResourcesByLabel[label] = map[string]*tfjson.StateResource{}
234237
}
235238
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+
}
236246
}
237247
}
238248
for _, module := range modules {
@@ -690,27 +700,11 @@ func ConvertState(ctx context.Context, modules []*tfjson.StateModule, rawGraph s
690700
// First, check if ResourceID is provided and try to find the resource by ID
691701
if attrs.ResourceID != "" {
692702
// 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
714708
logger.Warn(ctx, "coder_metadata resource_id not found, falling back to graph traversal",
715709
slog.F("resource_id", attrs.ResourceID),
716710
slog.F("metadata_address", resource.Address))

0 commit comments

Comments
 (0)