Templates/Blueprints/S3EventToSNSToSQS/s3tosnstosqs.ps1.txt

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
# PowerShell script file to be executed as a AWS Lambda function.
#
# When executing in Lambda the following variables will be predefined.
# $LambdaInput - A PSObject that contains the Lambda function input data.
# $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment.
#
# The last item in the PowerShell pipeline will be returned as the result of the Lambda function.
#
# To include PowerShell modules with your Lambda function, like the AWS.Tools.S3 module, add a "#Requires" statement
# indicating the module and version. If using an AWS.Tools.* module the AWS.Tools.Common module is also required.
#
# The following link contains documentation describing the structure of the S3 event object.
# https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html
#
# This example demonstrates how to process an S3 Event that follows the process:
# S3 Event -> SNS Topic -> SQS Queue -> Lambda Function
 
#Requires -Modules @{ModuleName='AWS.Tools.Common';ModuleVersion='4.0.5.0'}
#Requires -Modules @{ModuleName='AWS.Tools.S3';ModuleVersion='4.0.5.0'}
 
# Uncomment to send the input event to CloudWatch Logs
#Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)
 
foreach ($sqsRecord in $LambdaInput.Records)
{
    $sqsRecordBody = ConvertFrom-Json -InputObject $sqsRecord.body
 
    try
    {
        # If this call works, then the SNS Subscription is configured with
        # "Raw Message Delivery" = "True"
        $snsMessage = ConvertFrom-Json -InputObject $sqsRecordBody.Message
    }
    catch
    {
        # If we hit the catch statement, then the SNS Subscription is configured
        # with "Raw Message Delivery" = "False"
        $snsMessage = $sqsRecordBody
    }
 
    if ($snsMessage.Records.Count -gt 0)
    {
        # We have an array of SNS Records, lets process them
 
        foreach ($s3Event in $snsMessage.Records)
        {
            $bucket = $s3Event.s3.bucket.name
            $key = $s3Event.s3.object.key
 
            Write-Host 'Processing event for:' (ConvertTo-Json -InputObject @{Bucket = $bucket; Key = $key} -Compress)
 
            # TODO: Add logic to handle S3 event record, for example
            $obj = Get-S3Object -Bucket $bucket -Key $key
            Write-Host "Object $key is $($obj.Size) bytes"
        }
    }
    else
    {
        # We likely have an S3 Test Event, write it out to logs
        Write-Host 'SNS Message:' (ConvertTo-Json -InputObject $snsMessage -Compress)
    }
}