-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_cf_service_key.go
245 lines (216 loc) · 6.86 KB
/
resource_cf_service_key.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
package cloudfoundry
import (
"context"
"encoding/json"
"fmt"
"log"
"time"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
"code.cloudfoundry.org/cli/resources"
"code.cloudfoundry.org/cli/types"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/terraform-providers/terraform-provider-cloudfoundry/cloudfoundry/common"
"github.com/terraform-providers/terraform-provider-cloudfoundry/cloudfoundry/managers"
)
func resourceServiceKey() *schema.Resource {
return &schema.Resource{
CreateContext: resourceServiceKeyCreate,
ReadContext: resourceServiceKeyRead,
DeleteContext: resourceServiceKeyDelete,
Importer: &schema.ResourceImporter{
StateContext: ImportReadContext(resourceServiceKeyRead),
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"service_instance": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"params": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
Sensitive: true,
ConflictsWith: []string{"params_json"},
},
"params_json": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Sensitive: true,
ConflictsWith: []string{"params"},
ValidateFunc: validation.StringIsJSON,
},
"credentials": &schema.Schema{
Type: schema.TypeMap,
Computed: true,
Sensitive: true,
},
},
}
}
func resourceServiceKeyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
session := meta.(*managers.Session)
name := d.Get("name").(string)
serviceInstance := d.Get("service_instance").(string)
params := d.Get("params").(map[string]interface{})
paramJson := d.Get("params_json").(string)
if len(params) == 0 && paramJson != "" {
err := json.Unmarshal([]byte(paramJson), ¶ms)
if err != nil {
return diag.FromErr(err)
}
}
binding := resources.ServiceCredentialBinding{
ServiceInstanceGUID: serviceInstance,
Name: name,
Parameters: types.NewOptionalObject(params),
Type: resources.ServiceCredentialBindingType("key"),
}
jobURL, _, err := session.ClientV3.CreateServiceCredentialBinding(binding)
if err != nil {
return diag.FromErr(err)
}
var serviceKey resources.ServiceCredentialBinding
// Poll the state of the async job
err = common.PollingWithTimeout(func() (bool, error) {
job, _, err := session.ClientV3.GetJob(jobURL)
if err != nil {
return true, err
}
// Stop polling and return error if job failed
if job.State == constant.JobFailed {
return true, fmt.Errorf(
"ServiceKey creation failed for key %s, reason: %+v",
serviceInstance,
job.Errors(),
)
}
// Check binding state if job completed
if job.State == constant.JobComplete {
createdKeys, _, err := session.ClientV3.GetServiceCredentialBindings(
ccv3.Query{
Key: ccv3.QueryKey("service_instance_guids"),
Values: []string{binding.ServiceInstanceGUID},
}, ccv3.Query{
Key: ccv3.NameFilter,
Values: []string{name},
},
)
if err != nil {
return true, err
}
if len(createdKeys) == 0 {
return false, nil
}
if createdKeys[0].LastOperation.State == resources.OperationSucceeded {
serviceKey = createdKeys[0]
return true, nil
}
if createdKeys[0].LastOperation.State == resources.OperationFailed {
return true, fmt.Errorf(
"Service key creation failed for key %s, reason: %+v",
serviceInstance,
job.Errors(),
)
}
}
// Last operation initial or inprogress or job not completed, continue polling
return false, nil
}, 5*time.Second, 60*time.Second)
if err != nil {
return diag.FromErr(err)
}
credentials, _, err := session.ClientV3.GetServiceCredentialBindingDetails(serviceKey.GUID)
if err != nil {
return diag.FromErr(err)
}
d.Set("credentials", normalizeMap(credentials.Credentials, make(map[string]interface{}), "", "_"))
d.SetId(serviceKey.GUID)
return nil
}
func resourceServiceKeyRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
session := meta.(*managers.Session)
var serviceKeys []resources.ServiceCredentialBinding
var err error
if d.Id() != "" {
serviceKeys, _, err = session.ClientV3.GetServiceCredentialBindings(
ccv3.Query{
Key: ccv3.GUIDFilter,
Values: []string{d.Id()},
},
)
} else {
serviceKeys, _, err = session.ClientV3.GetServiceCredentialBindings(
ccv3.Query{
Key: ccv3.QueryKey("service_instance_guids"),
Values: []string{d.Get("service_instance").(string)},
}, ccv3.Query{
Key: ccv3.NameFilter,
Values: []string{d.Get("name").(string)},
},
)
}
if err != nil {
return diag.FromErr(err)
}
if len(serviceKeys) == 0 {
d.SetId("")
return nil
}
if len(serviceKeys) != 1 {
return diag.FromErr(fmt.Errorf("Some thing went wrong"))
}
d.Set("name", serviceKeys[0].Name)
d.Set("service_instance", serviceKeys[0].ServiceInstanceGUID)
d.SetId(serviceKeys[0].GUID)
serviceKeyDetails, _, err := session.ClientV3.GetServiceCredentialBindingDetails(d.Id())
if err != nil {
return diag.FromErr(err)
}
d.Set("credentials", normalizeMap(serviceKeyDetails.Credentials, make(map[string]interface{}), "", "_"))
return nil
}
func resourceServiceKeyDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
// Note : When deleting credential bindings originated from user provided service instances,
// the delete operation does not require interactions with service brokers,
// therefore the API will respond synchronously to the delete request.
session := meta.(*managers.Session)
jobURL, _, err := session.ClientV3.DeleteServiceCredentialBinding(d.Id())
if err != nil {
return diag.FromErr(err)
}
if jobURL == "" {
log.Printf("[INFO] Deleted service credential binding %s for User-Provided service instance, finishing without polling", d.Id())
return diag.FromErr(err)
}
// Polling when deleting service credential binding for a managed service instance
err = common.PollingWithTimeout(func() (bool, error) {
job, _, err := session.ClientV3.GetJob(jobURL)
if err != nil {
return true, err
}
// Stop polling and return error if job failed
if job.State == constant.JobFailed {
return true, fmt.Errorf(
"Service key deletion failed, reason: %+v",
job.Errors(),
)
}
// Check binding state if job completed
if job.State == constant.JobComplete {
return true, nil
}
// Last operation initial or inprogress or job not completed, continue polling
return false, nil
}, 5*time.Second, 60*time.Second)
return diag.FromErr(err)
}