-
Notifications
You must be signed in to change notification settings - Fork 9
/
Scheduled-Patch-Automation.yaml
339 lines (332 loc) · 15.2 KB
/
Scheduled-Patch-Automation.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
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
# *
# * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# * SPDX-License-Identifier: MIT-0
# *
# * 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.
# *
# * 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.
# *
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS CloudFormation template to create a scheduled multi-account and multi-Region patching operation using Amazon EventBridge, AWS Lambda, and AWS Systems Manager Automation.
Parameters:
EventBridgeRuleSchedule:
Type: String
Description: >-
The cron or rate expression to use for the EventBridge rule. For example: cron(0 02 ? * TUE *). Important: The time zone used is UTC. For more information, see https://docs.aws.amazon.com/eventbridge/latest/userguide/scheduled-events.html.
ExecutionRoleName:
Type: String
Default: AWS-SystemsManager-AutomationExecutionRole
Description: >-
The Automation execution role to be assumed in target accounts during multi-account and multi-Region Automation patching operations.
ExistingAutomationAdministrationRole:
Type: String
Description: >-
(Optional) The IAM role ARN of an existing Automation Administration role which has permissions to invoke multi-account and multi-Region Automation workflows.
MaximumConcurrency:
Type: String
Default: 10%
Description: >-
Specify the number or percentage of targets on which to execute the task at the same time. You can specify a number, such as 10, or a percentage, such as 10%. The default value is 10%.
MaximumErrors:
Type: String
Default: 10%
Description: >-
The number of errors that are allowed before the system stops initiating the automation on additional targets. You can specify either an absolute number of errors, for example 10, or a percentage of the target set, for example 10%. The default value is 10%.
RunPatchBaselineOperation:
Type: String
Default: Scan
AllowedValues:
- Scan
- Install
Description: >-
(Required) The update or configuration to perform on the instance. The Scan operation checks if patches specified in the patch baseline are installed on the instance. The Install operation installs patches missing from the baseline.
RunPatchBaselineRebootOption:
Type: String
Default: NoReboot
AllowedValues:
- RebootIfNeeded
- NoReboot
Description: >-
(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.
RunPatchBaselineInstallOverrideList:
Type: String
Default: ''
AllowedPattern: '(^$)|^https://.+$|^s3://([^/]+)/(.*?([^/]+))$'
Description: >-
(Optional) An https URL or an Amazon S3 path-style URL to the list of patches to be installed. This patch installation list overrides the patches specified by the default patch baseline.
ResourceGroupName:
Type: String
Description: >-
Enter a resource group that includes the resources you want to target. Important: The Resource Group name is case sensitive.
TargetAccounts:
Type: String
Description: >-
Comma separated list of AWS Account Ids for the target account(s).
TargetLocationMaxConcurrency:
Type: String
Default: '1'
Description: >-
Specify the number or percentage of locations (account-Region pairs) on which to execute the task at the same time. You can specify a number, such as 10, or a percentage, such as 10%. The default value is 1.
TargetLocationMaxErrors:
Type: String
Default: '1'
Description: >-
Specify an error threshold which will stop the task after the task fails on a specific number or percentage of locations. You can specify either an absolute number of errors, for example 10, or a percentage of the locations, for example 10%. The default value is 1.
TargetRegionIds:
Type: String
Description: >-
Comma separated list of AWS Regions to target. For example: us-east-1,ap-south-1.
Conditions:
CreateAutomationAdministrationRoleCondition:
Fn::Equals:
- Ref: ExistingAutomationAdministrationRole
- ''
Resources:
EventBridgeRule:
Type: AWS::Events::Rule
Properties:
Description: EventBridge rule created for scheduled multi-account and multi-Region Automation patching using AWS Lambda and AWS Systems Manager Automation
Name: Schedule-Trigger-for-Lambda-MultiAccountPatchingBlog
ScheduleExpression:
Ref: EventBridgeRuleSchedule
State: ENABLED
Targets:
- Arn:
Fn::GetAtt:
- MultiAccountPatchingBlogLambdaFunction
- Arn
Id: MultiAccountPatchingBlog
PermissionForEventsToInvokeLambda:
Type: AWS::Lambda::Permission
Properties:
FunctionName:
Ref: MultiAccountPatchingBlogLambdaFunction
Action: lambda:InvokeFunction
Principal: events.amazonaws.com
SourceArn:
Fn::GetAtt:
- EventBridgeRule
- Arn
AWSLambdaSSMMultiAccountPatchingBlogRole:
Type: AWS::IAM::Role
Properties:
RoleName: AWS-Lambda-SSM-MultiAccountPatchingBlogRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: "/"
Policies:
- PolicyName: AWSLambdaSSMMultiAccountPatchingBlogPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ssm:StartAutomationExecution
Resource:
- Fn::Sub: arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:automation-definition/${AutomationDocumentMamrRunPatchBaseline}:$DEFAULT
- Action: iam:PassRole
Resource:
Fn::Sub: arn:${AWS::Partition}:iam::${AWS::AccountId}:role/AWS-SystemsManager-AutomationAdministrationRole
Effect: Allow
- Action: logs:CreateLogGroup
Resource:
Fn::Sub: arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:*
Effect: Allow
- Action:
- logs:CreateLogStream
- logs:PutLogEvents
Resource:
Fn::Sub: arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/MultiAccountPatchingBlog:*
Effect: Allow
MultiAccountPatchingBlogLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: !Sub |
import boto3
import os
import string
import uuid
client = boto3.client('ssm')
def handler(event,context):
TargetAccounts=os.environ['TargetAccounts']
b = str(TargetAccounts)
TargetAccountsArray = b.split(",")
TargetRegionIds=os.environ['TargetRegionIds']
b = str(TargetRegionIds)
TargetRegionIdsArray = b.split(",")
RunPatchBaselineOperation=os.environ['RunPatchBaselineOperation']
RunPatchBaselineRebootOption=os.environ['RunPatchBaselineRebootOption']
RunPatchBaselineInstallOverrideList=os.environ['RunPatchBaselineInstallOverrideList']
ResourceGroupName=os.environ['ResourceGroupName']
MaximumConcurrency=os.environ['MaximumConcurrency']
MaximumErrors=os.environ['MaximumErrors']
TargetLocationMaxConcurrency=os.environ['TargetLocationMaxConcurrency']
TargetLocationMaxErrors=os.environ['TargetLocationMaxErrors']
ExecutionRoleName=os.environ['ExecutionRoleName']
MasterAccountID=os.environ['MasterAccountID']
AutomationDocumentMamrRunPatchBaseline=os.environ['AutomationDocumentMamrRunPatchBaseline']
if len(RunPatchBaselineInstallOverrideList) > 0:
response = client.start_automation_execution(
DocumentName=f'{AutomationDocumentMamrRunPatchBaseline}',
Parameters={
'AutomationAssumeRole':[f'arn:aws:iam::{MasterAccountID}:role/AWS-SystemsManager-AutomationAdministrationRole'] ,
'Operation' : [f'{RunPatchBaselineOperation}'] ,
'RebootOption' : [f'{RunPatchBaselineRebootOption}'] ,
'InstallOverrideList' : [f'{RunPatchBaselineInstallOverrideList}'] ,
'SnapshotId' : [str(uuid.uuid4())]
},
TargetLocations=[
{
'Accounts': TargetAccountsArray,
'Regions': TargetRegionIdsArray,
'TargetLocationMaxConcurrency': f'{TargetLocationMaxConcurrency}',
'TargetLocationMaxErrors': f'{TargetLocationMaxErrors}',
'ExecutionRoleName': f'{ExecutionRoleName}'
}
]
)
else:
response = client.start_automation_execution(
DocumentName=f'{AutomationDocumentMamrRunPatchBaseline}',
Parameters={
'AutomationAssumeRole':[f'arn:aws:iam::{MasterAccountID}:role/AWS-SystemsManager-AutomationAdministrationRole'] ,
'Operation' : [f'{RunPatchBaselineOperation}'] ,
'RebootOption' : [f'{RunPatchBaselineRebootOption}'] ,
'SnapshotId' : [str(uuid.uuid4())]
},
TargetLocations=[
{
'Accounts': TargetAccountsArray,
'Regions': TargetRegionIdsArray,
'TargetLocationMaxConcurrency': f'{TargetLocationMaxConcurrency}',
'TargetLocationMaxErrors': f'{TargetLocationMaxErrors}',
'ExecutionRoleName': f'{ExecutionRoleName}'
}
]
)
print(response)
Environment:
Variables:
TargetAccounts: !Ref TargetAccounts
TargetRegionIds: !Ref TargetRegionIds
RunPatchBaselineOperation: !Ref RunPatchBaselineOperation
RunPatchBaselineRebootOption: !Ref RunPatchBaselineRebootOption
RunPatchBaselineInstallOverrideList: !Ref RunPatchBaselineInstallOverrideList
ResourceGroupName: !Ref ResourceGroupName
MaximumConcurrency: !Ref MaximumConcurrency
MaximumErrors: !Ref MaximumErrors
TargetLocationMaxConcurrency: !Ref TargetLocationMaxConcurrency
TargetLocationMaxErrors: !Ref TargetLocationMaxErrors
ExecutionRoleName: !Ref ExecutionRoleName
MasterAccountID: !Sub ${AWS::AccountId}
AutomationDocumentMamrRunPatchBaseline: !Ref AutomationDocumentMamrRunPatchBaseline
FunctionName: MultiAccountPatchingBlog
Handler: index.handler
Role: !GetAtt AWSLambdaSSMMultiAccountPatchingBlogRole.Arn
Runtime: python3.7
AutomationAdministrationServiceRole:
Type: AWS::IAM::Role
Condition: CreateAutomationAdministrationRoleCondition
Properties:
RoleName: AWS-SystemsManager-AutomationAdministrationRole
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: ssm.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: AssumeRole-AWSSystemsManagerAutomationExecutionRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- sts:AssumeRole
Resource:
Fn::Sub: arn:${AWS::Partition}:iam::*:role/AWS-SystemsManager-AutomationExecutionRole
- Effect: Allow
Action:
- organizations:ListAccountsForParent
Resource:
- "*"
AutomationDocumentMamrRunPatchBaseline:
Type: AWS::SSM::Document
Properties:
Name: Automation-RunPatchBaseline
DocumentType: Automation
Content:
description: >-
**Description**
This document runs the Command document ```AWS-RunPatchBaseline``` on the specified instances.
schemaVersion: '0.3'
assumeRole: '{{ AutomationAssumeRole }}'
parameters:
AutomationAssumeRole:
type: String
description: The ARN of the Automation service role to assume.
Operation:
type: String
default: Scan
description: >-
(Required) The update or configuration to perform on the instance. The
system checks if patches specified in the patch baseline are installed on
the instance. The install operation installs patches missing from the
baseline.
RebootOption:
type: String
default: RebootIfNeeded
description: >-
(Optional) Reboot behavior after a patch Install operation. If you choose
NoReboot and patches are installed, the instance is marked as non-compliant
until a subsequent reboot and scan.
InstallOverrideList:
type: String
default: ""
description: >-
(Optional) An https URL or an Amazon S3 path-style URL to the list of patches to be installed. This patch installation list overrides the patches specified by the default patch baseline.
SnapshotId:
type: String
default: ""
description: >-
(Optional) The snapshot ID to use to retrieve a patch baseline snapshot.
mainSteps:
- name: runPatchBaseline
action: 'aws:runCommand'
timeoutSeconds: 7200
onFailure: Abort
inputs:
DocumentName: AWS-RunPatchBaseline
Targets:
- Key: 'resource-groups:Name'
Values:
- !Ref ResourceGroupName
Parameters:
Operation: '{{ Operation }}'
RebootOption: '{{ RebootOption }}'
SnapshotId: '{{ SnapshotId }}'
InstallOverrideList: '{{ InstallOverrideList }}'
MaxConcurrency: !Ref MaximumConcurrency
MaxErrors: !Ref MaximumErrors
description: >-
This command runs the Command document ```AWS-RunPatchBaseline``` on the
specified instances.