-
Notifications
You must be signed in to change notification settings - Fork 2
/
SAPConfgHltCloudFormation.yml
351 lines (324 loc) · 13.2 KB
/
SAPConfgHltCloudFormation.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
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
AWSTemplateFormatVersion: 2010-09-09
Description: >-
CloudFormation template (SO9493) for automating SAP Configuration Health Checks on AWS (SO9493). This template provisions the necessary AWS resources.
Parameters:
ExistingS3BucketName:
Type: String
Description: 'Enter the name of the S3 bucket created specifically for this solution.'
Resources:
SAPConfgHltRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Principal:
Service: 'lambda.amazonaws.com'
Action: 'sts:AssumeRole'
Policies:
- PolicyName: 'SAPConfgHltFullAccessPolicy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'ssm:SendCommand'
- 'ssm:GetCommandInvocation'
- 'ssm:ListCommands'
- 's3:GetObject'
- 's3:CopyObject'
- 's3:PutObject'
- 's3:ListBucket'
- 's3:GetBucketNotification'
- 's3:PutBucketNotification'
- 'dynamodb:GetItem'
- 'dynamodb:PutItem'
- 'dynamodb:Scan'
- 'dynamodb:UpdateItem'
- 'dynamodb:BatchWriteItem'
- 'dynamodb:BatchGetItem'
- 'dynamodb:Query'
- 'dynamodb:DeleteItem'
- 'lambda:InvokeFunction'
- 'athena:CreateTable'
- 'athena:StartQueryExecution'
- 'athena:GetQueryExecution'
- 'athena:GetQueryResults'
- 'ec2:Describe*'
- 'ses:SendEmail'
- 'ses:SendRawEmail'
Resource: '*'
- Effect: 'Allow'
Action:
- 'dynamodb:GetItem'
- 'dynamodb:PutItem'
- 'dynamodb:Scan'
- 'dynamodb:UpdateItem'
- 'dynamodb:BatchWriteItem'
- 'dynamodb:BatchGetItem'
- 'dynamodb:Query'
- 'dynamodb:DeleteItem'
Resource:
- !GetAtt SAPConfgHltChkTable.Arn
- !GetAtt SAPConfgHltChkTableMetaData.Arn
- PolicyName: 'SapRoboLensCloudWatchLogsPolicy'
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: 'Allow'
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
- 'logs:DescribeLogGroups'
Resource: 'arn:aws:logs:*:*:*'
CopyFilesFunction:
Type: 'AWS::Lambda::Function'
DependsOn: SAPConfgHltRole
Properties:
FunctionName: CopySAPGitHubCodeS3
Handler: index.handler
Role: !GetAtt SAPConfgHltRole.Arn
Code:
ZipFile: |
import json
import os
import urllib.request
import zipfile
import io
import boto3
import cfnresponse
print('CopySAPGitHubCodeS3 Loading function')
s3 = boto3.client('s3')
response_data={}
def download_repo_as_zip(git_repo):
# Modified: Changed the URL to directly download the zip file from the public GitHub repository
repo_url = f"https://github.com/{git_repo}/archive/refs/heads/main.zip"
with urllib.request.urlopen(repo_url) as response:
if response.getcode() == 200:
print("Successfully downloaded repository zip file")
return io.BytesIO(response.read())
else:
raise Exception(f"Failed to download repository: {response.getcode()} {response.read().decode()}")
def upload_files_to_s3(zip_content, bucket_name, source_dir, target_dir):
with zipfile.ZipFile(zip_content) as zip_file:
for file_info in zip_file.infolist():
if not file_info.is_dir():
file_path = file_info.filename
parts = file_path.split('/')
if source_dir in parts:
source_index = parts.index(source_dir)
target_path = target_dir + '/'.join(parts[source_index + 1:])
file_data = zip_file.read(file_path)
print(f"Uploading {file_path} to s3://{bucket_name}/{target_path}")
s3.put_object(
Bucket=bucket_name,
Key=target_path,
Body=file_data
)
def handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
s3_bucket = os.environ['TARGET_BUCKET']
git_repo = "aws-solutions-library-samples/guidance-for-automating-sap-configuration-health-checks-on-aws"
source_dir = 'source'
target_dir = 'inventory/'
try:
zip_content = download_repo_as_zip(git_repo)
upload_files_to_s3(zip_content, s3_bucket, source_dir, target_dir)
response_data['Status'] = 'Files copied to S3 successfully.'
cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
except Exception as e:
print(f"Error: {e}")
response_data['Status'] = f"Error: {str(e)}"
cfnresponse.send(event, context, cfnresponse.FAILED, response_data)
Runtime: 'python3.11'
Timeout: 300
Environment:
Variables:
TARGET_BUCKET: !Ref ExistingS3BucketName
InvokeCopyFilesFunction:
Type: 'Custom::InvokeCopyFilesFunction'
Properties:
ServiceToken: !GetAtt CopyFilesFunction.Arn
SAPConfgHltChkGenFunction:
Type: 'AWS::Lambda::Function'
DependsOn: InvokeCopyFilesFunction
Properties:
FunctionName: 'SAPConfgHltChkGen'
Handler: 'main.lambda_handler'
Role: !GetAtt SAPConfgHltRole.Arn
Code:
S3Bucket: !Ref ExistingS3BucketName
S3Key: 'inventory/SAPConfgHltChkGen.zip'
Runtime: 'python3.11'
MemorySize: 200
Timeout: 875 # 14 minutes and 35 seconds
Environment:
Variables:
s3bucket: !Ref ExistingS3BucketName
dydb_chk_tbl: !Ref SAPConfgHltChkTable
dydb_chk_tbl_mdata: !Ref SAPConfgHltChkTableMetaData
LambdaInvokePermission:
Type: 'AWS::Lambda::Permission'
Properties:
FunctionName: !GetAtt SAPConfgHltChkGenFunction.Arn
Action: 'lambda:InvokeFunction'
Principal: s3.amazonaws.com
SourceAccount: !Ref 'AWS::AccountId'
SourceArn: !Sub 'arn:aws:s3:::${ExistingS3BucketName}'
SAPConfgHltChkS3NotificationLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
FunctionName: 'SAPConfgHltChkS3Notification'
Handler: index.lambda_handler
Role: !GetAtt SAPConfgHltRole.Arn
Code:
ZipFile: |
from __future__ import print_function
import json
import boto3
import cfnresponse
SUCCESS = "SUCCESS"
FAILED = "FAILED"
print('Loading function')
s3 = boto3.resource('s3')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
responseData={}
try:
if event['RequestType'] == 'Delete':
print("Request Type:",event['RequestType'])
Bucket=event['ResourceProperties']['Bucket']
delete_notification(Bucket)
print("Sending response to custom resource after Delete")
elif event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
print("Request Type:",event['RequestType'])
LambdaArn=event['ResourceProperties']['LambdaArn']
Bucket=event['ResourceProperties']['Bucket']
add_notification(LambdaArn, Bucket)
responseData={'Bucket':Bucket}
print("Sending response to custom resource")
responseStatus = 'SUCCESS'
except Exception as e:
print('Failed to process:', e)
responseStatus = 'FAILED'
responseData = {'Failure': 'Something bad happened.'}
cfnresponse.send(event, context, responseStatus, responseData, "CustomResourcePhysicalID")
def add_notification(LambdaArn, Bucket):
bucket_notification = s3.BucketNotification(Bucket)
response = bucket_notification.put(
NotificationConfiguration={
'LambdaFunctionConfigurations': [
{
'LambdaFunctionArn': LambdaArn,
'Events': [
's3:ObjectCreated:*'
],
'Filter': {
'Key': {
'FilterRules': [
{
'Name': 'prefix',
'Value': 'inventory/AWSSAPLensRoboInventory.csv'
}
]
}
}
}
]
}
)
print("Put request completed....")
def delete_notification(Bucket):
bucket_notification = s3.BucketNotification(Bucket)
response = bucket_notification.put(
NotificationConfiguration={}
)
print("Delete request completed....")
Runtime: python3.11
Timeout: 50
LambdaTrigger:
Type: 'Custom::LambdaTrigger'
DependsOn: LambdaInvokePermission
Properties:
ServiceToken: !GetAtt SAPConfgHltChkS3NotificationLambdaFunction.Arn
LambdaArn: !GetAtt SAPConfgHltChkGenFunction.Arn
Bucket: !Ref ExistingS3BucketName
SAPConfgHltChkExe:
Type: 'AWS::Lambda::Function'
DependsOn: InvokeCopyFilesFunction
Properties:
FunctionName: 'SAPConfgHltChkExe'
Handler: 'main.lambda_handler'
Role: !GetAtt SAPConfgHltRole.Arn
Code:
S3Bucket: !Ref ExistingS3BucketName
S3Key: 'inventory/SAPConfgHltChkExe.zip'
Runtime: 'python3.11'
MemorySize: 200
Timeout: 875 # 14 minutes and 35 seconds
Environment:
Variables:
s3bucket: !Ref ExistingS3BucketName
dydb_chk_tbl: !Ref SAPConfgHltChkTable
dydb_chk_tbl_mdata: !Ref SAPConfgHltChkTableMetaData
SAPConfgHltChkMain:
Type: 'AWS::Lambda::Function'
DependsOn: InvokeCopyFilesFunction
Properties:
FunctionName: 'SAPConfgHltChkMain'
Handler: 'main.lambda_handler'
Role: !GetAtt SAPConfgHltRole.Arn
Code:
S3Bucket: !Ref ExistingS3BucketName
S3Key: 'inventory/SAPConfgHltChkMain.zip'
Runtime: 'python3.11'
MemorySize: 200
Timeout: 875 # 14 minutes and 35 seconds
Environment:
Variables:
s3bucket: !Ref ExistingS3BucketName
dydb_chk_tbl: !Ref SAPConfgHltChkTable
dydb_chk_tbl_mdata: !Ref SAPConfgHltChkTableMetaData
SAPConfgHltChkTable:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: SAPConfgHltChk
AttributeDefinitions:
- AttributeName: instance_id
AttributeType: S
- AttributeName: compliance_id
AttributeType: S
KeySchema:
- AttributeName: instance_id
KeyType: HASH
- AttributeName: compliance_id
KeyType: RANGE
BillingMode: 'PAY_PER_REQUEST'
SAPConfgHltChkTableMetaData:
Type: 'AWS::DynamoDB::Table'
Properties:
TableName: SAPConfgHltChkMetaData
AttributeDefinitions:
- AttributeName: instance_id
AttributeType: S
- AttributeName: instance_no
AttributeType: S
KeySchema:
- AttributeName: instance_id
KeyType: HASH
- AttributeName: instance_no
KeyType: RANGE
BillingMode: 'PAY_PER_REQUEST'
SAPConfigHltSchedule:
Type: AWS::Events::Rule
Properties:
Name: SAPConfigHltSchedule
Description: Scheduler for SAP Configuration Health Checks.
ScheduleExpression: "rate(1 day)" # Adjust the schedule expression as needed
State: DISABLED
Targets:
- Id: "SAPConfgHltChkMain"
Arn: !GetAtt SAPConfgHltChkMain.Arn
Input: '{"aws-sap-instance-ids": ["instanceid1", "instanceid2"]}'