-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgroup_resource.go
349 lines (313 loc) · 11.7 KB
/
group_resource.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
package provider
import (
"context"
"fmt"
"strings"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/terraform-provider-coderd/internal/codersdkvalidator"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int32default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
// Ensure provider defined types fully satisfy framework interfaces.
var _ resource.Resource = &GroupResource{}
var _ resource.ResourceWithImportState = &GroupResource{}
func NewGroupResource() resource.Resource {
return &GroupResource{}
}
// GroupResource defines the resource implementation.
type GroupResource struct {
*CoderdProviderData
}
// GroupResourceModel describes the resource data model.
type GroupResourceModel struct {
ID UUID `tfsdk:"id"`
Name types.String `tfsdk:"name"`
DisplayName types.String `tfsdk:"display_name"`
AvatarURL types.String `tfsdk:"avatar_url"`
QuotaAllowance types.Int32 `tfsdk:"quota_allowance"`
OrganizationID UUID `tfsdk:"organization_id"`
Members types.Set `tfsdk:"members"`
}
func CheckGroupEntitlements(ctx context.Context, features map[codersdk.FeatureName]codersdk.Feature) (diags diag.Diagnostics) {
if !features[codersdk.FeatureTemplateRBAC].Enabled {
diags.AddError("Feature not enabled", "Your license is not entitled to use groups.")
return
}
return nil
}
func (r *GroupResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_group"
}
func (r *GroupResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "A group on the Coder deployment.\n\n" +
"Creating groups requires an Enterprise license.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
MarkdownDescription: "Group ID.",
CustomType: UUIDType,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
MarkdownDescription: "The unique name of the group.",
Required: true,
Validators: []validator.String{
codersdkvalidator.GroupName(),
},
},
"display_name": schema.StringAttribute{
MarkdownDescription: "The display name of the group. Defaults to the group name.",
Computed: true,
Optional: true,
Validators: []validator.String{
codersdkvalidator.DisplayName(),
},
Default: stringdefault.StaticString(""),
},
"avatar_url": schema.StringAttribute{
MarkdownDescription: "The URL of the group's avatar.",
Computed: true,
Optional: true,
Default: stringdefault.StaticString(""),
},
// Int32 in the db
"quota_allowance": schema.Int32Attribute{
MarkdownDescription: "The number of quota credits to allocate to each user in the group.",
Optional: true,
Computed: true,
Default: int32default.StaticInt32(0),
},
"organization_id": schema.StringAttribute{
MarkdownDescription: "The organization ID that the group belongs to. Defaults to the provider default organization ID.",
CustomType: UUIDType,
Optional: true,
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplaceIfConfigured(),
},
},
"members": schema.SetAttribute{
MarkdownDescription: "Members of the group, by ID. If `null`, members will not be added or removed by Terraform. To have a group resource with unmanaged members, but be able to read the members in Terraform, use `data.coderd_group`",
ElementType: UUIDType,
Optional: true,
},
},
}
}
func (r *GroupResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
data, ok := req.ProviderData.(*CoderdProviderData)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Resource Configure Type",
fmt.Sprintf("Expected *CoderdProviderData, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.CoderdProviderData = data
}
func (r *GroupResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
// Read Terraform plan data into the model
var data GroupResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(CheckGroupEntitlements(ctx, r.Features)...)
if resp.Diagnostics.HasError() {
return
}
orgID := data.OrganizationID.ValueUUID()
tflog.Info(ctx, "creating group")
group, err := r.Client.CreateGroup(ctx, orgID, codersdk.CreateGroupRequest{
Name: data.Name.ValueString(),
DisplayName: data.DisplayName.ValueString(),
AvatarURL: data.AvatarURL.ValueString(),
QuotaAllowance: int(data.QuotaAllowance.ValueInt32()),
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to create group, got error: %s", err))
return
}
tflog.Info(ctx, "successfully created group", map[string]any{
"id": group.ID.String(),
})
data.ID = UUIDValue(group.ID)
data.DisplayName = types.StringValue(group.DisplayName)
tflog.Info(ctx, "setting group members")
var members []string
resp.Diagnostics.Append(
data.Members.ElementsAs(ctx, &members, false)...,
)
if resp.Diagnostics.HasError() {
return
}
group, err = r.Client.PatchGroup(ctx, group.ID, codersdk.PatchGroupRequest{
AddUsers: members,
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to add members to group, got error: %s", err))
return
}
tflog.Info(ctx, "successfully set group members")
// Save data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *GroupResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
// Read Terraform prior state data into the model
var data GroupResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
groupID := data.ID.ValueUUID()
group, err := r.Client.Group(ctx, groupID)
if err != nil {
if isNotFound(err) {
resp.Diagnostics.AddWarning("Client Warning", fmt.Sprintf("Group with ID %s not found. Marking as deleted.", groupID.String()))
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get group, got error: %s", err))
return
}
data.Name = types.StringValue(group.Name)
data.DisplayName = types.StringValue(group.DisplayName)
data.AvatarURL = types.StringValue(group.AvatarURL)
data.QuotaAllowance = types.Int32Value(int32(group.QuotaAllowance))
data.OrganizationID = UUIDValue(group.OrganizationID)
if !data.Members.IsNull() {
members := make([]attr.Value, 0, len(group.Members))
for _, member := range group.Members {
members = append(members, UUIDValue(member.ID))
}
data.Members = types.SetValueMust(UUIDType, members)
}
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *GroupResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
// Read Terraform plan data into the model
var data GroupResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
groupID := data.ID.ValueUUID()
group, err := r.Client.Group(ctx, groupID)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get group, got error: %s", err))
return
}
var add []string
var remove []string
if !data.Members.IsNull() {
var plannedMembers []UUID
resp.Diagnostics.Append(data.Members.ElementsAs(ctx, &plannedMembers, false)...)
if resp.Diagnostics.HasError() {
return
}
curMembers := make([]uuid.UUID, 0, len(group.Members))
for _, member := range group.Members {
curMembers = append(curMembers, member.ID)
}
add, remove = memberDiff(curMembers, plannedMembers)
}
tflog.Info(ctx, "updating group", map[string]any{
"id": groupID,
"new_members": add,
"removed_members": remove,
"new_name": data.Name,
"new_displayname": data.DisplayName,
"new_avatarurl": data.AvatarURL,
"new_quota": data.QuotaAllowance,
})
quotaAllowance := int(data.QuotaAllowance.ValueInt32())
_, err = r.Client.PatchGroup(ctx, group.ID, codersdk.PatchGroupRequest{
AddUsers: add,
RemoveUsers: remove,
Name: data.Name.ValueString(),
DisplayName: data.DisplayName.ValueStringPointer(),
AvatarURL: data.AvatarURL.ValueStringPointer(),
QuotaAllowance: "aAllowance,
})
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to update group, got error: %s", err))
return
}
tflog.Info(ctx, "successfully updated group")
// Save updated data into Terraform state
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *GroupResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
// Read Terraform prior state data into the model
var data GroupResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
groupID := data.ID.ValueUUID()
tflog.Info(ctx, "deleting group", map[string]any{
"id": groupID,
})
err := r.Client.DeleteGroup(ctx, groupID)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to delete group, got error: %s", err))
return
}
tflog.Info(ctx, "successfully deleted group")
}
func (r *GroupResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
var groupID uuid.UUID
idParts := strings.Split(req.ID, "/")
if len(idParts) == 1 {
var err error
groupID, err = uuid.Parse(req.ID)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to parse import group ID as UUID, got error: %s", err))
return
}
} else if len(idParts) == 2 {
org, err := r.Client.OrganizationByName(ctx, idParts[0])
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to get organization with name %s: %s", idParts[0], err))
return
}
group, err := r.Client.GroupByOrgAndName(ctx, org.ID, idParts[1])
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Failed to get group with name %s: %s", idParts[1], err))
return
}
groupID = group.ID
} else {
resp.Diagnostics.AddError("Client Error", "Invalid import ID format, expected a single UUID or `<organization-name>/<group-name>`")
return
}
group, err := r.Client.Group(ctx, groupID)
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to get imported group, got error: %s", err))
return
}
if group.Source == "oidc" {
resp.Diagnostics.AddError("Client Error", "Cannot import groups created via OIDC")
return
}
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), groupID.String())...)
}