-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAWSIdempotentCreateServiceLinkedRole.yaml
242 lines (222 loc) · 8.22 KB
/
AWSIdempotentCreateServiceLinkedRole.yaml
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
# MIT License - No Attribution
#
# Copyright (c) 2019 Jeffrey S. Levine
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# AWSIdempotentCreateServiceLinkedRole.yaml - Create a service-linked
# role if it doesn't already exist.
#
# See the Lamba function code for more details.
---
AWSTemplateFormatVersion: '2010-09-09'
Description: Create service-linked role if it doesn't already exist
Resources:
# IdempotentCreateServiceLinkedRoleExecutionRole - The AWS Lambda execution
# role for the custom CloudFormation resources that are used to create the
# service-linked role.
#
# It must include permissions for all the API calls made by the Lambda
# function. This typically includes the APIsneeded to write to Amazon
# CloudWatch Logs. In this case, since we are using a custom resource to
# work with service-linked role, it must include the IAM permissions to
# call the GetRole and CreateServiceLinkedRole APIs.
IdempotentCreateServiceLinkedRoleExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: '/'
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- iam:CreateServiceLinkedRole
- iam:GetRole
Resource: '*'
# IdempotentCreateServiceLinkedRoleFunction
#
# This Lambda function backs a custome CloudFormation resources and creates an
# AWS service-linked role if it doesn't already exist.
#
# The function accepts the following parameters that are passed as properties:
#
# (1) The AWS service name (e.g. 'inspector.amazonaws.com')
#
# The function then does the following:
#
# (1) Looks up the corresponding default IAM role name associated with the
# ervice. If it finds the role, it sets the resource response Arn and
# RoleId values.
#
# (2) If the service-linked role does not exist, create it. If the creation is
# successful, return the Arn and RoleId in the resource response.
#
# (3) If the creation of the service-linked role fails report an error.
#
# Caveats:
#
# (1) This function does not pass the ACID test. If multiple copies of this
# function are running with the same AWS service name in the same region
# at the same time, there could be some conflicts.
#
# (2) The function does not support the 'suffix' extension that allows
# multiple service-linked roles to exist for the same service.
# That is actually why this code was written.
#
# (3) The function ignores deletes and updates.
IdempotentCreateServiceLinkedRoleFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
MemorySize: 128
Role: !GetAtt IdempotentCreateServiceLinkedRoleExecutionRole.Arn
Runtime: 'python3.6'
Timeout: 30
Code:
ZipFile: |
import json
import boto3
import cfnresponse
import string
from botocore.exceptions import ClientError
def handler(event, context):
serviceDictionary = {
'inspector.amazonaws.com': 'AWSServiceRoleForAmazonInspector'
}
print('event =', json.dumps(event))
if event['RequestType'] in ['Delete', 'Update']:
responseData = {}
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
responseData
)
return
client = boto3.client('iam')
awsServiceName = event['ResourceProperties']['AWSServiceName']
if not awsServiceName in serviceDictionary:
responseData = {}
cfnresponse.send(
event,
context,
cfnresponse.FAILED,
responseData
)
return
try:
response = client.get_role(
RoleName = serviceDictionary[awsServiceName]
)
roleAlreadyExists = True
except:
roleAlreadyExists = False
if roleAlreadyExists:
print(
'The service-linked role for service',
awsServiceName,
'already exists. The Arn and RoleId will be returned.'
)
responseData = {
'Arn': response['Role']['Arn'],
'RoleId': response['Role']['RoleId']
}
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
responseData
)
return
try:
response = client.create_service_linked_role(
AWSServiceName=awsServiceName
)
createRoleSucceeded=True
except ClientError as e:
createRoleSucceeded=False
if createRoleSucceeded:
print(
'The service-linked role for service',
awsServiceName,
'has been created. The Arn and RoleId will be returned.'
)
responseData = {
'Arn': response['Role']['Arn'],
'RoleId': response['Role']['RoleId']
}
cfnresponse.send(
event,
context,
cfnresponse.SUCCESS,
responseData
)
else:
print(
'Unable to create the service-linked role for service',
awsServiceName,
'.'
)
print('exception =', json.dumps(e.response))
responseData = {}
cfnresponse.send(
event,
context,
cfnresponse.FAILED,
responseData
)
IdempotentCreateServiceLinkedRole1:
Type: Custom::IdempotentCreateServiceLinkedRole1
DeletionPolicy: Retain
Properties:
ServiceToken: !GetAtt IdempotentCreateServiceLinkedRoleFunction.Arn
AWSServiceName: 'inspector.amazonaws.com'
IdempotentCreateServiceLinkedRole2:
Type: Custom::IdempotentCreateServiceLinkedRole2
DeletionPolicy: Retain
DependsOn: IdempotentCreateServiceLinkedRole1
Properties:
ServiceToken: !GetAtt IdempotentCreateServiceLinkedRoleFunction.Arn
AWSServiceName: 'inspector.amazonaws.com'
Outputs:
Role1Arn:
Description: Role 1 ARN
Value: !GetAtt IdempotentCreateServiceLinkedRole1.Arn
Role1RoleId:
Description: Role 1 RoleId
Value: !GetAtt IdempotentCreateServiceLinkedRole1.RoleId
Role2Arn:
Description: Role 2 ARN
Value: !GetAtt IdempotentCreateServiceLinkedRole2.Arn
Role2RoleId:
Description: Role 2 RoleId
Value: !GetAtt IdempotentCreateServiceLinkedRole2.RoleId