forked from ovh/terraform-provider-ovh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_cloud_project_user.go
338 lines (284 loc) · 9 KB
/
resource_cloud_project_user.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
package ovh
import (
"context"
"fmt"
"log"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/ovh/terraform-provider-ovh/ovh/helpers"
"github.com/ovh/go-ovh/ovh"
)
func resourceCloudProjectUser() *schema.Resource {
return &schema.Resource{
Create: resourceCloudProjectUserCreate,
Read: resourceCloudProjectUserRead,
Delete: resourceCloudProjectUserDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceCloudProjectUserImportState,
},
Schema: map[string]*schema.Schema{
"service_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DefaultFunc: schema.EnvDefaultFunc("OVH_CLOUD_PROJECT_SERVICE", nil),
Description: "Service name of the resource representing the id of the cloud project.",
},
"description": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"role_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateCloudProjectUserRoleFunc,
},
"role_names": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
// Computed
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"openstack_rc": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
},
"password": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"roles": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Computed: true,
},
"id": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"permissions": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"username": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceCloudProjectUserImportState(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
userId := d.Id()
// Fallback to the environment variable if service_name not given
serviceName := os.Getenv("OVH_CLOUD_PROJECT_SERVICE")
splitId := strings.SplitN(userId, "/", 2)
if len(splitId) == 2 {
serviceName = splitId[0]
userId = splitId[1]
}
if serviceName == "" || userId == "" {
return nil, fmt.Errorf("Import Id is not service_name/id formatted")
}
d.SetId(userId)
d.Set("service_name", serviceName)
return []*schema.ResourceData{d}, nil
}
func validateCloudProjectUserRoleFunc(v interface{}, k string) (ws []string, errors []error) {
err := helpers.ValidateStringEnum(v.(string), []string{
"administrator",
"ai_training_operator",
"authentication",
"backup_operator",
"compute_operator",
"image_operator",
"infrastructure_supervisor",
"network_operator",
"network_security_operator",
"objectstore_operator",
"volume_operator",
})
if err != nil {
errors = append(errors, err)
}
return
}
func resourceCloudProjectUserCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
serviceName := d.Get("service_name").(string)
params := (&CloudProjectUserCreateOpts{}).FromResource(d)
for _, role := range params.Roles {
if _, errs := validateCloudProjectUserRoleFunc(role, ""); errs != nil {
return fmt.Errorf("roles contains unsupported value: %s.", role)
}
}
r := &CloudProjectUser{}
log.Printf("[DEBUG] Will create public cloud user: %s", params)
endpoint := fmt.Sprintf(
"/cloud/project/%s/user",
url.PathEscape(serviceName),
)
if err := config.OVHClient.Post(endpoint, params, r); err != nil {
return fmt.Errorf("calling Post %s with params %s:\n\t %q", endpoint, params, err)
}
// Set Password only at creation time
d.Set("password", r.Password)
d.SetId(strconv.Itoa(r.Id))
log.Printf("[DEBUG] Waiting for User %s:", r)
stateConf := &resource.StateChangeConf{
Pending: []string{"creating"},
Target: []string{"ok"},
Refresh: waitForCloudProjectUser(config.OVHClient, serviceName, d.Id()),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("waiting for user (%s): %s", params, err)
}
log.Printf("[DEBUG] Created User %s", r)
return resourceCloudProjectUserRead(d, meta)
}
func resourceCloudProjectUserRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
serviceName := d.Get("service_name").(string)
user := &CloudProjectUser{}
log.Printf("[DEBUG] Will read public cloud user %s from project: %s", d.Id(), serviceName)
endpoint := fmt.Sprintf(
"/cloud/project/%s/user/%s",
url.PathEscape(serviceName),
d.Id(),
)
if err := config.OVHClient.Get(endpoint, user); err != nil {
return helpers.CheckDeleted(d, err, endpoint)
}
d.SetId(strconv.Itoa(user.Id))
// set resource attributes
for k, v := range user.ToMap() {
d.Set(k, v)
}
openstackrc := make(map[string]string)
if err := cloudUserGetOpenstackRC(serviceName, d.Id(), config.OVHClient, openstackrc); err != nil {
return fmt.Errorf("Reading openstack creds for user %s: %s", d.Id(), err)
}
d.Set("openstack_rc", &openstackrc)
d.Set("service_name", serviceName)
log.Printf("[DEBUG] Read Public Cloud User %s", user)
return nil
}
func resourceCloudProjectUserDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
serviceName := d.Get("service_name").(string)
id := d.Id()
log.Printf("[DEBUG] Will delete public cloud user %s from project: %s", id, serviceName)
endpoint := fmt.Sprintf(
"/cloud/project/%s/user/%s",
url.PathEscape(serviceName),
id,
)
if err := config.OVHClient.Delete(endpoint, nil); err != nil {
return fmt.Errorf("calling Delete %s:\n\t %q", endpoint, err)
}
log.Printf("[DEBUG] Deleting Public Cloud User %s from project %s:", id, serviceName)
stateConf := &resource.StateChangeConf{
Pending: []string{"deleting"},
Target: []string{"deleted"},
Refresh: waitForCloudProjectUser(config.OVHClient, serviceName, id),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
if _, err := stateConf.WaitForState(); err != nil {
return fmt.Errorf("Deleting Public Cloud user %s from project %s", id, serviceName)
}
log.Printf("[DEBUG] Deleted Public Cloud User %s from project %s", id, serviceName)
d.SetId("")
return nil
}
var cloudUserOSTenantName = regexp.MustCompile("export OS_TENANT_NAME=\"?([[:alnum:]]+)\"?")
var cloudUserOSTenantId = regexp.MustCompile("export OS_TENANT_ID=\"??([[:alnum:]]+)\"??")
var cloudUserOSAuthURL = regexp.MustCompile("export OS_AUTH_URL=\"??([[:^space:]]+)\"??")
var cloudUserOSUsername = regexp.MustCompile("export OS_USERNAME=\"?([[:alnum:]]+)\"?")
func cloudUserGetOpenstackRC(serviceName, id string, c *ovh.Client, rc map[string]string) error {
log.Printf("[DEBUG] Will read public cloud user openstack rc for project: %s, id: %s", serviceName, id)
endpoint := fmt.Sprintf(
"/cloud/project/%s/user/%s/openrc?region=to_be_overriden",
url.PathEscape(serviceName),
id,
)
r := &CloudProjectUserOpenstackRC{}
if err := c.Get(endpoint, r); err != nil {
return fmt.Errorf("calling Get %s:\n\t %q", endpoint, err)
}
authURL := cloudUserOSAuthURL.FindStringSubmatch(r.Content)
if authURL == nil {
return fmt.Errorf("couln't extract OS_AUTH_URL from content: \n\t%s", r.Content)
}
tenantName := cloudUserOSTenantName.FindStringSubmatch(r.Content)
if tenantName == nil {
return fmt.Errorf("couln't extract OS_TENANT_NAME from content: \n\t%s", r.Content)
}
tenantId := cloudUserOSTenantId.FindStringSubmatch(r.Content)
if tenantId == nil {
return fmt.Errorf("couln't extract OS_TENANT_ID from content: \n\t%s", r.Content)
}
username := cloudUserOSUsername.FindStringSubmatch(r.Content)
if username == nil {
return fmt.Errorf("couln't extract OS_USERNAME from content: \n\t%s", r.Content)
}
rc["OS_AUTH_URL"] = authURL[1]
rc["OS_TENANT_ID"] = tenantId[1]
rc["OS_TENANT_NAME"] = tenantName[1]
rc["OS_USERNAME"] = username[1]
return nil
}
func waitForCloudProjectUser(c *ovh.Client, serviceName, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
r := &CloudProjectUser{}
endpoint := fmt.Sprintf(
"/cloud/project/%s/user/%s",
url.PathEscape(serviceName),
id,
)
if err := c.Get(endpoint, r); err != nil {
if errOvh, ok := err.(*ovh.APIError); ok && errOvh.Code == 404 {
log.Printf("[DEBUG] user id %s on project %s deleted", id, serviceName)
return r, "deleted", nil
} else {
return r, "", err
}
}
log.Printf("[DEBUG] Pending User: %s", r)
return r, r.Status, nil
}
}