Skip to content

Commit 5964e92

Browse files
authored
states/statefile: consistently sort resources across modules (#25498)
If a statefile had resources with the same name in different modules, the sort order could be inconsistent between state refreshes. This adds the module to the Less() function used in sorting and a minimal test to verify consistent ordering.
1 parent 3cfe888 commit 5964e92

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

states/statefile/version4.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,8 @@ func (sr sortResourcesV4) Len() int { return len(sr) }
535535
func (sr sortResourcesV4) Swap(i, j int) { sr[i], sr[j] = sr[j], sr[i] }
536536
func (sr sortResourcesV4) Less(i, j int) bool {
537537
switch {
538+
case sr[i].Module != sr[j].Module:
539+
return sr[i].Module < sr[j].Module
538540
case sr[i].Mode != sr[j].Mode:
539541
return sr[i].Mode < sr[j].Mode
540542
case sr[i].Type != sr[j].Type:

states/statefile/version4_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package statefile
2+
3+
import (
4+
"sort"
5+
"testing"
6+
)
7+
8+
// This test verifies that modules are sorted before resources:
9+
// https://github.com/hashicorp/terraform/issues/21552
10+
func TestVersion4_sort(t *testing.T) {
11+
resources := sortResourcesV4{
12+
{
13+
Module: "module.child",
14+
Type: "test_instance",
15+
Name: "foo",
16+
},
17+
{
18+
Type: "test_instance",
19+
Name: "foo",
20+
},
21+
{
22+
Module: "module.kinder",
23+
Type: "test_instance",
24+
Name: "foo",
25+
},
26+
{
27+
Module: "module.child.grandchild",
28+
Type: "test_instance",
29+
Name: "foo",
30+
},
31+
}
32+
sort.Stable(resources)
33+
34+
moduleOrder := []string{"", "module.child", "module.child.grandchild", "module.kinder"}
35+
36+
for i, resource := range resources {
37+
if resource.Module != moduleOrder[i] {
38+
t.Errorf("wrong sort order: expected %q, got %q\n", moduleOrder[i], resource.Module)
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)