-
Notifications
You must be signed in to change notification settings - Fork 69
/
Phone_number_validate.yaml
604 lines (551 loc) · 20.1 KB
/
Phone_number_validate.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
AWSTemplateFormatVersion: 2010-09-09
Description: Amazon Pinpoint Phone Number Validate
Parameters:
PinpointProjectId:
Type: String
Description: Amazon Pinpoint Project ID to perform validation against
TempExportS3Bucket:
Type: String
Description: Name of the existing Amazon S3 Bucket where Pinpoint export files can be placed for validation.
TempExportS3Prefix:
Type: String
Description: Prefix of the Amazon S3 Bucket where new export files will be placed.
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:
PhoneNotValidatedSegment:
Type: 'AWS::Pinpoint::Segment'
Properties:
ApplicationId: !Ref PinpointProjectId
SegmentGroups:
Include: ALL
Groups:
- Type: NONE
Dimensions:
-
Attributes:
PNV_PhoneNumberValidated:
AttributeType: "INCLUSIVE"
Values:
- "Yes"
SourceType: ALL
- Type: ANY
Dimensions:
-
Demographic:
Channel:
DimensionType: INCLUSIVE
Values:
- "SMS"
- "VOICE"
Name: Needs Phone Number Validated
ExportPinpointEndpointsLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ExportPinpointEndpointsLambdaRole.Arn
Runtime: python3.7
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
PINPOINT_PROJECT_ID: !Ref PinpointProjectId
ROLE_ARN: !GetAtt PinpointExportRole.Arn
EXPORT_SEGMENT_ID: !GetAtt PhoneNotValidatedSegment.SegmentId
S3_BUCKET: !Ref TempExportS3Bucket
S3_PREFIX: !Ref TempExportS3Prefix
Code:
ZipFile: |
import boto3
import os
import random
import string
import logging
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)
random_prefix = ''.join(random.choice(string.ascii_lowercase) for i in range(10))
full_prefix = os.environ.get('S3_PREFIX') + '/' + random_prefix
s3_url = 's3://' + os.environ.get('S3_BUCKET') + '/' + full_prefix
response = client.create_export_job(
ApplicationId=os.environ.get('PINPOINT_PROJECT_ID'),
ExportJobRequest={
'RoleArn': os.environ.get('ROLE_ARN'),
'S3UrlPrefix': s3_url,
'SegmentId': os.environ.get('EXPORT_SEGMENT_ID')
}
)
logging.info(response)
return {
'ExportJobId': response['ExportJobResponse']['Id'],
'S3_FULL_PREFIX': full_prefix
}
ExportStatusLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ExportStatusLambdaRole.Arn
Runtime: python3.7
Timeout: 60
Environment:
Variables:
LOG_LEVEL: "INFO"
PINPOINT_PROJECT_ID: !Ref PinpointProjectId
Code:
ZipFile: |
import boto3
import os
import logging
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)
response = client.get_export_job(
ApplicationId=os.environ.get('PINPOINT_PROJECT_ID'),
JobId=event['ExportJobId']
)
logging.info(response)
return {
'ExportJobStatus': response['ExportJobResponse']['JobStatus'],
'ExportJobId': response['ExportJobResponse']['Id'],
'S3URL': response['ExportJobResponse']['Definition']['S3UrlPrefix'],
'S3_FULL_PREFIX': event['S3_FULL_PREFIX']
}
ValidatePhoneLambda:
Type: AWS::Lambda::Function
Properties:
Handler: index.lambda_handler
Role: !GetAtt ValidatePhoneLambdaRole.Arn
Runtime: python3.7
Timeout: 300
Environment:
Variables:
LOG_LEVEL: "INFO"
PINPOINT_PROJECT_ID: !Ref PinpointProjectId
ASSUME_US: !Ref AssumeUS
S3_BUCKET: !Ref TempExportS3Bucket
Code:
ZipFile: |
import boto3
import os
import json
import codecs
import logging
import gzip
from io import BytesIO
s3r = boto3.resource('s3')
s3c = boto3.client('s3')
client = boto3.client('pinpoint')
assume_us = os.environ["ASSUME_US"].lower() == "true"
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)
response = s3c.list_objects_v2(
Bucket=os.environ.get('S3_BUCKET'),
Prefix=event['S3_FULL_PREFIX']
)
logging.info(response)
validate_count = 0
for content in response['Contents']:
s3_key = content['Key']
if not s3_key.endswith('.gz'):
continue
logging.info(s3_key)
# Upload new version extract from gz
s3c.upload_fileobj(
Fileobj=gzip.GzipFile( None, 'rb',
fileobj=BytesIO(s3c.get_object(Bucket=os.environ.get('S3_BUCKET'), Key=s3_key)['Body'].read())),
Bucket=os.environ.get('S3_BUCKET'),
Key=s3_key + ".json")
# Read in json version
iterator = s3r.Object(os.environ.get('S3_BUCKET'), s3_key + ".json").get()['Body'].iter_lines()
for line in iterator:
endpoint = json.loads(line)
logging.info('Got Endpoint')
logging.info(endpoint)
response = client.phone_number_validate(
NumberValidateRequest={
'PhoneNumber': get_number(endpoint['Address'])
}
)
pnv_response = response['NumberValidateResponse']
update_response = client.update_endpoint(
ApplicationId=os.environ.get('PINPOINT_PROJECT_ID'),
EndpointId=endpoint['Id'],
EndpointRequest={
'Address': pnv_response['CleansedPhoneNumberE164'],
'Attributes': {
'PNV_PhoneNumberValidated': ['Yes'],
'PNV_OriginalPhoneNumber': [endpoint['Address']],
'PNV_Carrier': [pnv_response['Carrier'] if 'Carrier' in pnv_response else 'Unknown'],
'PNV_City': [pnv_response['City'] if 'City' in pnv_response else 'Unknown'],
'PNV_Country': [pnv_response['Country'] if 'Country' in pnv_response else 'Unknown'],
'PNV_CountryCodeIso2': [pnv_response['CountryCodeIso2'] if 'CountryCodeIso2' in pnv_response else 'Unknown'],
'PNV_PhoneType': [pnv_response['PhoneType'] if 'PhoneType' in pnv_response else 'Unknown'],
'PNV_Timezone': [pnv_response['Timezone'] if 'Timezone' in pnv_response else 'Unknown'],
'PNV_ZipCode': [pnv_response['ZipCode'] if 'ZipCode' in pnv_response else 'Unknown']
}
}
)
logging.info(update_response)
validate_count = validate_count + 1
return {
'TotalPhoneNumbersValidated' : validate_count
}
def get_number(address):
if assume_us and get_numeric(address) == 10:
return "+1"+address
return address
def get_numeric(str):
import re
temp = re.findall(r'\d+', str)
res = ''.join(temp)
return len(res)
PinpointValidateNotificationTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: 'PinpointPhoneValidateNotifications'
KmsMasterKeyId: alias/aws/sns
PhoneValidateStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
RoleArn: !GetAtt StateMachineRole.Arn
DefinitionString:
!Sub
- |-
{
"StartAt": "ExportPinpointEndpoints",
"States": {
"ExportPinpointEndpoints": {
"Type": "Task",
"Resource": "${ExportPinpointEndpointsArn}",
"Next": "ExportWait"
},
"ExportWait": {
"Type": "Wait",
"Seconds": 30,
"Next": "ExportStatus"
},
"ExportStatus": {
"Type": "Task",
"Resource": "${ExportStatusArn}",
"Next": "IsExportFinished"
},
"IsExportFinished": {
"Type": "Choice",
"Default": "ExportWait",
"Choices": [
{
"Variable": "$.ExportJobStatus",
"StringEquals": "FAILED",
"Next": "PhoneValidateFailed"
},
{
"Variable": "$.ExportJobStatus",
"StringEquals": "COMPLETED",
"Next": "ValidatePhoneLambda"
}
]
},
"ValidatePhoneLambda": {
"Type": "Task",
"Resource": "${ValidatePhoneLambdaArn}",
"Next": "PhoneValidateSuccess"
},
"PhoneValidateSuccess": {
"Type": "Pass",
"Parameters": {
"ValidateOutput": {
"TotalPhoneNumbersValidated.$": "$.TotalPhoneNumbersValidated"
},
"ValidateInput.$": "$$.Execution.Input"
},
"Next": "EmitSuccess"
},
"EmitSuccess": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"ResultPath": null,
"Parameters": {
"TopicArn": "${SNSTopicArn}",
"Message": {
"Message": "Phone Validate Successful",
"ValidatePhoneResult.$": "$"
},
"Subject": "Amazon Pinpoint Phone Validate Successful",
"MessageAttributes": {
"notification_type": {
"DataType": "String",
"StringValue": "success"
}
}
},
"End": true
},
"PhoneValidateFailed": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "${SNSTopicArn}",
"Message": {
"Message": "Phone Validate Failed",
"ValidatePhoneResult.$": "$"
},
"Subject": "Amazon Pinpoint Phone Validate Failed",
"MessageAttributes": {
"notification_type": {
"DataType": "String",
"StringValue": "failure"
}
}
},
"End": true
}
}
}
- {ExportPinpointEndpointsArn: !GetAtt ExportPinpointEndpointsLambda.Arn, ExportStatusArn: !GetAtt ExportStatusLambda.Arn, ValidatePhoneLambdaArn: !GetAtt ValidatePhoneLambda.Arn, SNSTopicArn: !Ref PinpointValidateNotificationTopic}
ExportPinpointEndpointsLambdaRole:
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: "iam:PassRole"
Resource:
- !GetAtt PinpointExportRole.Arn
-
Effect: "Allow"
Action:
- "mobiletargeting:CreateExportJob"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}/jobs/export"
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}"
PinpointExportRole:
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:PutObject"
- "s3:GetObjectAcl"
- "s3:GetObject"
- "s3:DeleteObjectVersion"
- "s3:GetObjectTagging"
- "s3:DeleteObject"
- "s3:GetObjectVersion"
Resource:
- !Sub "arn:aws:s3:::${TempExportS3Bucket}*"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}/"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}/*"
-
Effect: "Allow"
Action:
- "s3:ListAllMyBuckets"
- "s3:GetBucketLocation"
Resource:
- !Sub "arn:aws:s3:::*"
ExportStatusLambdaRole:
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:GetExportJob"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}/jobs/export/*"
ValidatePhoneLambdaRole:
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:GetObjectAcl"
- "s3:GetObject"
- "s3:DeleteObjectVersion"
- "s3:GetObjectTagging"
- "s3:DeleteObject"
- "s3:GetObjectVersion"
- "s3:ListBucket"
Resource:
- !Sub "arn:aws:s3:::${TempExportS3Bucket}*"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}/"
- !Sub "arn:aws:s3:::${TempExportS3Bucket}/*"
-
Effect: "Allow"
Action:
- "s3:ListAllMyBuckets"
- "s3:GetBucketLocation"
Resource:
- !Sub "arn:aws:s3:::*"
-
Effect: "Allow"
Action:
- "mobiletargeting:PhoneNumberValidate"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:phone/number/validate"
-
Effect: "Allow"
Action:
- "mobiletargeting:UpdateEndpoint"
Resource:
- !Sub "arn:aws:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${PinpointProjectId}*"
StateMachineRole:
Type: AWS::IAM::Role
Metadata:
cfn_nag:
rules_to_suppress:
- id: W76
reason: Complex Role that is used for StateMachine to invoke many other lambdas
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Principal:
Service:
- "states.amazonaws.com"
Action:
- "sts:AssumeRole"
Path: "/"
Policies:
-
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "lambda:InvokeFunction"
Resource:
- !GetAtt ExportPinpointEndpointsLambda.Arn
- !GetAtt ExportStatusLambda.Arn
- !GetAtt ValidatePhoneLambda.Arn
-
Effect: "Allow"
Action: sns:Publish
Resource: !Ref PinpointValidateNotificationTopic
Outputs:
PhoneValidateStateMachineArn:
Description: The Phone Number Validate State Machine ARN
Value: !Ref PhoneValidateStateMachine
PhoneValidateNotificationTopicArn:
Description: SNS Topic used to provide updates to status
Value: !Ref PinpointValidateNotificationTopic