-
Notifications
You must be signed in to change notification settings - Fork 23
/
resource_alks_iamrole.go
388 lines (324 loc) · 10.8 KB
/
resource_alks_iamrole.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"github.com/Cox-Automotive/alks-go"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
func resourceAlksIamRole() *schema.Resource {
return &schema.Resource{
CreateContext: resourceAlksIamRoleCreate,
ReadContext: resourceAlksIamRoleRead,
UpdateContext: resourceAlksIamRoleUpdate,
DeleteContext: resourceAlksIamRoleDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
SchemaVersion: 1,
MigrateState: migrateState,
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name_prefix"},
ValidateFunc: ValidRoleName,
},
"name_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"name"},
ValidateFunc: ValidRolePrefix,
},
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ExactlyOneOf: []string{"assume_role_policy", "type"},
},
"assume_role_policy": {
Type: schema.TypeString,
Optional: true,
ForceNew: false,
ExactlyOneOf: []string{"assume_role_policy", "type"},
DiffSuppressFunc: SuppressEquivalentTrustPolicyDiffs,
},
"include_default_policies": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"role_added_to_ip": {
Type: schema.TypeBool,
Computed: true,
},
"arn": {
Type: schema.TypeString,
Computed: true,
},
"ip_arn": {
Type: schema.TypeString,
Computed: true,
},
"enable_alks_access": {
Type: schema.TypeBool,
Default: false,
Optional: true,
ForceNew: true,
},
"template_fields": {
Type: schema.TypeMap,
Elem: schema.TypeString,
ForceNew: true,
Optional: true,
},
"max_session_duration_in_seconds": {
Type: schema.TypeInt,
Default: 3600,
Optional: true,
ForceNew: true,
},
"tags": TagsSchema(),
"tags_all": TagsSchemaComputed(),
},
CustomizeDiff: customdiff.All(
SetTagsDiff,
trustPoliciesWithIncludeDefaultPolicies,
),
}
}
func resourceAlksIamRoleCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] ALKS IAM Role Create")
var roleName = NameWithPrefix(d.Get("name").(string), d.Get("name_prefix").(string))
var incDefPol = d.Get("include_default_policies").(bool)
var enableAlksAccess = d.Get("enable_alks_access").(bool)
var rawTemplateFields = d.Get("template_fields").(map[string]interface{})
var maxSessionDurationInSeconds = d.Get("max_session_duration_in_seconds").(int)
var tags = d.Get("tags").(map[string]interface{})
templateFields := make(map[string]string)
for k, v := range rawTemplateFields {
templateFields[k] = v.(string)
}
include := false
if incDefPol {
include = true
}
providerStruct := meta.(*AlksClient)
client := providerStruct.client
//Role Specific tags will overwrite default tags if value is defined in both maps
allTags := tagMapToSlice(combineTagMaps(providerStruct.defaultTags, tags))
if err := validateIAMEnabled(client); err != nil {
return diag.FromErr(err)
}
options := &alks.CreateIamRoleOptions{
RoleName: &roleName,
IncludeDefaultPolicies: &include,
AlksAccess: &enableAlksAccess,
TemplateFields: &templateFields,
MaxSessionDurationInSeconds: &maxSessionDurationInSeconds,
Tags: &allTags,
}
if roleType, ok := d.GetOk("type"); ok {
roleTypeString := roleType.(string)
options.RoleType = &roleTypeString
} else {
trustPolicyString := d.Get("assume_role_policy").(string)
trustPolicy := new(map[string]interface{})
json.Unmarshal([]byte(trustPolicyString), trustPolicy)
options.TrustPolicy = trustPolicy
}
resp, err := client.CreateIamRole(options)
if err != nil {
return diag.FromErr(err)
}
d.SetId(resp.RoleName)
_ = d.Set("role_added_to_ip", resp.RoleAddedToIP)
log.Printf("[INFO] alks_iamrole.id: %v", d.Id())
return resourceAlksIamRoleRead(ctx, d, meta)
}
func resourceAlksIamRoleDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] ALKS IAM Role Delete")
providerStruct := meta.(*AlksClient)
client := providerStruct.client
if err := validateIAMEnabled(client); err != nil {
return diag.FromErr(err)
}
if err := client.DeleteIamRole(d.Id()); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceAlksIamRoleRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] ALKS IAM Role Read")
providerStruct := meta.(*AlksClient)
client := providerStruct.client
defaultTags := providerStruct.defaultTags
ignoreTags := providerStruct.ignoreTags
// Check if role exists.
if d.Id() == "" || d.Id() == "none" {
return nil
}
foundRole, err := client.GetIamRole(d.Id())
if err != nil {
//If error is 404, RoleNotFound, we log it and let terraform decide how to handle it.
//All other errors cause a failure
if err.StatusCode == 404 {
log.Printf("[Error] %s", err.Error())
d.SetId("")
return nil
}
return diag.FromErr(err)
}
log.Printf("[INFO] alks_iamrole.id %v", d.Id())
_ = d.Set("name", foundRole.RoleName)
_ = d.Set("name_prefix", NamePrefixFromName(foundRole.RoleName))
_ = d.Set("arn", foundRole.RoleArn)
_ = d.Set("ip_arn", foundRole.RoleIPArn)
_ = d.Set("enable_alks_access", foundRole.AlksAccess)
_ = d.Set("role_added_to_ip", foundRole.RoleAddedToIP)
var roleType = d.Get("type")
if (roleType == nil) || (roleType == "") {
jsonStrPolicy, err := json.Marshal(foundRole.TrustPolicy)
if err == nil {
_ = d.Set("assume_role_policy", string(jsonStrPolicy))
}
_ = d.Set("include_default_policies", false)
}
_ = d.Set("max_session_duration_in_seconds", foundRole.MaxSessionDurationInSeconds)
allTags := tagSliceToMap(foundRole.Tags)
localTags := removeIgnoredTags(allTags, *ignoreTags)
if err := d.Set("tags_all", localTags); err != nil {
return diag.FromErr(err)
}
if err := d.Set("tags", removeIgnoredTags(resolveDuplicates(allTags, defaultTags, d), *ignoreTags)); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceAlksIamRoleUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] ALKS IAM Role Update")
providerStruct := meta.(*AlksClient)
client := providerStruct.client
if err := validateIAMEnabled(client); err != nil {
return diag.FromErr(err)
}
// enable partial state mode
d.Partial(true)
if d.HasChange("enable_alks_access") {
// try updating enable_alks_access
if err := updateAlksAccess(d, meta); err != nil {
return diag.FromErr(err)
}
}
//Do a read to get existing tags. If any of those are in ignore_tags, then they are externally managed
//and they should be included in the update so they don't get removed.
foundRole, err := client.GetIamRole(d.Id())
if err != nil {
return diag.FromErr(err)
}
options := alks.UpdateIamRoleRequest{
RoleName: &foundRole.RoleName,
}
if d.HasChange("tags_all") {
existingTags := tagSliceToMap(foundRole.Tags)
externalTags := getExternalyManagedTags(existingTags, *providerStruct.ignoreTags)
internalTags := d.Get("tags_all").(map[string]interface{})
//Tags includes default tags, role specific tags, and tags that exist externally on the role itself and are specified in ignored_tags
tags := tagMapToSlice(combineTagMaps(internalTags, externalTags))
options.Tags = &tags
}
if d.HasChange("assume_role_policy") {
// try updating assume_role_policy
trustPolicyString := d.Get("assume_role_policy").(string)
trustPolicy := new(map[string]interface{})
err := json.Unmarshal([]byte(trustPolicyString), trustPolicy)
if err != nil {
return diag.FromErr(err)
}
options.TrustPolicy = trustPolicy
}
if _, err := client.UpdateIamRole(&options); err != nil {
return diag.FromErr(err)
}
d.Partial(false)
return resourceAlksIamRoleRead(ctx, d, meta)
}
func updateAlksAccess(d *schema.ResourceData, meta interface{}) error {
var alksAccess = d.Get("enable_alks_access").(bool)
var roleArn = d.Get("arn").(string)
providerStruct := meta.(*AlksClient)
client := providerStruct.client
if err := validateIAMEnabled(client); err != nil {
return err
}
// create the machine identity
if alksAccess {
_, err := client.AddRoleMachineIdentity(roleArn)
if err != nil {
return err
}
} else {
// delete the machine identity
_, err := client.DeleteRoleMachineIdentity(roleArn)
if err != nil {
return err
}
}
return nil
}
func updateIamRoleTags(d *schema.ResourceData, meta interface{}) error {
providerStruct := meta.(*AlksClient)
client := providerStruct.client
if err := validateIAMEnabled(client); err != nil {
return err
}
//Do a read to get existing tags. If any of those are in ignore_tags, then they are externally managed
//and they should be included in the update so they don't get removed.
foundRole, err := client.GetIamRole(d.Id())
if err != nil {
return err
}
existingTags := tagSliceToMap(foundRole.Tags)
externalTags := getExternalyManagedTags(existingTags, *providerStruct.ignoreTags)
internalTags := d.Get("tags_all").(map[string]interface{})
//Tags includes default tags, role specific tags, and tags that exist externally on the role itself and are specified in ignored_tags
tags := tagMapToSlice(combineTagMaps(internalTags, externalTags))
options := alks.UpdateIamRoleRequest{
RoleName: &foundRole.RoleName,
Tags: &tags,
}
if _, err := client.UpdateIamRole(&options); err != nil {
return err
}
return nil
}
func migrateState(version int, state *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
switch version {
case 0:
log.Println("[INFO] Found Instance State v0, migrating to v1")
return migrateV0toV1(state)
default:
return state, fmt.Errorf("Unrecognized version '%d' in schema for instance of ALKS IAM role '%s'", version, state.Attributes["name"])
}
}
func migrateV0toV1(state *terraform.InstanceState) (*terraform.InstanceState, error) {
if state.Empty() {
log.Println("[DEBUG] Empty InstanceState, nothing to migrate")
return state, nil
}
if _, ok := state.Attributes["enable_alks_access"]; !ok {
log.Printf("[DEBUG] Attributes before migration: %#v", state.Attributes)
state.Attributes["enable_alks_access"] = "false"
log.Printf("[DEBUG] Attributes after migration: %#v", state.Attributes)
}
return state, nil
}