forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_shuffle.go
82 lines (67 loc) · 1.42 KB
/
resource_shuffle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package random
import (
"github.com/hashicorp/terraform/helper/schema"
)
func resourceShuffle() *schema.Resource {
return &schema.Resource{
Create: CreateShuffle,
Read: schema.Noop,
Delete: schema.RemoveFromState,
Schema: map[string]*schema.Schema{
"keepers": {
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"seed": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"input": {
Type: schema.TypeList,
Required: true,
ForceNew: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"result": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"result_count": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
},
},
}
}
func CreateShuffle(d *schema.ResourceData, _ interface{}) error {
input := d.Get("input").([]interface{})
seed := d.Get("seed").(string)
resultCount := d.Get("result_count").(int)
if resultCount == 0 {
resultCount = len(input)
}
result := make([]interface{}, 0, resultCount)
rand := NewRand(seed)
// Keep producing permutations until we fill our result
Batches:
for {
perm := rand.Perm(len(input))
for _, i := range perm {
result = append(result, input[i])
if len(result) >= resultCount {
break Batches
}
}
}
d.SetId("-")
d.Set("result", result)
return nil
}