-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathS3_triggered_import.yaml
1135 lines (1070 loc) · 42.1 KB
/
S3_triggered_import.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
AWSTemplateFormatVersion: 2010-09-09
Description: Amazon S3 Triggered Amazon Pinpoint Import and Campaign creation (with optional phone validation)
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: "Required Parameters"
Parameters:
- PinpointProjectId
- FileDropS3Bucket
- FileDropS3Prefix
-
Label:
default: "Optional Parameters"
Parameters:
- AutoCreateCampaign
- ValidatePhone
- AssumeUS
- CampaignDelay
Parameters:
PinpointProjectId:
Type: String
Description: Amazon Pinpoint Project ID to import into. Required!
FileDropS3Bucket:
Type: String
Description: Name of the EXISTING Amazon S3 Bucket where new import files will be placed. Note that it has to be in the same region as you are running this template and the bucket should not have any existing notification configurations or they will be overwritten.
FileDropS3Prefix:
Type: String
Default: import
Description: Prefix (sub-folder name) of the Amazon S3 Bucket where new import files will be placed. Required!
CampaignDelay:
Type: Number
Default: 15
Description: Number of minutes from the time of import to send the campaign. Allows for the last minute double check and/or pause as needed. Will be saved as CreateCampaign Lambda environment variable.
AutoCreateCampaign:
Type: String
Default: False
AllowedValues:
- True
- False
Description: Choose True if you want to automatically create a campaign based on the imported file or False if you want to just import into the system. Default is False. Will be saved as ImportSegment Lambda environment variable.
ValidatePhone:
Type: String
Default: True
AllowedValues:
- True
- False
Description: Choose TRUE if you want to use Pinpoint PhoneValidate functionality or FALSE if you want to import as-is. Default is TRUE.
AssumeUS:
Type: String
Default: True
AllowedValues:
- True
- False
Description: Enter TRUE if you want to assume US (+1) phone number for any phone 10 digits long or FALSE if you want to import as-is. Default is TRUE.
Resources:
## State Machine Lambdas
##Validate Lambda
ImportSegmentLambdaValidate:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ImportSegmentLambdaValidateRole.Arn
Runtime: python3.8
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
ASSUME_US: !Ref AssumeUS
Code:
ZipFile: |
import csv
import json
import logging
import os
import boto3
def validatePinpoint(user_document_old):
pinpointClient = boto3.client('pinpoint')
if os.environ["ASSUME_US"].lower() != "false":
assume_US = True
else:
assume_US = False
user_document = json.loads(user_document_old)
logging.info(user_document)
for i in user_document:
try:
if assume_US == True and getNumeric(user_document[i]['Address']) == 10:
logging.info("Assuming US number for " +
user_document[i]['Address'])
user_document[i]['Address'] = "+1"+user_document[i]['Address']
response = pinpointClient.phone_number_validate(
NumberValidateRequest={
'PhoneNumber': user_document[i]['Address']
}
)
response_json = response['NumberValidateResponse']
except Exception as error:
logging.error('validatePinpoint error: %s' % (error))
logging.error('validatePinpoint trace: %s' %
traceback.format_exc())
response_json = {}
response_json['CountryCodeIso2'] = 'XX'
response_json['OriginalPhoneNumber'] = user_document[i]['Address']
logging.info(response_json)
user_document[i]['CleansedPhoneNumberE164'] = getValue(
'CleansedPhoneNumberE164', response_json)
user_document[i]['CountryCodeIso2'] = response_json['CountryCodeIso2']
user_document[i]['OriginalPhoneNumber'] = response_json['OriginalPhoneNumber']
user_document[i]['Timezone'] = getValue('Timezone', response_json)
user_document[i]['ZipCode'] = getValue('ZipCode', response_json)
user_document[i]['Carrier'] = getValue('Carrier', response_json)
user_document[i]['PhoneTypeCode'] = getValue(
'PhoneTypeCode', response_json)
user_document[i]['PhoneType'] = getValue('PhoneType', response_json)
return user_document
def getNumeric(str):
import re
temp = re.findall(r'\d+', str)
res = ''.join(temp)
return len(res)
def getValue(name, field):
return field[name] if name in field else "UNKNOWN"
def load_csv_from_s3(s3_data_bucket, s3_data_key):
bucket, key = s3_data_bucket, s3_data_key
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
response = obj.get()
lines = response['Body'].read().decode('utf-8-sig').splitlines()
segment_records = {}
count = 0
for row in csv.DictReader(lines):
segment_records[count] = row
count += 1
segment_records = json.dumps(segment_records)
return segment_records
def lambda_handler(event, context):
s3url = event['S3URL']
s3bucket = event['S3Bucket']
s3key = event['S3Key']
filename, extension = os.path.splitext(os.path.basename(s3url))
user_document = {}
user_document = load_csv_from_s3(s3bucket, s3key)
user_document_valid_phoneNumbers = validatePinpoint(user_document)
return user_document_valid_phoneNumbers
ImportSegmentLambdaValidateRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: "/"
Policies:
-
PolicyName: "rootValidate"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
-
Effect: "Allow"
Action:
- "s3:PutObject"
- "s3:Get*"
- "s3:List*"
Resource:
- !Sub "arn:aws:s3:::${FileDropS3Bucket}*"
- !Sub "arn:aws:s3:::${FileDropS3Bucket}"
-
Effect: "Allow"
Action:
- "mobiletargeting:GetSegmentVersion"
- "mobiletargeting:GetSegment"
- "mobiletargeting:GetSegments"
- "mobiletargeting:GetSegmentVersions"
- "mobiletargeting:CreateImportJob"
- "mobiletargeting:PhoneNumberValidate"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}*"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:phone/number/validate"
-
Effect: "Allow"
Action: "iam:PassRole"
Resource:
- !GetAtt PinpointImportRole.Arn
##end
## Save Validate
ImportSegmentLambdaSave:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ImportSegmentLambdaSaveRole.Arn
Runtime: python3.8
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
Code:
ZipFile: |
import csv
import json
import logging
import os
import boto3
def save_validate_phone_results(pinpointResponse, s3_data_bucket, original_filename):
import datetime
timestamp_date = str(datetime.datetime.now().strftime("%Y%m%d"))
pinpointResultFile = 'tmp/'+original_filename+"_"+timestamp_date+'.csv'
data_file = open("/"+pinpointResultFile, 'w')
csv_writer = csv.writer(data_file)
count = 0
for emp in pinpointResponse['records']:
if count == 0:
header = emp.keys()
csv_writer.writerow(header)
count += 1
csv_writer.writerow(emp.values())
data_file.close()
s3_client = boto3.client('s3')
s3_client.upload_file("/"+pinpointResultFile,
s3_data_bucket, pinpointResultFile)
return "s3://"+s3_data_bucket+"/"+pinpointResultFile
def lambda_handler(event, context):
response=save_validate_phone_results(event['segment_valid_structure'],event['s3bucket'],event['filename'])
return response
ImportSegmentLambdaSaveRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: "/"
Policies:
-
PolicyName: "rootSave"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
-
Effect: "Allow"
Action:
- "s3:PutObject"
- "s3:Get*"
- "s3:List*"
Resource:
- !Sub "arn:aws:s3:::${FileDropS3Bucket}*"
- !Sub "arn:aws:s3:::${FileDropS3Bucket}"
-
Effect: "Allow"
Action:
- "mobiletargeting:GetSegmentVersion"
- "mobiletargeting:GetSegment"
- "mobiletargeting:GetSegments"
- "mobiletargeting:GetSegmentVersions"
- "mobiletargeting:CreateImportJob"
- "mobiletargeting:PhoneNumberValidate"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}*"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:phone/number/validate"
-
Effect: "Allow"
Action: "iam:PassRole"
Resource:
- !GetAtt PinpointImportRole.Arn
##end
ImportSegmentLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ImportSegmentLambdaRole.Arn
Runtime: python3.8
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
APPLICATION_ID: !Ref PinpointProjectId
ROLE_ARN: !GetAtt PinpointImportRole.Arn
FILE_FORMAT: "CSV"
CREATE_CAMPAIGN: !Ref AutoCreateCampaign
VALIDATE_PHONE: !Ref ValidatePhone
ValidateFunction: !GetAtt ImportSegmentLambdaValidate.Arn
SaveValidateResult: !GetAtt ImportSegmentLambdaSave.Arn
Code:
ZipFile: |
import json
import logging
import os
import boto3
import typing
def invokeLambdaFunction(*, functionName:str=None, payload:typing.Mapping[str, str]=None):
if functionName == None:
raise Exception('ERROR: functionName parameter required')
payloadBytesArr = bytes(json.dumps(payload), encoding='utf8')
client = boto3.client('lambda')
response = client.invoke(
FunctionName=functionName,
InvocationType="RequestResponse",
Payload=payloadBytesArr
)
return json.load(response['Payload'])
def load_csv_from_s3(s3_data_bucket, s3_data_key):
bucket, key = s3_data_bucket, s3_data_key
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
response = obj.get()
lines = response['Body'].read().decode('utf-8-sig').splitlines()
segment_records = {}
count = 0
for row in csv.DictReader(lines):
segment_records[count] = row
count += 1
segment_records = json.dumps(segment_records)
return segment_records
def map_to_segment(segment_local_file):
import copy
value_list = []
for new_key in range(0, len(segment_local_file)):
valid_json = {}
str_key = str(new_key)
for key, value in segment_local_file[str_key].items():
if key == 'PhoneType':
if value == 'INVALID' or segment_local_file[str_key]['CleansedPhoneNumberE164'] == "UNKNOWN":
valid_json['Attributes.Endpoint'] = 'INVALID'
valid_json['OptOut'] = 'ALL'
valid_json['Address'] = segment_local_file[str_key]['OriginalPhoneNumber']
valid_json['Location.Country'] = "XX"
else:
valid_json['Attributes.Endpoint'] = 'VALID'
valid_json['OptOut'] = segment_local_file[str_key]["OptOut"] if "OptOut" in segment_local_file[str_key] else "NONE"
valid_json['Address'] = segment_local_file[str_key]['CleansedPhoneNumberE164']
valid_json['Location.Country'] = segment_local_file[str_key][
'CountryCodeIso2'] if segment_local_file[str_key]['CountryCodeIso2'] != "UNKNOWN" else "XX"
name = key
if 'Attributes.' not in key and key not in ["Address", "ChannelType", "OptOut", "null"]:
name = 'Attributes.'+key
if key != "null":
valid_json[name] = value
value_json_new = copy.deepcopy(valid_json)
value_list.append(value_json_new)
return_json = {"records": value_list}
return return_json
def lambda_handler(event, context):
if os.environ["VALIDATE_PHONE"].lower() != "false":
validate_phone = True
else:
validate_phone = False
s3url = event['S3URL']
s3bucket = event['S3Bucket']
filename, extension = os.path.splitext(os.path.basename(s3url))
if validate_phone:
user_document_valid_phoneNumbers = invokeLambdaFunction(
functionName=os.environ["ValidateFunction"], payload=event)
segment_valid_structure = map_to_segment(
user_document_valid_phoneNumbers)
event_save = {"segment_valid_structure": segment_valid_structure,
"s3bucket": s3bucket, "filename": filename}
s3url = invokeLambdaFunction(
functionName=os.environ["SaveValidateResult"], payload=event_save)
client = boto3.client('pinpoint')
response = client.create_import_job(
ApplicationId=os.environ.get('APPLICATION_ID'),
ImportJobRequest={
'DefineSegment': True,
'Format': os.environ.get('FILE_FORMAT'),
'RoleArn': os.environ.get('ROLE_ARN'),
'S3Url': s3url,
'SegmentName': filename
}
)
return {
'ImportId': response['ImportJobResponse']['Id'],
'SegmentId': response['ImportJobResponse']['Definition']['SegmentId'],
'ExternalId': response['ImportJobResponse']['Definition']['ExternalId'],
'create_campaign': os.environ["CREATE_CAMPAIGN"].lower()
}
ImportSegmentLambdaRole:
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: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
-
Effect: "Allow"
Action:
- "s3:PutObject"
- "s3:Get*"
- "s3:List*"
Resource:
- !Sub "arn:aws:s3:::${FileDropS3Bucket}*"
- !Sub "arn:aws:s3:::${FileDropS3Bucket}"
-
Effect: "Allow"
Action:
- "mobiletargeting:GetSegmentVersion"
- "mobiletargeting:GetSegment"
- "mobiletargeting:GetSegments"
- "mobiletargeting:GetSegmentVersions"
- "mobiletargeting:CreateImportJob"
- "mobiletargeting:PhoneNumberValidate"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}*"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:phone/number/validate"
-
Effect: "Allow"
Action: "iam:PassRole"
Resource:
- !GetAtt PinpointImportRole.Arn
-
Effect: "Allow"
Action:
- "lambda:InvokeFunction"
Resource:
- !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${ImportSegmentLambdaValidate}"
- !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${ImportSegmentLambdaSave}"
PinpointImportRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- pinpoint.amazonaws.com
Action:
- 'sts:AssumeRole'
Path: "/"
Policies:
-
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action:
- "s3:Get*"
- "s3:List*"
Resource:
- !Sub "arn:aws:s3:::${FileDropS3Bucket}*"
- !Sub "arn:aws:s3:::${FileDropS3Bucket}"
ImportSegmentStatusLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ImportSegmentStatusLambdaRole.Arn
Runtime: python3.8
Timeout: 60
Environment:
Variables:
APPLICATION_ID: !Ref PinpointProjectId
Code:
ZipFile: |
import boto3
import time
import os
import logging
import traceback
import json
client = boto3.client('pinpoint')
def lambda_handler(event, context):
global log_level
log_level = str(os.environ.get('LOG_LEVEL')).upper()
if log_level not in [
'DEBUG', 'INFO',
'WARNING', 'ERROR',
'CRITICAL'
]:
log_level = 'ERROR'
logging.getLogger().setLevel(log_level)
logging.info(event)
create_campaign = event['create_campaign']
response = client.get_import_job(
ApplicationId=os.environ.get('APPLICATION_ID'),
JobId=event['ImportId']
)
logging.info(response)
return {
'ImportId': response['ImportJobResponse']['Id'],
'SegmentId': response['ImportJobResponse']['Definition']['SegmentId'],
'ExternalId': response['ImportJobResponse']['Definition']['ExternalId'],
'Status': response['ImportJobResponse']['JobStatus'],
'ResponseFormatted': response['ImportJobResponse'],
'create_campaign' : create_campaign
}
ImportSegmentStatusLambdaRole:
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: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
-
Effect: "Allow"
Action:
- "mobiletargeting:GetImportJob"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}/jobs/import/*"
##Create Campaign
CreateCampaignLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt CreateCampaignLambdaRole.Arn
Runtime: python3.8
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
CAMPAIGN_DELAY: !Ref CampaignDelay
Code:
ZipFile: |
import boto3
import datetime
import json
import os
import logging
import traceback
client = boto3.client('pinpoint')
def lambda_handler(event, context):
global log_level
log_level = str(os.environ.get('LOG_LEVEL')).upper()
if log_level not in [
'DEBUG', 'INFO',
'WARNING', 'ERROR',
'CRITICAL'
]:
log_level = 'ERROR'
logging.getLogger().setLevel(log_level)
logging.info(event)
delay = int(os.environ.get('CAMPAIGN_DELAY'))
segment_id = event['SegmentId']
segment_name = event['ResponseFormatted']['Definition']['SegmentName']
application_id = event['ResponseFormatted']['ApplicationId']
import_info = event['ResponseFormatted']
StartTime = (datetime.datetime.now() +
datetime.timedelta(minutes=delay)).isoformat()
try:
response = client.create_campaign(
ApplicationId=application_id,
WriteCampaignRequest={
"HoldoutPercent": 0,
"IsPaused": False,
"MessageConfiguration": {
"SMSMessage": {
"Body": "This is just a test...",
"MessageType": "TRANSACTIONAL"
}
},
"Name": segment_name,
"Schedule": {
"IsLocalTime": False,
"StartTime": StartTime,
"Frequency": "ONCE",
"Timezone": "UTC"
},
"SegmentId": segment_id
}
)
logging.info(response)
return {
'CampaignId': response['CampaignResponse']['Id'],
'SegmentId': response['CampaignResponse']['SegmentId'],
'CampaignState': response['CampaignResponse']['State']['CampaignStatus'],
'ImportInfo': import_info
}
except Exception as error:
logging.error('lambda_handler error: %s' % (error))
logging.error('lambda_handler trace: %s' % traceback.format_exc())
result = {
'statusCode': '500',
'body': {'message': 'error'}
}
return json.dumps(result)
CreateCampaignLambdaRole:
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: !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:*"
-
Effect: "Allow"
Action:
- "mobiletargeting:CreateCampaign"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}"
## State Machine
PinpointImportNotificationTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: 'PinpointImportNotifications'
ImportStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
RoleArn: !GetAtt ImportStateMachineRole.Arn
DefinitionString:
!Sub
- |-
{
"StartAt": "SendStartNotification",
"States": {
"SendStartNotification": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "${SNSTopicArn}",
"Message": {
"Message": "Import Started",
"Input.$": "$"
},
"Subject": "Amazon Pinpoint Import Started",
"MessageAttributes": {
"notification_type": {
"DataType": "String",
"StringValue": "started"
}
}
},
"ResultPath": null,
"Next": "ImportSegment"
},
"ImportSegment": {
"Type": "Task",
"Resource": "${ImportSegmentArn}",
"Next": "ImportSegmentWait"
},
"ImportSegmentWait": {
"Type": "Wait",
"Seconds": 5,
"Next": "ImportSegmentStatus"
},
"ImportSegmentStatus": {
"Type": "Task",
"Resource": "${ImportSegmentStatusArn}",
"Next": "IsImportSegmentFinished"
},
"IsImportSegmentFinished": {
"Type": "Choice",
"Default": "ImportSegmentWait",
"Choices": [
{
"Variable": "$.Status",
"StringEquals": "FAILED",
"Next": "ImportFailed"
},
{
"And": [
{
"Variable": "$.Status",
"StringEquals": "COMPLETED"
},
{
"Variable": "$.create_campaign",
"StringEquals": "True"
}
],
"Next": "CreateCampaign"
},
{
"And": [
{
"Variable": "$.Status",
"StringEquals": "COMPLETED"
},
{
"Not": {
"Variable": "$.create_campaign",
"StringEquals": "True"
}
}
],
"Next": "ImportSuccess"
}
]
},
"CreateCampaign": {
"Type": "Task",
"Resource": "${CreateCampaignArn}",
"Next": "IsCreateCampaignFinished"
},
"IsCreateCampaignFinished": {
"Type": "Choice",
"Default": "ImportFailed",
"Choices": [
{
"Variable": "$.CampaignState",
"StringEquals": "SCHEDULED",
"Next": "ImportSuccess"
},
{
"Variable": "$.CampaignState",
"StringEquals": "INVALID",
"Next": "ImportFailed"
}
]
},
"ImportSuccess": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "${SNSTopicArn}",
"Message": {
"Message": "Import&Campaign Schedule Successful",
"Result.$": "$"
},
"Subject": "Amazon Pinpoint Import&Campaign Schedule Successful",
"MessageAttributes": {
"notification_type": {
"DataType": "String",
"StringValue": "success"
}
}
},
"ResultPath": null,
"End": true
},
"ImportFailed": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "${SNSTopicArn}",
"Message": {
"Message": "Import or Campaign Failed",
"Result.$": "$"
},
"Subject": "Amazon Pinpoint Import or Campaign Failed",
"MessageAttributes": {
"notification_type": {
"DataType": "String",
"StringValue": "failure"
}
}
},
"ResultPath": null,
"End": true
}
}
}
- {ImportSegmentArn: !GetAtt ImportSegmentLambda.Arn, ImportSegmentStatusArn: !GetAtt ImportSegmentStatusLambda.Arn, CreateCampaignArn: !GetAtt CreateCampaignLambda.Arn, SNSTopicArn: !Ref PinpointImportNotificationTopic}
ImportStateMachineRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Principal:
Service:
- "states.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
ManagedPolicyArns:
- "arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole"
Policies:
-
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "lambda:InvokeFunction"
Resource:
- !GetAtt ImportSegmentLambda.Arn
- !GetAtt ImportSegmentStatusLambda.Arn
- !GetAtt CreateCampaignLambda.Arn
-
Effect: "Allow"
Action: sns:Publish
Resource: !Ref PinpointImportNotificationTopic
## S3 Trigger Lambda
S3NotificationLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt S3NotificationLambdaFunctionRole.Arn
Runtime: python3.8
Timeout: 30
Environment:
Variables:
LOG_LEVEL: "INFO"
STATE_MACHINE_ARN: !Ref ImportStateMachine
Code:
ZipFile: |
import boto3
import time
import json
import os
import logging
import traceback
client = boto3.client('stepfunctions')
def lambda_handler(event, context):
global log_level
log_level = str(os.environ.get('LOG_LEVEL')).upper()
if log_level not in [
'DEBUG', 'INFO',
'WARNING', 'ERROR',
'CRITICAL'
]:
log_level = 'ERROR'
logging.getLogger().setLevel(log_level)
logging.info(event)
try:
for record in event['Records']:
s3url = 's3://' + \
record['s3']['bucket']['name'] + \
'/' + record['s3']['object']['key']
response = client.start_execution(
stateMachineArn=os.environ.get('STATE_MACHINE_ARN'),
name='import_run-' + time.strftime("%Y%m%d-%H%M%S"),
input=json.dumps({
'S3URL': s3url,
'S3Bucket': record['s3']['bucket']['name'],
'S3Key': record['s3']['object']['key']
})
)
logging.info(response)
return True
except Exception as error:
logging.error('lambda_handler error: %s' % (error))
logging.error('lambda_handler trace: %s' % traceback.format_exc())
result = {
'statusCode': '500',
'body': {'message': 'error'}
}
return json.dumps(result)
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !GetAtt S3NotificationLambdaFunction.Arn
Action: lambda:InvokeFunction
Principal: s3.amazonaws.com
SourceAccount: !Ref 'AWS::AccountId'
SourceArn: !Sub 'arn:aws:s3:::${FileDropS3Bucket}'
S3NotificationLambdaFunctionRole:
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: states:StartExecution
Resource: !Ref ImportStateMachine