-
Notifications
You must be signed in to change notification settings - Fork 392
/
Copy pathresource_datadog_user.go
394 lines (350 loc) · 13.5 KB
/
resource_datadog_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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package datadog
import (
"context"
"log"
"github.com/terraform-providers/terraform-provider-datadog/datadog/internal/utils"
"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func resourceDatadogUser() *schema.Resource {
return &schema.Resource{
Description: "Provides a Datadog user resource. This can be used to create and manage Datadog users.",
CreateContext: resourceDatadogUserCreate,
ReadContext: resourceDatadogUserRead,
UpdateContext: resourceDatadogUserUpdate,
DeleteContext: resourceDatadogUserDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaFunc: func() map[string]*schema.Schema {
return map[string]*schema.Schema{
"disabled": {
Description: "Whether the user is disabled.",
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"email": {
Description: "Email address for user.",
Type: schema.TypeString,
Required: true,
},
"name": {
Description: "User's name. Should be set only for password authentication, as it is overridden by Google or SAML authentication.",
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"roles": {
Description: "A list of role IDs to assign to the user.",
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"send_user_invitation": {
Description: "Whether an invitation email should be sent when the user is created.",
Type: schema.TypeBool,
Optional: true,
Default: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// This is only used on create, so don't generate diff when the resource already exists
return d.Id() != ""
},
},
"verified": {
Description: "Returns `true` if the user is verified.",
Type: schema.TypeBool,
Computed: true,
},
"user_invitation_id": {
Description: "The ID of the user invitation that was sent when creating the user.",
Type: schema.TypeString,
Computed: true,
},
}
},
}
}
func buildDatadogUserV2Struct(d *schema.ResourceData) *datadogV2.UserCreateRequest {
userAttributes := datadogV2.NewUserCreateAttributesWithDefaults()
userAttributes.SetEmail(d.Get("email").(string))
if v, ok := d.GetOk("name"); ok {
userAttributes.SetName(v.(string))
}
userCreate := datadogV2.NewUserCreateDataWithDefaults()
userCreate.SetAttributes(*userAttributes)
roles := d.Get("roles").(*schema.Set).List()
rolesData := make([]datadogV2.RelationshipToRoleData, len(roles))
for i, role := range roles {
roleData := datadogV2.NewRelationshipToRoleData()
roleData.SetId(role.(string))
rolesData[i] = *roleData
}
toRoles := datadogV2.NewRelationshipToRoles()
toRoles.SetData(rolesData)
userRelationships := datadogV2.NewUserRelationships()
userRelationships.SetRoles(*toRoles)
userCreate.SetRelationships(*userRelationships)
userRequest := datadogV2.NewUserCreateRequestWithDefaults()
userRequest.SetData(*userCreate)
return userRequest
}
// Note: when migrating to Framework, use buildDatadogUserV2UpdateStructFw from datadog/resource_datadog_service_account.go
func buildDatadogUserV2UpdateStruct(d *schema.ResourceData, userID string) *datadogV2.UserUpdateRequest {
userAttributes := datadogV2.NewUserUpdateAttributesWithDefaults()
userAttributes.SetEmail(d.Get("email").(string))
if v, ok := d.GetOk("name"); ok {
userAttributes.SetName(v.(string))
}
userAttributes.SetDisabled(d.Get("disabled").(bool))
userUpdate := datadogV2.NewUserUpdateDataWithDefaults()
userUpdate.SetAttributes(*userAttributes)
userUpdate.SetId(userID)
userRequest := datadogV2.NewUserUpdateRequestWithDefaults()
userRequest.SetData(*userUpdate)
return userRequest
}
// Note: when migrating to Framework, use updateRolesFw from datadog/resource_datadog_service_account.go
func updateRoles(meta interface{}, userID string, oldRoles *schema.Set, newRoles *schema.Set) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
rolesToRemove := oldRoles.Difference(newRoles)
rolesToAdd := newRoles.Difference(oldRoles)
for _, roleI := range rolesToAdd.List() {
role := roleI.(string)
roleRelation := datadogV2.NewRelationshipToUserWithDefaults()
roleRelationData := datadogV2.NewRelationshipToUserDataWithDefaults()
roleRelationData.SetId(userID)
roleRelation.SetData(*roleRelationData)
_, httpResponse, err := apiInstances.GetRolesApiV2().AddUserToRole(auth, role, *roleRelation)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpResponse, "error adding user to role")
}
}
for _, roleI := range rolesToRemove.List() {
role := roleI.(string)
userRelation := datadogV2.NewRelationshipToUserWithDefaults()
userRelationData := datadogV2.NewRelationshipToUserDataWithDefaults()
userRelationData.SetId(userID)
userRelation.SetData(*userRelationData)
_, httpResponse, err := apiInstances.GetRolesApiV2().RemoveUserFromRole(auth, role, *userRelation)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpResponse, "error removing user from role")
}
}
return nil
}
func resourceDatadogUserCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
userRequest := buildDatadogUserV2Struct(d)
var userID string
updated := false
// Datadog does not actually delete users, so CreateUser might return a 409.
// We ignore that case and proceed, likely re-enabling the user.
createResponse, httpresp, err := apiInstances.GetUsersApiV2().CreateUser(auth, *userRequest)
if err != nil {
if httpresp == nil || httpresp.StatusCode != 409 {
return utils.TranslateClientErrorDiag(err, httpresp, "error creating user")
}
email := d.Get("email").(string)
log.Printf("[INFO] Updating existing Datadog user %s", email)
var existingUser *datadogV2.User
// Find user ID by listing user and filtering by email
listResponse, httpResp, err := apiInstances.GetUsersApiV2().ListUsers(auth,
*datadogV2.NewListUsersOptionalParameters().WithFilter(email))
if err != nil {
return utils.TranslateClientErrorDiag(err, httpResp, "error searching user")
}
if err := utils.CheckForUnparsed(listResponse); err != nil {
return diag.FromErr(err)
}
responseData := listResponse.GetData()
if len(responseData) == 1 {
existingUser = &responseData[0]
}
if len(responseData) > 1 {
for _, user := range responseData {
if user.Attributes.GetEmail() == email {
existingUser = &user
break
}
}
if existingUser == nil {
return diag.Errorf("could not find single user with email %s", email)
}
}
if existingUser == nil {
// We already raised an exception if multiple users were found but no exact email match.
// If user is nil at this stage, we can assume a user with the same handle already exists.
// Find the user and raise a helpful error message.
var existingUserWithHandle *datadogV2.User
resp, _ := apiInstances.GetUsersApiV2().ListUsersWithPagination(auth, *datadogV2.NewListUsersOptionalParameters().WithPageSize(500))
for paginationResult := range resp {
if paginationResult.Error != nil {
return diag.Errorf("error listing users: %s", paginationResult.Error)
}
if paginationResult.Item.Attributes.GetHandle() == email {
existingUserWithHandle = &paginationResult.Item
break
}
}
if existingUserWithHandle != nil {
return diag.Errorf("user with id %q already exists with handle %q", existingUserWithHandle.GetId(), email)
}
// Catch all error
return diag.Errorf("error retrieving user with email/handle %s", email)
}
userID = existingUser.GetId()
userRequest := buildDatadogUserV2UpdateStruct(d, userID)
updatedUser, _, err := apiInstances.GetUsersApiV2().UpdateUser(auth, userID, *userRequest)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpresp, "error updating user")
}
if err := utils.CheckForUnparsed(updatedUser); err != nil {
return diag.FromErr(err)
}
// Update roles
_, newRolesI := d.GetChange("roles")
newRoles := newRolesI.(*schema.Set)
oldRoles := schema.NewSet(newRoles.F, []interface{}{})
for _, existingRole := range updatedUser.Data.Relationships.Roles.GetData() {
oldRoles.Add(existingRole.GetId())
}
if err := updateRoles(meta, userID, oldRoles, newRoles); err != nil {
return err
}
if err := updateUserStateV2(d, &updatedUser); err != nil {
return err
}
updated = true
} else {
if err := utils.CheckForUnparsed(createResponse); err != nil {
return diag.FromErr(err)
}
userData := createResponse.GetData()
userID = userData.GetId()
}
// Send invitation email to newly created users
if d.Get("send_user_invitation").(bool) {
if err := sendUserInvitation(userID, d, meta); err != nil {
return err
}
}
d.SetId(userID)
if updated {
return nil
}
return updateUserStateV2(d, &createResponse)
}
func sendUserInvitation(userID string, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
userInviteRelationData := datadogV2.NewRelationshipToUserDataWithDefaults()
userInviteRelationData.SetId(userID)
userInviteUserRelation := datadogV2.NewRelationshipToUserWithDefaults()
userInviteUserRelation.SetData(*userInviteRelationData)
userInviteRelationships := datadogV2.NewUserInvitationRelationshipsWithDefaults()
userInviteRelationships.SetUser(*userInviteUserRelation)
userInviteData := datadogV2.NewUserInvitationDataWithDefaults()
userInviteData.SetRelationships(*userInviteRelationships)
userInvite := []datadogV2.UserInvitationData{*userInviteData}
body := *datadogV2.NewUserInvitationsRequestWithDefaults()
body.SetData(userInvite)
res, httpResponse, err := apiInstances.GetUsersApiV2().SendInvitations(auth, body)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpResponse, "error sending user invitation")
}
if err := utils.CheckForUnparsed(res); err != nil {
return diag.FromErr(err)
}
if err := d.Set("user_invitation_id", res.GetData()[0].GetId()); err != nil {
return diag.FromErr(err)
}
return nil
}
func updateUserStateV2(d *schema.ResourceData, user *datadogV2.UserResponse) diag.Diagnostics {
userData := user.GetData()
userAttributes := userData.GetAttributes()
userRelations := userData.GetRelationships()
userRolesRelations := userRelations.GetRoles()
userRoles := userRolesRelations.GetData()
if err := d.Set("email", userAttributes.GetEmail()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("name", userAttributes.GetName()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("verified", userAttributes.GetVerified()); err != nil {
return diag.FromErr(err)
}
if err := d.Set("disabled", userAttributes.GetDisabled()); err != nil {
return diag.FromErr(err)
}
roles := make([]string, len(userRoles))
for i, userRole := range userRoles {
roles[i] = userRole.GetId()
}
if err := d.Set("roles", roles); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceDatadogUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
userResponse, httpResponse, err := apiInstances.GetUsersApiV2().GetUser(auth, d.Id())
if err != nil {
if httpResponse != nil && httpResponse.StatusCode == 404 {
d.SetId("")
return nil
}
return utils.TranslateClientErrorDiag(err, httpResponse, "error getting user")
}
if err := utils.CheckForUnparsed(userResponse); err != nil {
return diag.FromErr(err)
}
return updateUserStateV2(d, &userResponse)
}
func resourceDatadogUserUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
if d.HasChange("roles") {
oldRolesI, newRolesI := d.GetChange("roles")
oldRoles := oldRolesI.(*schema.Set)
newRoles := newRolesI.(*schema.Set)
if err := updateRoles(meta, d.Id(), oldRoles, newRoles); err != nil {
return err
}
}
userRequest := buildDatadogUserV2UpdateStruct(d, d.Id())
updatedUser, httpResponse, err := apiInstances.GetUsersApiV2().UpdateUser(auth, d.Id(), *userRequest)
if err != nil {
return utils.TranslateClientErrorDiag(err, httpResponse, "error updating user")
}
if err := utils.CheckForUnparsed(updatedUser); err != nil {
return diag.FromErr(err)
}
// Update state once after we do the UpdateUser operation. At this point, the roles have already been changed
// so the updated list is available in the update response.
return updateUserStateV2(d, &updatedUser)
}
func resourceDatadogUserDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
providerConf := meta.(*ProviderConfiguration)
apiInstances := providerConf.DatadogApiInstances
auth := providerConf.Auth
if httpResponse, err := apiInstances.GetUsersApiV2().DisableUser(auth, d.Id()); err != nil {
if httpResponse != nil && httpResponse.StatusCode == 404 {
return nil
}
return utils.TranslateClientErrorDiag(err, httpResponse, "error disabling user")
}
return nil
}