-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathinstance_profile.go
405 lines (326 loc) · 12.3 KB
/
instance_profile.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
395
396
397
398
399
400
401
402
403
404
405
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package iam
import (
"context"
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/arn"
"github.com/aws/aws-sdk-go-v2/service/iam"
awstypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/id"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/create"
"github.com/hashicorp/terraform-provider-aws/internal/enum"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/names"
)
const (
instanceProfileNameMaxLen = 128
instanceProfileNamePrefixMaxLen = instanceProfileNameMaxLen - id.UniqueIDSuffixLength
)
// @SDKResource("aws_iam_instance_profile", name="Instance Profile")
// @Tags(identifierAttribute="id", resourceType="InstanceProfile")
// @Testing(existsType="github.com/aws/aws-sdk-go-v2/service/iam/types;types.InstanceProfile")
func resourceInstanceProfile() *schema.Resource {
return &schema.Resource{
CreateWithoutTimeout: resourceInstanceProfileCreate,
ReadWithoutTimeout: resourceInstanceProfileRead,
UpdateWithoutTimeout: resourceInstanceProfileUpdate,
DeleteWithoutTimeout: resourceInstanceProfileDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
names.AttrARN: {
Type: schema.TypeString,
Computed: true,
},
"create_date": {
Type: schema.TypeString,
Computed: true,
},
names.AttrName: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{names.AttrNamePrefix},
ValidateFunc: validResourceName(instanceProfileNameMaxLen),
},
names.AttrNamePrefix: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{names.AttrName},
ValidateFunc: validResourceName(instanceProfileNamePrefixMaxLen),
},
names.AttrPath: {
Type: schema.TypeString,
Optional: true,
Default: "/",
ForceNew: true,
},
names.AttrRole: {
Type: schema.TypeString,
Optional: true,
},
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
"unique_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceInstanceProfileCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).IAMClient(ctx)
name := create.Name(d.Get(names.AttrName).(string), d.Get(names.AttrNamePrefix).(string))
input := &iam.CreateInstanceProfileInput{
InstanceProfileName: aws.String(name),
Path: aws.String(d.Get(names.AttrPath).(string)),
Tags: getTagsIn(ctx),
}
output, err := conn.CreateInstanceProfile(ctx, input)
// Some partitions (e.g. ISO) may not support tag-on-create.
partition := meta.(*conns.AWSClient).Partition(ctx)
if input.Tags != nil && errs.IsUnsupportedOperationInPartitionError(partition, err) {
input.Tags = nil
output, err = conn.CreateInstanceProfile(ctx, input)
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "creating IAM Instance Profile (%s): %s", name, err)
}
d.SetId(aws.ToString(output.InstanceProfile.InstanceProfileName))
_, err = tfresource.RetryWhenNotFound(ctx, propagationTimeout, func() (interface{}, error) {
return findInstanceProfileByName(ctx, conn, d.Id())
})
if err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for IAM Instance Profile (%s) create: %s", d.Id(), err)
}
if v, ok := d.GetOk(names.AttrRole); ok {
err := instanceProfileAddRole(ctx, conn, d.Id(), v.(string))
if err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
}
// For partitions not supporting tag-on-create, attempt tag after create.
if tags := getTagsIn(ctx); input.Tags == nil && len(tags) > 0 {
err := instanceProfileCreateTags(ctx, conn, d.Id(), tags)
// If default tags only, continue. Otherwise, error.
if v, ok := d.GetOk(names.AttrTags); (!ok || len(v.(map[string]interface{})) == 0) && errs.IsUnsupportedOperationInPartitionError(partition, err) {
return append(diags, resourceInstanceProfileRead(ctx, d, meta)...)
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "setting IAM Instance Profile (%s) tags: %s", d.Id(), err)
}
}
if err := waitInstanceProfileReady(ctx, conn, name, d.Timeout(schema.TimeoutCreate)); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for IAM Instance Profile (%s) to be ready: %s", name, err)
}
return append(diags, resourceInstanceProfileRead(ctx, d, meta)...)
}
func resourceInstanceProfileRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).IAMClient(ctx)
instanceProfile, err := findInstanceProfileByName(ctx, conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] IAM Instance Profile (%s) not found, removing from state", d.Id())
d.SetId("")
return diags
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading IAM Instance Profile (%s): %s", d.Id(), err)
}
if len(instanceProfile.Roles) > 0 {
roleName := aws.ToString(instanceProfile.Roles[0].RoleName)
_, err := findRoleByName(ctx, conn, roleName)
if err != nil {
if tfresource.NotFound(err) {
err := instanceProfileRemoveRole(ctx, conn, d.Id(), roleName)
if err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
}
return sdkdiag.AppendErrorf(diags, "reading IAM Role (%s) attached to IAM Instance Profile (%s): %s", roleName, d.Id(), err)
}
}
d.Set(names.AttrARN, instanceProfile.Arn)
d.Set("create_date", instanceProfile.CreateDate.Format(time.RFC3339))
d.Set(names.AttrName, instanceProfile.InstanceProfileName)
d.Set(names.AttrNamePrefix, create.NamePrefixFromName(aws.ToString(instanceProfile.InstanceProfileName)))
d.Set(names.AttrPath, instanceProfile.Path)
if d.Get(names.AttrRole) != "" {
d.Set(names.AttrRole, nil)
}
if len(instanceProfile.Roles) > 0 {
d.Set(names.AttrRole, instanceProfile.Roles[0].RoleName) //there will only be 1 role returned
}
d.Set("unique_id", instanceProfile.InstanceProfileId)
setTagsOut(ctx, instanceProfile.Tags)
return diags
}
func resourceInstanceProfileUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).IAMClient(ctx)
if d.HasChange(names.AttrRole) {
o, n := d.GetChange(names.AttrRole)
if o := o.(string); o != "" {
err := instanceProfileRemoveRole(ctx, conn, d.Id(), o)
if err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
}
if n := n.(string); n != "" {
err := instanceProfileAddRole(ctx, conn, d.Id(), n)
if err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
}
}
if err := waitInstanceProfileReady(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate)); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for IAM Instance Profile (%s) to be ready: %s", d.Id(), err)
}
return append(diags, resourceInstanceProfileRead(ctx, d, meta)...)
}
func resourceInstanceProfileDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).IAMClient(ctx)
if v, ok := d.GetOk(names.AttrRole); ok {
err := instanceProfileRemoveRole(ctx, conn, d.Id(), v.(string))
if err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
}
log.Printf("[INFO] Deleting IAM Instance Profile: %s", d.Id())
_, err := conn.DeleteInstanceProfile(ctx, &iam.DeleteInstanceProfileInput{
InstanceProfileName: aws.String(d.Id()),
})
if errs.IsA[*awstypes.NoSuchEntityException](err) {
return diags
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "deleting IAM Instance Profile (%s): %s", d.Id(), err)
}
return diags
}
func instanceProfileAddRole(ctx context.Context, conn *iam.Client, profileName, roleName string) error {
input := &iam.AddRoleToInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
RoleName: aws.String(roleName),
}
_, err := tfresource.RetryWhen(ctx, propagationTimeout,
func() (interface{}, error) {
return conn.AddRoleToInstanceProfile(ctx, input)
},
func(err error) (bool, error) {
// IAM unfortunately does not provide a better error code or message for eventual consistency
// InvalidParameterValue: Value (XXX) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name
// NoSuchEntity: The request was rejected because it referenced an entity that does not exist. The error message describes the entity. HTTP Status Code: 404
errInvalidParameterValue := invalidParameterValueError{err}
if errs.IsAErrorMessageContains[*invalidParameterValueError](errInvalidParameterValue, "Invalid IAM Instance Profile name") || errs.IsAErrorMessageContains[*awstypes.NoSuchEntityException](err, "The role with name") {
return true, err
}
return false, err
},
)
if err != nil {
return fmt.Errorf("adding IAM Role (%s) to IAM Instance Profile (%s): %w", roleName, profileName, err)
}
return nil
}
func instanceProfileRemoveRole(ctx context.Context, conn *iam.Client, profileName, roleName string) error {
input := &iam.RemoveRoleFromInstanceProfileInput{
InstanceProfileName: aws.String(profileName),
RoleName: aws.String(roleName),
}
_, err := conn.RemoveRoleFromInstanceProfile(ctx, input)
if errs.IsA[*awstypes.NoSuchEntityException](err) {
return nil
}
if err != nil {
return fmt.Errorf("removing IAM Role (%s) from IAM Instance Profile (%s): %w", roleName, profileName, err)
}
return nil
}
func findInstanceProfileByName(ctx context.Context, conn *iam.Client, name string) (*awstypes.InstanceProfile, error) {
input := &iam.GetInstanceProfileInput{
InstanceProfileName: aws.String(name),
}
output, err := conn.GetInstanceProfile(ctx, input)
if errs.IsA[*awstypes.NoSuchEntityException](err) {
return nil, &retry.NotFoundError{
LastError: err,
LastRequest: input,
}
}
if err != nil {
return nil, err
}
if output == nil || output.InstanceProfile == nil {
return nil, tfresource.NewEmptyResultError(input)
}
return output.InstanceProfile, nil
}
const (
InstanceProfileFound = "Found"
InstanceProfileInvalidARN = "InvalidARN"
)
func statusInstanceProfile(ctx context.Context, conn *iam.Client, name string) retry.StateRefreshFunc {
return func() (interface{}, string, error) {
output, err := findInstanceProfileByName(ctx, conn, name)
if tfresource.NotFound(err) {
return nil, "", nil
}
if err != nil {
return nil, "", err
}
_, err = arn.Parse(aws.ToString(output.Arn))
if err != nil {
return nil, InstanceProfileInvalidARN, nil // lint:ignore nilerr // this is usually a temporary state
}
return output, InstanceProfileFound, nil
}
}
func waitInstanceProfileReady(ctx context.Context, conn *iam.Client, id string, timeout time.Duration) error {
stateConf := &retry.StateChangeConf{
Pending: []string{"", InstanceProfileInvalidARN},
Target: enum.Slice(InstanceProfileFound),
Refresh: statusInstanceProfile(ctx, conn, id),
Timeout: timeout,
Delay: 5 * time.Second,
NotFoundChecks: 5,
ContinuousTargetOccurence: 3,
}
_, err := stateConf.WaitForStateContext(ctx)
return err
}
func instanceProfileTags(ctx context.Context, conn *iam.Client, identifier string) ([]awstypes.Tag, error) {
output, err := conn.ListInstanceProfileTags(ctx, &iam.ListInstanceProfileTagsInput{
InstanceProfileName: aws.String(identifier),
})
if err != nil {
return nil, err
}
return output.Tags, nil
}
type invalidParameterValueError struct {
error
}
func (e *invalidParameterValueError) ErrorMessage() string {
if e == nil || e.error == nil {
return ""
}
return e.Error()
}