-
Notifications
You must be signed in to change notification settings - Fork 669
/
resource_ibm_is_security_group_target.go
371 lines (312 loc) · 11.7 KB
/
resource_ibm_is_security_group_target.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
366
367
368
369
370
371
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package vpc
import (
"fmt"
"log"
"strings"
"time"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/conns"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/flex"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
"github.com/IBM/vpc-go-sdk/vpcv1"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
isSecurityGroupTargetID = "target"
isSecurityGroupResourceType = "resource_type"
)
func ResourceIBMISSecurityGroupTarget() *schema.Resource {
return &schema.Resource{
Create: resourceIBMISSecurityGroupTargetCreate,
Read: resourceIBMISSecurityGroupTargetRead,
Delete: resourceIBMISSecurityGroupTargetDelete,
Exists: resourceIBMISSecurityGroupTargetExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"security_group": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Security group id",
},
isSecurityGroupTargetID: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "security group target identifier",
ValidateFunc: validate.InvokeValidator("ibm_is_security_group_target", isSecurityGroupTargetID),
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: "Security group target name",
},
"crn": {
Type: schema.TypeString,
Computed: true,
Description: "The CRN for this Security group target",
},
isSecurityGroupResourceType: {
Type: schema.TypeString,
Computed: true,
Description: "Resource Type",
},
},
}
}
func ResourceIBMISSecurityGroupTargetValidator() *validate.ResourceValidator {
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isSecurityGroupTargetID,
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Required: true,
Regexp: `^[-0-9a-z_]+$`,
MinValueLength: 1,
MaxValueLength: 64},
validate.ValidateSchema{
Identifier: "security_group",
ValidateFunctionIdentifier: validate.ValidateRegexpLen,
Type: validate.TypeString,
Required: true,
Regexp: `^[-0-9a-z_]+$`,
MinValueLength: 1,
MaxValueLength: 64})
ibmISSecurityGroupResourceValidator := validate.ResourceValidator{ResourceName: "ibm_is_security_group_target", Schema: validateSchema}
return &ibmISSecurityGroupResourceValidator
}
func resourceIBMISSecurityGroupTargetCreate(d *schema.ResourceData, meta interface{}) error {
sess, err := vpcClient(meta)
if err != nil {
return err
}
securityGroupID := d.Get("security_group").(string)
targetID := d.Get(isSecurityGroupTargetID).(string)
createSecurityGroupTargetBindingOptions := &vpcv1.CreateSecurityGroupTargetBindingOptions{}
createSecurityGroupTargetBindingOptions.SecurityGroupID = &securityGroupID
createSecurityGroupTargetBindingOptions.ID = &targetID
sg, response, err := sess.CreateSecurityGroupTargetBinding(createSecurityGroupTargetBindingOptions)
if err != nil || sg == nil {
return fmt.Errorf("[ERROR] Error while creating Security Group Target Binding %s\n%s", err, response)
}
sgtarget := sg.(*vpcv1.SecurityGroupTargetReference)
d.SetId(fmt.Sprintf("%s/%s", securityGroupID, *sgtarget.ID))
crn := sgtarget.CRN
if crn != nil && *crn != "" && strings.Contains(*crn, "load-balancer") {
lbid := sgtarget.ID
_, errsgt := isWaitForLbSgTargetCreateAvailable(sess, *lbid, d.Timeout(schema.TimeoutCreate))
if errsgt != nil {
return errsgt
}
} else if crn != nil && *crn != "" && strings.Contains(*crn, "virtual_network_interfaces") {
vpcClient, err := meta.(conns.ClientSession).VpcV1API()
if err != nil {
return err
}
vniId := sgtarget.ID
_, errsgt := isWaitForVNISgTargetCreateAvailable(vpcClient, *vniId, d.Timeout(schema.TimeoutCreate))
if errsgt != nil {
return errsgt
}
}
return resourceIBMISSecurityGroupTargetRead(d, meta)
}
func resourceIBMISSecurityGroupTargetRead(d *schema.ResourceData, meta interface{}) error {
sess, err := vpcClient(meta)
if err != nil {
return err
}
parts, err := flex.IdParts(d.Id())
if err != nil {
return err
}
securityGroupID := parts[0]
securityGroupTargetID := parts[1]
d.Set("security_group", securityGroupID)
d.Set(isSecurityGroupTargetID, securityGroupTargetID)
getSecurityGroupTargetOptions := &vpcv1.GetSecurityGroupTargetOptions{
SecurityGroupID: &securityGroupID,
ID: &securityGroupTargetID,
}
data, response, err := sess.GetSecurityGroupTarget(getSecurityGroupTargetOptions)
if err != nil || data == nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[ERROR] Error getting Security Group Target : %s\n%s", err, response)
}
target := data.(*vpcv1.SecurityGroupTargetReference)
d.Set("name", *target.Name)
d.Set("crn", target.CRN)
if target.ResourceType != nil && *target.ResourceType != "" {
d.Set(isSecurityGroupResourceType, *target.ResourceType)
}
return nil
}
func resourceIBMISSecurityGroupTargetDelete(d *schema.ResourceData, meta interface{}) error {
sess, err := vpcClient(meta)
if err != nil {
return err
}
parts, err := flex.IdParts(d.Id())
if err != nil {
return err
}
securityGroupID := parts[0]
securityGroupTargetID := parts[1]
getSecurityGroupTargetOptions := &vpcv1.GetSecurityGroupTargetOptions{
SecurityGroupID: &securityGroupID,
ID: &securityGroupTargetID,
}
sgt, response, err := sess.GetSecurityGroupTarget(getSecurityGroupTargetOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[ERROR] Error Getting Security Group Targets (%s): %s\n%s", securityGroupID, err, response)
}
deleteSecurityGroupTargetBindingOptions := sess.NewDeleteSecurityGroupTargetBindingOptions(securityGroupID, securityGroupTargetID)
response, err = sess.DeleteSecurityGroupTargetBinding(deleteSecurityGroupTargetBindingOptions)
if err != nil {
return fmt.Errorf("[ERROR] Error Deleting Security Group Targets : %s\n%s", err, response)
}
securityGroupTargetReference := sgt.(*vpcv1.SecurityGroupTargetReference)
crn := securityGroupTargetReference.CRN
if crn != nil && *crn != "" && strings.Contains(*crn, "load-balancer") {
lbid := securityGroupTargetReference.ID
_, errsgt := isWaitForLBRemoveAvailable(sess, sgt, *lbid, securityGroupID, securityGroupTargetID, d.Timeout(schema.TimeoutDelete))
if errsgt != nil {
return errsgt
}
}
d.SetId("")
return nil
}
func resourceIBMISSecurityGroupTargetExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess, err := vpcClient(meta)
if err != nil {
return false, err
}
parts, err := flex.IdParts(d.Id())
if err != nil {
return false, err
}
securityGroupID := parts[0]
securityGroupTargetID := parts[1]
getSecurityGroupTargetOptions := &vpcv1.GetSecurityGroupTargetOptions{
SecurityGroupID: &securityGroupID,
ID: &securityGroupTargetID,
}
_, response, err := sess.GetSecurityGroupTarget(getSecurityGroupTargetOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return false, nil
}
return false, fmt.Errorf("[ERROR] Error getting Security Group Target : %s\n%s", err, response)
}
return true, nil
}
func isWaitForLBRemoveAvailable(sess *vpcv1.VpcV1, sgt vpcv1.SecurityGroupTargetReferenceIntf, lbId, securityGroupID, securityGroupTargetID string, timeout time.Duration) (interface{}, error) {
log.Printf("[INFO] Waiting for load balancer binding (%s) to be removed.", lbId)
stateConf := &resource.StateChangeConf{
Pending: []string{isLBProvisioning},
Target: []string{isLBProvisioningDone},
Refresh: isLBRemoveRefreshFunc(sess, sgt, lbId, securityGroupID, securityGroupTargetID),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
NotFoundChecks: 1,
}
return stateConf.WaitForState()
}
func isLBRemoveRefreshFunc(sess *vpcv1.VpcV1, sgt vpcv1.SecurityGroupTargetReferenceIntf, lbId, securityGroupID, securityGroupTargetID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
getSecurityGroupTargetOptions := &vpcv1.GetSecurityGroupTargetOptions{
SecurityGroupID: &securityGroupID,
ID: &securityGroupTargetID,
}
_, response, err := sess.GetSecurityGroupTarget(getSecurityGroupTargetOptions)
if err != nil {
if response != nil && response.StatusCode == 404 {
getlboptions := &vpcv1.GetLoadBalancerOptions{
ID: &lbId,
}
lb, response, err := sess.GetLoadBalancer(getlboptions)
if err != nil {
return nil, "", fmt.Errorf("[ERROR] Error Getting Load Balancer : %s\n%s", err, response)
}
if *lb.ProvisioningStatus == "active" || *lb.ProvisioningStatus == "failed" {
return sgt, isLBProvisioningDone, nil
} else {
return sgt, isLBProvisioning, nil
}
}
return nil, isLBProvisioningDone, fmt.Errorf("[ERROR] Error getting Security Group Target : %s\n%s", err, response)
}
return sgt, isLBProvisioning, nil
}
}
func isWaitForLbSgTargetCreateAvailable(sess *vpcv1.VpcV1, lbId string, timeout time.Duration) (interface{}, error) {
log.Printf("Waiting for load balancer (%s) to be available.", lbId)
stateConf := &resource.StateChangeConf{
Pending: []string{"retry", isLBProvisioning, "update_pending"},
Target: []string{isLBProvisioningDone, ""},
Refresh: isLBSgTargetRefreshFunc(sess, lbId),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
return stateConf.WaitForState()
}
func isLBSgTargetRefreshFunc(sess *vpcv1.VpcV1, lbId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
getlboptions := &vpcv1.GetLoadBalancerOptions{
ID: &lbId,
}
lb, response, err := sess.GetLoadBalancer(getlboptions)
if err != nil {
return nil, "", fmt.Errorf("[ERROR] Error Getting Load Balancer : %s\n%s", err, response)
}
if *lb.ProvisioningStatus == "active" || *lb.ProvisioningStatus == "failed" {
return lb, isLBProvisioningDone, nil
}
return lb, isLBProvisioning, nil
}
}
func isWaitForVNISgTargetCreateAvailable(sess *vpcv1.VpcV1, vniId string, timeout time.Duration) (interface{}, error) {
log.Printf("Waiting for virtual network interface (%s) to be available.", vniId)
stateConf := &resource.StateChangeConf{
Pending: []string{"pending", "updating", "waiting"},
Target: []string{isLBProvisioningDone, ""},
Refresh: isVNISgTargetRefreshFunc(sess, vniId),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
return stateConf.WaitForState()
}
func isVNISgTargetRefreshFunc(vpcClient *vpcv1.VpcV1, vniId string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
getVNIOptions := &vpcv1.GetVirtualNetworkInterfaceOptions{
ID: &vniId,
}
vni, response, err := vpcClient.GetVirtualNetworkInterface(getVNIOptions)
if err != nil {
return nil, "", fmt.Errorf("[ERROR] Error Getting Load Balancer : %s\n%s", err, response)
}
if *vni.LifecycleState == "failed" {
return vni, *vni.LifecycleState, fmt.Errorf("Network Interface creationg failed with status %s ", *vni.LifecycleState)
}
return vni, *vni.LifecycleState, nil
}
}