This repository has been archived by the owner on Jun 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
/
resource_group.go
289 lines (238 loc) · 7.2 KB
/
resource_group.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
package gsuite
import (
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
directory "google.golang.org/api/admin/directory/v1"
)
func resourceGroup() *schema.Resource {
return &schema.Resource{
Create: resourceGroupCreate,
Read: resourceGroupRead,
Update: resourceGroupUpdate,
Delete: resourceGroupDelete,
Importer: &schema.ResourceImporter{
State: resourceGroupImporter,
},
Schema: map[string]*schema.Schema{
"email": {
Type: schema.TypeString,
Required: true,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
ValidateFunc: validateEmail,
},
"aliases": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"direct_members_count": {
Type: schema.TypeInt,
Computed: true,
},
"admin_created": {
Type: schema.TypeBool,
Computed: true,
},
"non_editable_aliases": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
}
}
func resourceGroupCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
group := &directory.Group{
Email: strings.ToLower(d.Get("email").(string)),
}
if v, ok := d.GetOk("name"); ok {
log.Printf("[DEBUG] Setting group name: %s", v.(string))
group.Name = v.(string)
}
if v, ok := d.GetOk("description"); ok {
log.Printf("[DEBUG] Setting group description: %s", v.(string))
group.Description = v.(string)
}
var createdGroup *directory.Group
var err error
err = retry(func() error {
createdGroup, err = config.directory.Groups.Insert(group).Do()
return err
}, config.TimeoutMinutes)
// give the eventually consistent G Suite time to settle the group
time.Sleep(time.Second * 1)
if err != nil {
if config.UpdateExisting && strings.Contains(fmt.Sprintf("%s", err), "Entity already exists.") {
log.Printf("[INFO] Group already exists, overwriting existing values")
d.SetId(d.Get("email").(string))
return resourceGroupUpdate(d, meta)
}
return fmt.Errorf("[ERROR] Error creating group: %s", err)
}
// Try to read the group, retrying for 404's, this makes sure the group has been
// created before we try to use it for follow-up actions (like adding aliases)
err = retryNotFound(func() error {
group, err = config.directory.Groups.Get(createdGroup.Id).Do()
return err
}, config.TimeoutMinutes)
if err != nil {
return fmt.Errorf("[ERROR] Taking too long to create this group: %s", err)
}
d.SetId(createdGroup.Id)
log.Printf("[INFO] Created group: %s", createdGroup.Email)
// Handle group aliases
aliasesCount := d.Get("aliases.#").(int)
for i := 0; i < aliasesCount; i++ {
cfgAlias := d.Get(fmt.Sprintf("aliases.%d", i)).(string)
err = retry(func() error {
alias := &directory.Alias{
Alias: cfgAlias,
}
_, err = config.directory.Groups.Aliases.Insert(d.Id(), alias).Do()
return err
}, config.TimeoutMinutes)
}
if err != nil {
return fmt.Errorf("[ERROR] Error creating group aliases: %s", err)
}
return resourceGroupRead(d, meta)
}
func resourceGroupUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
group := &directory.Group{}
nullFields := []string{}
if d.HasChange("email") {
log.Printf("[DEBUG] Updating group email: %s", d.Get("email").(string))
group.Email = strings.ToLower(d.Get("email").(string))
}
if d.HasChange("name") {
if v, ok := d.GetOk("name"); ok {
log.Printf("[DEBUG] Updating group name: %s", v.(string))
group.Name = v.(string)
} else {
log.Printf("[DEBUG] Removing group name")
group.Name = ""
nullFields = append(nullFields, "name")
}
}
if d.HasChange("description") {
if v, ok := d.GetOk("description"); ok {
log.Printf("[DEBUG] Updating group description: %s", v.(string))
group.Description = v.(string)
} else {
log.Printf("[DEBUG] Removing group description")
group.Description = ""
nullFields = append(nullFields, "description")
}
}
if len(nullFields) > 0 {
group.NullFields = nullFields
}
var updatedGroup *directory.Group
var err error
err = retry(func() error {
updatedGroup, err = config.directory.Groups.Patch(d.Id(), group).Do()
return err
}, config.TimeoutMinutes)
if err != nil {
return fmt.Errorf("[ERROR] Error updating group: %s", err)
}
// in case we were updating an existing we set the id back to the API ID
d.SetId(updatedGroup.Id)
// Handle group aliases
var aliasesResponse *directory.Aliases
err = retry(func() error {
aliasesResponse, err = config.directory.Groups.Aliases.List(d.Id()).Do()
return err
}, config.TimeoutMinutes)
if err != nil {
return fmt.Errorf("[ERROR] Could not list group aliases: %s", err)
}
for _, v := range aliasesResponse.Aliases {
c, ok := v.(map[string]interface{})
if ok {
alias := c["alias"].(string)
log.Printf("[DEBUG] Removing alias: %s", alias)
err = config.directory.Groups.Aliases.Delete(d.Id(), alias).Do()
}
}
if err != nil {
return fmt.Errorf("[ERROR] Error removing group aliases: %s", err)
}
aliasesCount := d.Get("aliases.#").(int)
for i := 0; i < aliasesCount; i++ {
cfgAlias := d.Get(fmt.Sprintf("aliases.%d", i)).(string)
err = retry(func() error {
alias := &directory.Alias{
Alias: cfgAlias,
}
_, err = config.directory.Groups.Aliases.Insert(d.Id(), alias).Do()
return err
}, config.TimeoutMinutes)
}
if err != nil {
return fmt.Errorf("[ERROR] Error creating group aliases: %s", err)
}
log.Printf("[INFO] Updated group: %s", updatedGroup.Email)
return resourceGroupRead(d, meta)
}
func resourceGroupRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
var group *directory.Group
var err error
err = retry(func() error {
group, err = config.directory.Groups.Get(d.Id()).Do()
return err
}, config.TimeoutMinutes)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Group %q", d.Get("name").(string)))
}
d.SetId(group.Id)
d.Set("direct_members_count", group.DirectMembersCount)
d.Set("admin_created", group.AdminCreated)
d.Set("aliases", group.Aliases)
d.Set("non_editable_aliases", group.NonEditableAliases)
d.Set("description", group.Description)
d.Set("name", group.Name)
return nil
}
func resourceGroupDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
var err error
err = retry(func() error {
err = config.directory.Groups.Delete(d.Id()).Do()
return err
}, config.TimeoutMinutes)
if err != nil {
return fmt.Errorf("[ERROR] Error deleting group: %s", err)
}
d.SetId("")
return nil
}
// Allow importing using any key (id, email, alias)
func resourceGroupImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
id, err := config.directory.Groups.Get(d.Id()).Do()
if err != nil {
return nil, fmt.Errorf("[ERROR] Error fetching group. Make sure the group exists: %s ", err)
}
d.SetId(id.Id)
d.Set("email", id.Email)
d.Set("description", id.Description)
d.Set("name", id.Name)
return []*schema.ResourceData{d}, nil
}