-
Notifications
You must be signed in to change notification settings - Fork 114
/
resource_integer.go
226 lines (194 loc) · 6.69 KB
/
resource_integer.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package provider
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/terraform-providers/terraform-provider-random/internal/planmodifiers"
"github.com/terraform-providers/terraform-provider-random/internal/random"
)
var _ provider.ResourceType = (*integerResourceType)(nil)
type integerResourceType struct{}
func (r *integerResourceType) GetSchema(context.Context) (tfsdk.Schema, diag.Diagnostics) {
return tfsdk.Schema{
Description: "The resource `random_integer` generates random values from a given range, described " +
"by the `min` and `max` attributes of a given resource.\n" +
"\n" +
"This resource can be used in conjunction with resources that have the `create_before_destroy` " +
"lifecycle flag set, to avoid conflicts with unique names during the brief period where both the " +
"old and new resources exist concurrently.",
Attributes: map[string]tfsdk.Attribute{
"keepers": {
Description: "Arbitrary map of values that, when changed, will trigger recreation of " +
"resource. See [the main provider documentation](../index.html) for more information.",
Type: types.MapType{
ElemType: types.StringType,
},
Optional: true,
PlanModifiers: []tfsdk.AttributePlanModifier{
planmodifiers.RequiresReplaceIfValuesNotNull(),
},
},
"min": {
Description: "The minimum inclusive value of the range.",
Type: types.Int64Type,
Required: true,
PlanModifiers: []tfsdk.AttributePlanModifier{resource.RequiresReplace()},
},
"max": {
Description: "The maximum inclusive value of the range.",
Type: types.Int64Type,
Required: true,
PlanModifiers: []tfsdk.AttributePlanModifier{resource.RequiresReplace()},
},
"seed": {
Description: "A custom seed to always produce the same value.",
Type: types.StringType,
Optional: true,
PlanModifiers: []tfsdk.AttributePlanModifier{resource.RequiresReplace()},
},
"result": {
Description: "The random integer result.",
Type: types.Int64Type,
Computed: true,
PlanModifiers: []tfsdk.AttributePlanModifier{
resource.UseStateForUnknown(),
},
},
"id": {
Description: "The string representation of the integer result.",
Type: types.StringType,
Computed: true,
PlanModifiers: []tfsdk.AttributePlanModifier{
resource.UseStateForUnknown(),
},
},
},
}, nil
}
func (r *integerResourceType) NewResource(_ context.Context, _ provider.Provider) (resource.Resource, diag.Diagnostics) {
return &integerResource{}, nil
}
var (
_ resource.Resource = (*integerResource)(nil)
_ resource.ResourceWithImportState = (*integerResource)(nil)
)
type integerResource struct{}
func (r *integerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan integerModelV0
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
max := int(plan.Max.Value)
min := int(plan.Min.Value)
seed := plan.Seed.Value
if max < min {
resp.Diagnostics.AddError(
"Create Random Integer Error",
"The minimum (min) value needs to be smaller than or equal to maximum (max) value.",
)
return
}
rand := random.NewRand(seed)
number := rand.Intn((max+1)-min) + min
u := &integerModelV0{
ID: types.String{Value: strconv.Itoa(number)},
Keepers: plan.Keepers,
Min: types.Int64{Value: int64(min)},
Max: types.Int64{Value: int64(max)},
Result: types.Int64{Value: int64(number)},
}
if seed != "" {
u.Seed.Value = seed
} else {
u.Seed.Null = true
}
diags = resp.State.Set(ctx, u)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
// Read does not need to perform any operations as the state in ReadResourceResponse is already populated.
func (r *integerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
}
// Update is intentionally left blank as all required and optional attributes force replacement of the resource
// through the RequiresReplace AttributePlanModifier.
func (r *integerResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var model integerModelV0
resp.Diagnostics.Append(req.Plan.Get(ctx, &model)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &model)...)
}
// Delete does not need to explicitly call resp.State.RemoveResource() as this is automatically handled by the
// [framework](https://github.com/hashicorp/terraform-plugin-framework/pull/301).
func (r *integerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
}
func (r *integerResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
parts := strings.Split(req.ID, ",")
if len(parts) != 3 && len(parts) != 4 {
resp.Diagnostics.AddError(
"Import Random Integer Error",
"Invalid import usage: expecting {result},{min},{max} or {result},{min},{max},{seed}",
)
return
}
result, err := strconv.ParseInt(parts[0], 10, 64)
if err != nil {
resp.Diagnostics.AddError(
"Import Random Integer Error",
"The value supplied could not be parsed as an integer.\n\n"+
fmt.Sprintf("Original Error: %s", err),
)
return
}
min, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
resp.Diagnostics.AddError(
"Import Random Integer Error",
"The min value supplied could not be parsed as an integer.\n\n"+
fmt.Sprintf("Original Error: %s", err),
)
return
}
max, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil {
resp.Diagnostics.AddError(
"Import Random Integer Error",
"The max value supplied could not be parsed as an integer.\n\n"+
fmt.Sprintf("Original Error: %s", err),
)
return
}
var state integerModelV0
state.ID.Value = parts[0]
state.Keepers.ElemType = types.StringType
state.Result.Value = result
state.Min.Value = min
state.Max.Value = max
if len(parts) == 4 {
state.Seed.Value = parts[3]
}
diags := resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
}
type integerModelV0 struct {
ID types.String `tfsdk:"id"`
Keepers types.Map `tfsdk:"keepers"`
Min types.Int64 `tfsdk:"min"`
Max types.Int64 `tfsdk:"max"`
Seed types.String `tfsdk:"seed"`
Result types.Int64 `tfsdk:"result"`
}