-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.yml
308 lines (305 loc) · 11.7 KB
/
stack.yml
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
AWSTemplateFormatVersion: '2010-09-09'
Description: State Machine that checks all EC2 instances registered with SSM and sends alerts to MS Teams if actions are needed
Parameters:
MicrosoftTeamsWebhookURL:
Description: Microsoft Teams secret for the webhook URL
Type: String
Resources:
EventBridgeRetrieveConnectionCredentialsScopedAccessPolicy:
Type: "AWS::IAM::ManagedPolicy"
Properties:
ManagedPolicyName: "EventBridgeRetrieveConnectionCredentialsScopedAccessPolicy"
Description: "Allow AWS Step Functions to make an HTTP call with Connection credentials on your behalf."
PolicyDocument:
Version: "2012-10-17"
Statement:
- Resource:
- !Sub "arn:aws:events:${AWS::Region}:${AWS::AccountId}:connection/${EventBridgeAPIConnection}/*"
Action:
- "events:RetrieveConnectionCredentials"
Effect: "Allow"
Sid: "RetrieveConnectionCredentials"
- Resource:
- !Sub "arn:aws:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:events!connection/${EventBridgeAPIConnection}/*"
Action:
- "secretsmanager:GetSecretValue"
- "secretsmanager:DescribeSecret"
Effect: "Allow"
Sid: "GetAndDescribeSecretValue"
IAMManagedPolicyStepFunctionsInvokeHttpEndpointScopedAccess:
Type: "AWS::IAM::ManagedPolicy"
Properties:
ManagedPolicyName: StepFunctionsInvokeHttpEndpointScopedAccessPolicy
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Sid: InvokeHttpEndpoint1
Action:
- states:InvokeHTTPEndpoint
Resource:
- !Sub "arn:aws:states:${AWS::Region}:${AWS::AccountId}:stateMachine:*"
Condition:
StringEquals:
states:HTTPEndpoint:
- !Sub ${MicrosoftTeamsWebhookURL}
states:HTTPMethod:
- POST
IAMManagedPolicyEventBridgeInvokeStepFunctions:
Type: "AWS::IAM::ManagedPolicy"
Properties:
ManagedPolicyName: "IAMManagedPolicyEventBridgeInvokeStepFunctions"
Description: ""
PolicyDocument:
Version: "2012-10-17"
Statement:
- Resource:
- !Sub "arn:aws:states:${AWS::Region}:${AWS::AccountId}:stateMachine:*"
Action:
- "states:StartExecution"
Effect: "Allow"
IAMRoleEventBridgeInvokeStepFunctions:
Type: "AWS::IAM::Role"
Properties:
ManagedPolicyArns:
- Ref: "IAMManagedPolicyEventBridgeInvokeStepFunctions"
MaxSessionDuration: 3600
RoleName: "IAMRoleEventBridgeInvokeStepFunctions-CF"
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Action: "sts:AssumeRole"
Effect: "Allow"
Principal:
Service: "events.amazonaws.com"
SecretEventBridgeAPIConnection:
Type: AWS::SecretsManager::Secret
Properties:
Description: A random secret needed to create the AWS::Events::Connection resource
GenerateSecretString:
SecretStringTemplate: '{"username": "notused"}'
GenerateStringKey: "password"
PasswordLength: 16
ExcludeCharacters: '"@/\'
Name: EventBridgeAPIConnection
EventBridgeAPIConnection:
Type: AWS::Events::Connection
Properties:
AuthorizationType: API_KEY
AuthParameters:
ApiKeyAuthParameters:
ApiKeyName: notused
ApiKeyValue: !Ref SecretEventBridgeAPIConnection
Description: Authentication for HTTP endpoints in Step Functions is handled using an EventBridge Connection resource
Name: StepFunctionEventBridgeAPIConnection
StepFunctionsStateMachine:
Type: "AWS::StepFunctions::StateMachine"
Properties:
DefinitionString: |-
{
"Comment": "List EC2 instances with ComplianceType=Patch, filter NON_COMPLIANT instances, and retrieve their names and IDs",
"StartAt": "DescribeInstances",
"States": {
"DescribeInstances": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:ec2:describeInstances",
"Parameters": {
"Filters": [
{
"Name": "instance-state-name",
"Values": [
"running"
]
}
]
},
"ResultPath": "$.Instances",
"Next": "ExtractInstanceIDs"
},
"ExtractInstanceIDs": {
"Type": "Pass",
"Parameters": {
"InstanceIDs.$": "$.Instances.Reservations[*].Instances[*].InstanceId"
},
"ResultPath": "$",
"Next": "FetchInstanceComplianceData"
},
"FetchInstanceComplianceData": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:ssm:listComplianceItems",
"Parameters": {
"ResourceIds.$": "$.InstanceIDs",
"Filters": [
{
"Key": "ComplianceType",
"Values": [
"Patch"
]
},
{
"Key": "Status",
"Values": [
"NON_COMPLIANT"
]
}
],
"MaxResults": 50
},
"ResultPath": "$.ComplianceData",
"Next": "FilterNONCOMPLIANTInstances"
},
"FilterNONCOMPLIANTInstances": {
"Type": "Pass",
"Parameters": {
"NONCOMPLIANTInstanceIDs.$": "$.ComplianceData.ComplianceItems[*].ResourceId"
},
"ResultPath": "$",
"Next": "CalculateArrayLength"
},
"CalculateArrayLength": {
"Type": "Pass",
"Parameters": {
"ArrayLength": {
"Fn::Size": [
"$.NONCOMPLIANTInstanceIDs"
]
}
},
"ResultPath": "$",
"Next": "CheckIfInstancesFound"
},
"CheckIfInstancesFound": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.ArrayLength",
"NumericGreaterThan": 0,
"Next": "DescribeTagsForFilteredInstances"
}
],
"Default": "EndState"
},
"DescribeTagsForFilteredInstances": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:ec2:describeTags",
"Parameters": {
"Filters": [
{
"Name": "resource-type",
"Values": [
"instance"
]
},
{
"Name": "resource-id",
"Values.$": "$.NONCOMPLIANTInstanceIDs"
},
{
"Name": "key",
"Values": [
"Name"
]
}
]
},
"ResultPath": "$.InstanceTags",
"Next": "PrepareNonCompliantInstanceList"
},
"PrepareNonCompliantInstanceList": {
"Type": "Pass",
"InputPath": "$.InstanceTags",
"ResultPath": "$",
"Parameters": {
"Instances": {
"Names.$": "$.Tags[*].Value",
"Ids.$": "$.Tags[*].ResourceId"
}
},
"Next": "CallThirdPartyAPI"
},
"CallThirdPartyAPI": {
"Type": "Task",
"Resource": "arn:aws:states:::http:invoke",
"Parameters": {
"Method": "POST",
"ApiEndpoint": "${MicrosoftTeamsWebhookURL}",
"Authentication": {
"ConnectionArn": "${EventBridgeConnectionArn}"
},
"Headers": {
"Content-Type": "application/json"
},
"RequestBody": {
"text.$": "States.Format('The next EC2 instances have the Non-Compliant status in SSM and might need to be rebooted in order to have all patches installed:\n{}', States.JsonToString($.Instances))"
}
},
"Retry": [
{
"ErrorEquals": [
"States.ALL"
],
"IntervalSeconds": 1,
"MaxAttempts": 3,
"BackoffRate": 2,
"JitterStrategy": "FULL"
}
],
"End": true
},
"EndState": {
"Type": "Succeed"
}
}
}
DefinitionSubstitutions:
MicrosoftTeamsWebhookURL: !Ref MicrosoftTeamsWebhookURL
EventBridgeConnectionArn: !GetAtt EventBridgeAPIConnection.Arn
LoggingConfiguration:
IncludeExecutionData: false
Level: "OFF"
StateMachineName: "SSMPatchingAlerts"
RoleArn:
Fn::GetAtt:
- "IAMRoleStepFunctionsSSMAlerts"
- "Arn"
Tags: []
StateMachineType: "STANDARD"
TracingConfiguration:
Enabled: false
IAMRoleStepFunctionsSSMAlerts:
Properties:
AssumeRolePolicyDocument:
Statement:
- Action: "sts:AssumeRole"
Condition:
ArnLike:
"aws:SourceArn": !Sub "arn:aws:states:${AWS::Region}:${AWS::AccountId}:stateMachine:*"
StringEquals:
"aws:SourceAccount": !Sub "${AWS::AccountId}"
Effect: Allow
Principal:
Service: states.amazonaws.com
Sid: TrustPolicy1
Version: 2012-10-17
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
- "arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess"
- !Ref IAMManagedPolicyStepFunctionsInvokeHttpEndpointScopedAccess
- !Ref EventBridgeRetrieveConnectionCredentialsScopedAccessPolicy
MaxSessionDuration: 3600
RoleName: IAMRoleStepFunctionsSSMAlerts-CF
Type: "AWS::IAM::Role"
EventsRuleStepFunctionSSMAlerts:
Properties:
Description: Step Functions trigger event
EventBusName: default
Name: StepFunctionSSMAlertsCF
ScheduleExpression: cron(0 8 ? * 2 *)
State: ENABLED
Targets:
- Arn: !GetAtt
- StepFunctionsStateMachine
- Arn
Id: state-machine
RoleArn: !GetAtt IAMRoleEventBridgeInvokeStepFunctions.Arn
Type: "AWS::Events::Rule"