-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
iamrole.go
324 lines (268 loc) · 9.29 KB
/
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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package awstasks
import (
"fmt"
"encoding/json"
"net/url"
"reflect"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/iam"
"k8s.io/klog/v2"
"k8s.io/kops/pkg/diff"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
)
// +kops:fitask
type IAMRole struct {
ID *string
Lifecycle *fi.Lifecycle
Name *string
RolePolicyDocument fi.Resource // "inline" IAM policy
PermissionsBoundary *string
Tags map[string]string
// ExportWithId will expose the name & ARN for reuse as part of a larger system. Only supported by terraform currently.
ExportWithID *string
}
var _ fi.CompareWithID = &IAMRole{}
func (e *IAMRole) CompareWithID() *string {
return e.ID
}
func (e *IAMRole) Find(c *fi.Context) (*IAMRole, error) {
cloud := c.Cloud.(awsup.AWSCloud)
request := &iam.GetRoleInput{RoleName: e.Name}
response, err := cloud.IAM().GetRole(request)
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() == "NoSuchEntity" {
return nil, nil
}
}
if err != nil {
return nil, fmt.Errorf("error getting role: %v", err)
}
r := response.Role
actual := &IAMRole{}
actual.ID = r.RoleId
actual.Name = r.RoleName
if r.PermissionsBoundary != nil {
actual.PermissionsBoundary = r.PermissionsBoundary.PermissionsBoundaryArn
}
if r.AssumeRolePolicyDocument != nil {
// The AssumeRolePolicyDocument is URI encoded (?)
actualPolicy := *r.AssumeRolePolicyDocument
actualPolicy, err = url.QueryUnescape(actualPolicy)
if err != nil {
return nil, fmt.Errorf("error parsing AssumeRolePolicyDocument for IAMRole %s: %v", *e.Name, err)
}
// The RolePolicyDocument is reformatted by AWS
// We parse both as JSON; if the json forms are equal we pretend the actual value is the expected value
if e.RolePolicyDocument != nil {
expectedPolicy, err := fi.ResourceAsString(e.RolePolicyDocument)
if err != nil {
return nil, fmt.Errorf("error reading expected RolePolicyDocument for IAMRole %q: %v", aws.StringValue(e.Name), err)
}
expectedJson := make(map[string]interface{})
err = json.Unmarshal([]byte(expectedPolicy), &expectedJson)
if err != nil {
return nil, fmt.Errorf("error parsing expected RolePolicyDocument for IAMRole %q: %v", aws.StringValue(e.Name), err)
}
actualJson := make(map[string]interface{})
err = json.Unmarshal([]byte(actualPolicy), &actualJson)
if err != nil {
return nil, fmt.Errorf("error parsing actual RolePolicyDocument for IAMRole %q: %v", aws.StringValue(e.Name), err)
}
if reflect.DeepEqual(actualJson, expectedJson) {
klog.V(2).Infof("actual RolePolicyDocument was json-equal to expected; returning expected value")
actualPolicy = expectedPolicy
}
}
actual.RolePolicyDocument = fi.NewStringResource(actualPolicy)
}
actual.Tags = mapIAMTagsToMap(r.Tags)
klog.V(2).Infof("found matching IAMRole %q", aws.StringValue(actual.ID))
e.ID = actual.ID
// Avoid spurious changes
actual.ExportWithID = e.ExportWithID
actual.Lifecycle = e.Lifecycle
return actual, nil
}
func (e *IAMRole) Run(c *fi.Context) error {
return fi.DefaultDeltaRunMethod(e, c)
}
func (s *IAMRole) CheckChanges(a, e, changes *IAMRole) error {
if a != nil {
if e.Name == nil {
return fi.RequiredField("Name")
}
} else {
if changes.Name == nil {
return fi.CannotChangeField("Name")
}
}
return nil
}
func (_ *IAMRole) RenderAWS(t *awsup.AWSAPITarget, a, e, changes *IAMRole) error {
policy, err := fi.ResourceAsString(e.RolePolicyDocument)
if err != nil {
return fmt.Errorf("error rendering RolePolicyDocument: %v", err)
}
if a == nil {
klog.V(2).Infof("Creating IAMRole with Name:%q", *e.Name)
request := &iam.CreateRoleInput{}
request.AssumeRolePolicyDocument = aws.String(policy)
request.RoleName = e.Name
request.Tags = mapToIAMTags(e.Tags)
if e.PermissionsBoundary != nil {
request.PermissionsBoundary = e.PermissionsBoundary
}
response, err := t.Cloud.IAM().CreateRole(request)
if err != nil {
klog.V(2).Infof("IAMRole policy: %s", policy)
return fmt.Errorf("error creating IAMRole: %v", err)
}
e.ID = response.Role.RoleId
} else {
if changes.RolePolicyDocument != nil {
klog.V(2).Infof("Updating IAMRole AssumeRolePolicy %q", *e.Name)
var err error
actualPolicy := ""
if a.RolePolicyDocument != nil {
actualPolicy, err = fi.ResourceAsString(a.RolePolicyDocument)
if err != nil {
return fmt.Errorf("error reading actual policy document: %v", err)
}
}
if actualPolicy == policy {
klog.Warning("Policies were actually the same")
} else {
d := diff.FormatDiff(actualPolicy, policy)
klog.V(2).Infof("diff: %s", d)
}
request := &iam.UpdateAssumeRolePolicyInput{}
request.PolicyDocument = aws.String(policy)
request.RoleName = e.Name
_, err = t.Cloud.IAM().UpdateAssumeRolePolicy(request)
if err != nil {
return fmt.Errorf("error updating IAMRole: %v", err)
}
}
if changes.PermissionsBoundary != nil {
klog.V(2).Infof("Updating IAMRole PermissionsBoundary %q", *e.Name)
var err error
if e.PermissionsBoundary == nil {
request := &iam.DeleteRolePermissionsBoundaryInput{}
request.RoleName = e.Name
_, err = t.Cloud.IAM().DeleteRolePermissionsBoundary(request)
if err != nil {
return fmt.Errorf("error updating IAMRole: %v", err)
}
} else {
request := &iam.PutRolePermissionsBoundaryInput{}
request.RoleName = e.Name
request.PermissionsBoundary = e.PermissionsBoundary
_, err = t.Cloud.IAM().PutRolePermissionsBoundary(request)
if err != nil {
return fmt.Errorf("error updating IAMRole: %v", err)
}
}
}
if changes.Tags != nil {
if len(a.Tags) > 0 {
existingTagKeys := make([]*string, 0)
for k := range a.Tags {
existingTagKeys = append(existingTagKeys, &k)
}
untagRequest := &iam.UntagRoleInput{
RoleName: e.Name,
TagKeys: existingTagKeys,
}
_, err = t.Cloud.IAM().UntagRole(untagRequest)
if err != nil {
return fmt.Errorf("error untagging IAMRole: %v", err)
}
}
if len(e.Tags) > 0 {
tagRequest := &iam.TagRoleInput{
RoleName: e.Name,
Tags: mapToIAMTags(e.Tags),
}
_, err = t.Cloud.IAM().TagRole(tagRequest)
if err != nil {
return fmt.Errorf("error tagging IAMRole: %v", err)
}
}
}
}
// TODO: Should we use path as our tag?
return nil // No tags in IAM
}
type terraformIAMRole struct {
Name *string `json:"name" cty:"name"`
AssumeRolePolicy *terraform.Literal `json:"assume_role_policy" cty:"assume_role_policy"`
PermissionsBoundary *string `json:"permissions_boundary,omitempty" cty:"permissions_boundary"`
Tags map[string]string `json:"tags,omitempty" cty:"tags"`
}
func (_ *IAMRole) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *IAMRole) error {
policy, err := t.AddFile("aws_iam_role", *e.Name, "policy", e.RolePolicyDocument, false)
if err != nil {
return fmt.Errorf("error rendering RolePolicyDocument: %v", err)
}
tf := &terraformIAMRole{
Name: e.Name,
AssumeRolePolicy: policy,
Tags: e.Tags,
}
if e.PermissionsBoundary != nil {
tf.PermissionsBoundary = e.PermissionsBoundary
}
if fi.StringValue(e.ExportWithID) != "" {
t.AddOutputVariable(*e.ExportWithID+"_role_arn", terraform.LiteralProperty("aws_iam_role", *e.Name, "arn"))
t.AddOutputVariable(*e.ExportWithID+"_role_name", e.TerraformLink())
}
return t.RenderResource("aws_iam_role", *e.Name, tf)
}
func (e *IAMRole) TerraformLink() *terraform.Literal {
return terraform.LiteralProperty("aws_iam_role", *e.Name, "name")
}
type cloudformationIAMRole struct {
RoleName *string `json:"RoleName"`
AssumeRolePolicyDocument map[string]interface{}
PermissionsBoundary *string `json:"PermissionsBoundary,omitempty"`
Tags []cloudformationTag `json:"Tags,omitempty"`
}
func (_ *IAMRole) RenderCloudformation(t *cloudformation.CloudformationTarget, a, e, changes *IAMRole) error {
jsonString, err := fi.ResourceAsBytes(e.RolePolicyDocument)
if err != nil {
return err
}
data := make(map[string]interface{})
err = json.Unmarshal(jsonString, &data)
if err != nil {
return fmt.Errorf("error parsing RolePolicyDocument: %v", err)
}
cf := &cloudformationIAMRole{
RoleName: e.Name,
AssumeRolePolicyDocument: data,
Tags: buildCloudformationTags(e.Tags),
}
if e.PermissionsBoundary != nil {
cf.PermissionsBoundary = e.PermissionsBoundary
}
return t.RenderResource("AWS::IAM::Role", *e.Name, cf)
}
func (e *IAMRole) CloudformationLink() *cloudformation.Literal {
return cloudformation.Ref("AWS::IAM::Role", *e.Name)
}