This repository has been archived by the owner on Dec 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
resource_telefonicaopencloud_as_policy_v1.go
365 lines (334 loc) · 11.8 KB
/
resource_telefonicaopencloud_as_policy_v1.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package telefonicaopencloud
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/hashicorp/terraform/helper/schema"
"github.com/huaweicloud/golangsdk/openstack/autoscaling/v1/policies"
)
func resourceASPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceASPolicyCreate,
Read: resourceASPolicyRead,
Update: resourceASPolicyUpdate,
Delete: resourceASPolicyDelete,
Schema: map[string]*schema.Schema{
"region": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"scaling_policy_name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: resourceASPolicyValidateName,
ForceNew: false,
},
"scaling_group_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"scaling_policy_type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: false,
ValidateFunc: resourceASPolicyValidatePolicyType,
},
"alarm_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"scheduled_policy": &schema.Schema{
Type: schema.TypeList,
Optional: true,
ForceNew: false,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"launch_time": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: false,
},
"recurrence_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
ValidateFunc: resourceASPolicyValidateRecurrenceType,
},
"recurrence_value": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"start_time": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
Default: getCurrentUTCwithoutSec(),
DiffSuppressFunc: suppressDiffAll,
},
"end_time": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
},
},
},
"scaling_policy_action": &schema.Schema{
Optional: true,
Type: schema.TypeList,
MaxItems: 1,
ForceNew: false,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"operation": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: resourceASPolicyValidateActionOperation,
},
"instance_number": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Default: 1,
},
},
},
},
"cool_down_time": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
Default: 900,
},
},
}
}
func getCurrentUTCwithoutSec() string {
utcTime := time.Now().UTC().Format(time.RFC3339)
splits := strings.SplitN(utcTime, ":", 3)
resultTime := strings.Join(splits[0:2], ":") + "Z"
return resultTime
}
func validateParameters(d *schema.ResourceData) error {
log.Printf("[DEBUG] validateParameters for as policy!")
policyType := d.Get("scaling_policy_type").(string)
alarmId := d.Get("alarm_id").(string)
log.Printf("[DEBUG] validateParameters alarmId is :%s", alarmId)
log.Printf("[DEBUG] validateParameters policyType is :%s", policyType)
scheduledPolicy := d.Get("scheduled_policy").([]interface{})
log.Printf("[DEBUG] validateParameters scheduledPolicy is :%#v", scheduledPolicy)
if policyType == "ALARM" {
if alarmId == "" {
return fmt.Errorf("Parameter alarm_id should be set if policy type is ALARM.")
}
}
if policyType == "SCHEDULED" || policyType == "RECURRENCE" {
if len(scheduledPolicy) == 0 {
return fmt.Errorf("Parameter scheduled_policy should be set if policy type is RECURRENCE or SCHEDULED.")
}
}
if len(scheduledPolicy) == 1 {
scheduledPolicyMap := scheduledPolicy[0].(map[string]interface{})
log.Printf("[DEBUG] validateParameters scheduledPolicyMap is :%#v", scheduledPolicyMap)
recurrenceType := scheduledPolicyMap["recurrence_type"].(string)
endTime := scheduledPolicyMap["end_time"].(string)
log.Printf("[DEBUG] validateParameters recurrenceType is :%#v", recurrenceType)
if policyType == "RECURRENCE" {
if recurrenceType == "" {
return fmt.Errorf("Parameter recurrence_type should be set if policy type is RECURRENCE.")
}
if endTime == "" {
return fmt.Errorf("Parameter end_time should be set if policy type is RECURRENCE.")
}
}
}
return nil
}
func getScheduledPolicy(rawScheduledPolicy map[string]interface{}) policies.SchedulePolicyOpts {
scheduledPolicy := policies.SchedulePolicyOpts{
LaunchTime: rawScheduledPolicy["launch_time"].(string),
RecurrenceType: rawScheduledPolicy["recurrence_type"].(string),
RecurrenceValue: rawScheduledPolicy["recurrence_value"].(string),
StartTime: rawScheduledPolicy["start_time"].(string),
EndTime: rawScheduledPolicy["end_time"].(string),
}
return scheduledPolicy
}
func getPolicyAction(rawPolicyAction map[string]interface{}) policies.ActionOpts {
policyAction := policies.ActionOpts{
Operation: rawPolicyAction["operation"].(string),
InstanceNum: rawPolicyAction["instance_number"].(int),
}
return policyAction
}
func resourceASPolicyCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
asClient, err := config.autoscalingV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating TelefonicaOpenCloud autoscaling client: %s", err)
}
log.Printf("[DEBUG] asClient: %#v", asClient)
err = validateParameters(d)
if err != nil {
return fmt.Errorf("Error creating ASPolicy: %s", err)
}
createOpts := policies.CreateOpts{
Name: d.Get("scaling_policy_name").(string),
ID: d.Get("scaling_group_id").(string),
Type: d.Get("scaling_policy_type").(string),
AlarmID: d.Get("alarm_id").(string),
CoolDownTime: d.Get("cool_down_time").(int),
}
scheduledPolicyList := d.Get("scheduled_policy").([]interface{})
if len(scheduledPolicyList) == 1 {
scheduledPolicyMap := scheduledPolicyList[0].(map[string]interface{})
scheduledPolicy := getScheduledPolicy(scheduledPolicyMap)
createOpts.SchedulePolicy = scheduledPolicy
}
policyActionList := d.Get("scaling_policy_action").([]interface{})
if len(policyActionList) == 1 {
policyActionMap := policyActionList[0].(map[string]interface{})
policyAction := getPolicyAction(policyActionMap)
createOpts.Action = policyAction
}
log.Printf("[DEBUG] Create AS policy Options: %#v", createOpts)
asPolicyId, err := policies.Create(asClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating ASPolicy: %s", err)
}
d.SetId(asPolicyId)
log.Printf("[DEBUG] Create AS Policy %q Success!", asPolicyId)
return resourceASPolicyRead(d, meta)
}
func resourceASPolicyRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
asClient, err := config.autoscalingV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating TelefonicaOpenCloud autoscaling client: %s", err)
}
asPolicy, err := policies.Get(asClient, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "AS Policy")
}
log.Printf("[DEBUG] Retrieved ASPolicy %q: %+v", d.Id(), asPolicy)
d.Set("scaling_policy_name", asPolicy.Name)
d.Set("scaling_policy_type", asPolicy.Type)
d.Set("alarm_id", asPolicy.AlarmID)
d.Set("cool_down_time", asPolicy.CoolDownTime)
policyActionInfo := asPolicy.Action
policyAction := map[string]interface{}{}
policyAction["operation"] = policyActionInfo.Operation
policyAction["instance_number"] = policyActionInfo.InstanceNum
policyActionList := []map[string]interface{}{}
policyActionList = append(policyActionList, policyAction)
d.Set("scaling_policy_action", policyActionList)
scheduledPolicyInfo := asPolicy.SchedulePolicy
scheduledPolicy := map[string]interface{}{}
scheduledPolicy["launch_time"] = scheduledPolicyInfo.LaunchTime
scheduledPolicy["recurrence_type"] = scheduledPolicyInfo.RecurrenceType
scheduledPolicy["recurrence_value"] = scheduledPolicyInfo.RecurrenceValue
scheduledPolicy["start_time"] = scheduledPolicyInfo.StartTime
scheduledPolicy["end_time"] = scheduledPolicyInfo.EndTime
scheduledPolicies := []map[string]interface{}{}
scheduledPolicies = append(scheduledPolicies, scheduledPolicy)
d.Set("scheduled_policy", scheduledPolicies)
d.Set("region", GetRegion(d, config))
return nil
}
func resourceASPolicyUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
asClient, err := config.autoscalingV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating TelefonicaOpenCloud autoscaling client: %s", err)
}
err = validateParameters(d)
if err != nil {
return fmt.Errorf("Error updating ASPolicy: %s", err)
}
updateOpts := policies.UpdateOpts{
Name: d.Get("scaling_policy_name").(string),
Type: d.Get("scaling_policy_type").(string),
AlarmID: d.Get("alarm_id").(string),
CoolDownTime: d.Get("cool_down_time").(int),
}
scheduledPolicyList := d.Get("scheduled_policy").([]interface{})
if len(scheduledPolicyList) == 1 {
scheduledPolicyMap := scheduledPolicyList[0].(map[string]interface{})
scheduledPolicy := getScheduledPolicy(scheduledPolicyMap)
updateOpts.SchedulePolicy = scheduledPolicy
}
policyActionList := d.Get("scaling_policy_action").([]interface{})
if len(policyActionList) == 1 {
policyActionMap := policyActionList[0].(map[string]interface{})
policyAction := getPolicyAction(policyActionMap)
updateOpts.Action = policyAction
}
log.Printf("[DEBUG] Update AS policy Options: %#v", updateOpts)
asPolicyID, err := policies.Update(asClient, d.Id(), updateOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating ASPolicy %q: %s", asPolicyID, err)
}
return resourceASPolicyRead(d, meta)
}
func resourceASPolicyDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
asClient, err := config.autoscalingV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating TelefonicaOpenCloud autoscaling client: %s", err)
}
log.Printf("[DEBUG] Begin to delete AS policy %q", d.Id())
if delErr := policies.Delete(asClient, d.Id()).ExtractErr(); delErr != nil {
return fmt.Errorf("Error deleting AS policy: %s", delErr)
}
return nil
}
var RecurrenceTypes = [3]string{"Daily", "Weekly", "Monthly"}
func resourceASPolicyValidateRecurrenceType(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
for i := range RecurrenceTypes {
if value == RecurrenceTypes[i] {
return
}
}
errors = append(errors, fmt.Errorf("%q must be one of %v", k, RecurrenceTypes))
return
}
var PolicyActions = [3]string{"ADD", "REMOVE", "SET"}
func resourceASPolicyValidateActionOperation(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
for i := range PolicyActions {
if value == PolicyActions[i] {
return
}
}
errors = append(errors, fmt.Errorf("%q must be one of %v", k, PolicyActions))
return
}
var PolicyTypes = [3]string{"ALARM", "SCHEDULED", "RECURRENCE"}
func resourceASPolicyValidatePolicyType(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
for i := range PolicyTypes {
if value == PolicyTypes[i] {
return
}
}
errors = append(errors, fmt.Errorf("%q must be one of %v", k, PolicyTypes))
return
}
func resourceASPolicyValidateName(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if len(value) > 64 || len(value) < 1 {
errors = append(errors, fmt.Errorf("%q must contain more than 1 and less than 64 characters", value))
}
if !regexp.MustCompile(`^[0-9a-zA-Z-_]+$`).MatchString(value) {
errors = append(errors, fmt.Errorf("only alphanumeric characters, hyphens, and underscores allowed in %q", value))
}
return
}